/* Mapbox GL JS is Copyright © 2020 Mapbox and subject to the Mapbox Terms of Service ((https://www.mapbox.com/legal/tos/). */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mapboxgl = factory());
})(this, (function () { 'use strict';

/* eslint-disable */

var shared, worker, mapboxgl;
// define gets called three times: one for each chunk. we rely on the order
// they're imported to know which is which
function define(_, chunk) {
if (!shared) {
    shared = chunk;
} else if (!worker) {
    worker = chunk;
} else {
    var workerBundleString = "self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; (" + shared + ")(sharedChunk); (" + worker + ")(sharedChunk); self.onerror = null;"

    var sharedChunk = {};
    shared(sharedChunk);
    mapboxgl = chunk(sharedChunk);
    if (typeof window !== 'undefined' && window && window.URL && window.URL.createObjectURL) {
        mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
    }
}
}


define(['exports'], (function (exports) { 'use strict';

//      
/* eslint-env browser */
// shim window for the case of requiring the browser bundle in Node
var window$1 = typeof self !== 'undefined' ? self : {};

var version = "3.0.1";

//       strict
let mapboxHTTPURLRegex;
const config = {
    API_URL: 'https://api.mapbox.com',
    get API_URL_REGEX() {
        if (mapboxHTTPURLRegex == null) {
            const prodMapboxHTTPURLRegex = /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i;
            try {
                mapboxHTTPURLRegex = process.env.API_URL_REGEX != null ? new RegExp(process.env.API_URL_REGEX) : prodMapboxHTTPURLRegex;
            } catch (e) {
                mapboxHTTPURLRegex = prodMapboxHTTPURLRegex;
            }
        }
        return mapboxHTTPURLRegex;
    },
    get API_TILEJSON_REGEX() {
        // https://docs.mapbox.com/api/maps/mapbox-tiling-service/#retrieve-tilejson-metadata
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i;
    },
    get API_SPRITE_REGEX() {
        // https://docs.mapbox.com/api/maps/styles/#retrieve-a-sprite-image-or-json
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i;
    },
    get API_FONTS_REGEX() {
        // https://docs.mapbox.com/api/maps/fonts/#retrieve-font-glyph-ranges
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i;
    },
    get API_STYLE_REGEX() {
        // https://docs.mapbox.com/api/maps/styles/#retrieve-a-style
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i;
    },
    get API_CDN_URL_REGEX() {
        return /^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i;
    },
    get EVENTS_URL() {
        if (!config.API_URL) {
            return null;
        }
        try {
            const url = new URL(config.API_URL);
            if (url.hostname === 'api.mapbox.cn') {
                return 'https://events.mapbox.cn/events/v2';
            } else if (url.hostname === 'api.mapbox.com') {
                return 'https://events.mapbox.com/events/v2';
            } else {
                return null;
            }
        } catch (e) {
            return null;
        }
    },
    SESSION_PATH: '/map-sessions/v1',
    FEEDBACK_URL: 'https://apps.mapbox.com/feedback',
    TILE_URL_VERSION: 'v4',
    RASTER_URL_PREFIX: 'raster/v1',
    REQUIRE_ACCESS_TOKEN: true,
    ACCESS_TOKEN: null,
    DEFAULT_STYLE: 'mapbox://styles/mapbox/standard',
    MAX_PARALLEL_IMAGE_REQUESTS: 16,
    DRACO_URL: 'https://api.mapbox.com/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm',
    GLYPHS_URL: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'
};

//       strict
const exported$2 = {
    supported: false,
    testSupport
};
let glForTesting;
let webpCheckComplete = false;
let webpImgTest;
let webpImgTestOnloadComplete = false;
if (window$1.document) {
    webpImgTest = window$1.document.createElement('img');
    webpImgTest.onload = function () {
        if (glForTesting)
            testWebpTextureUpload(glForTesting);
        glForTesting = null;
        webpImgTestOnloadComplete = true;
    };
    webpImgTest.onerror = function () {
        webpCheckComplete = true;
        glForTesting = null;
    };
    webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=';
}
function testSupport(gl) {
    if (webpCheckComplete || !webpImgTest)
        return;
    // HTMLImageElement.complete is set when an image is done loading it's source
    // regardless of whether the load was successful or not.
    // It's possible for an error to set HTMLImageElement.complete to true which would trigger
    // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp
    // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload
    // after a successful image load event.
    if (webpImgTestOnloadComplete) {
        testWebpTextureUpload(gl);
    } else {
        glForTesting = gl;
    }
}
function testWebpTextureUpload(gl) {
    // Edge 18 supports WebP but not uploading a WebP image to a gl texture
    // Test support for this before allowing WebP images.
    // https://github.com/mapbox/mapbox-gl-js/issues/7671
    const texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    try {
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest);
        // The error does not get triggered in Edge if the context is lost
        if (gl.isContextLost())
            return;
        exported$2.supported = true;
    } catch (e) {
    }
    gl.deleteTexture(texture);
    webpCheckComplete = true;
}

//      
/***** START WARNING REMOVAL OR MODIFICATION OF THE
* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE  ******
* The following code is used to access Mapbox's APIs. Removal or modification
* of this code can result in higher fees and/or
* termination of your account with Mapbox.
*
* Under the Mapbox Terms of Service, you may not use this code to access Mapbox
* Mapping APIs other than through Mapbox SDKs.
*
* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps
* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/
******************************************************************************/
const SKU_ID = '01';
function createSkuToken() {
    // SKU_ID and TOKEN_VERSION are specified by an internal schema and should not change
    const TOKEN_VERSION = '1';
    const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    // sessionRandomizer is a randomized 10-digit base-62 number
    let sessionRandomizer = '';
    for (let i = 0; i < 10; i++) {
        sessionRandomizer += base62chars[Math.floor(Math.random() * 62)];
    }
    const expiration = 12 * 60 * 60 * 1000;
    // 12 hours
    const token = [
        TOKEN_VERSION,
        SKU_ID,
        sessionRandomizer
    ].join('');
    const tokenExpiresAt = Date.now() + expiration;
    return {
        token,
        tokenExpiresAt
    };
}
    /***** END WARNING - REMOVAL OR MODIFICATION OF THE
PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE  ******/

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var unitbezier = UnitBezier;
function UnitBezier(p1x, p1y, p2x, p2y) {
    // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
    this.cx = 3 * p1x;
    this.bx = 3 * (p2x - p1x) - this.cx;
    this.ax = 1 - this.cx - this.bx;
    this.cy = 3 * p1y;
    this.by = 3 * (p2y - p1y) - this.cy;
    this.ay = 1 - this.cy - this.by;
    this.p1x = p1x;
    this.p1y = p1y;
    this.p2x = p2x;
    this.p2y = p2y;
}
UnitBezier.prototype = {
    sampleCurveX: function (t) {
        // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
        return ((this.ax * t + this.bx) * t + this.cx) * t;
    },
    sampleCurveY: function (t) {
        return ((this.ay * t + this.by) * t + this.cy) * t;
    },
    sampleCurveDerivativeX: function (t) {
        return (3 * this.ax * t + 2 * this.bx) * t + this.cx;
    },
    solveCurveX: function (x, epsilon) {
        if (epsilon === undefined)
            epsilon = 0.000001;
        if (x < 0)
            return 0;
        if (x > 1)
            return 1;
        var t = x;
        // First try a few iterations of Newton's method - normally very fast.
        for (var i = 0; i < 8; i++) {
            var x2 = this.sampleCurveX(t) - x;
            if (Math.abs(x2) < epsilon)
                return t;
            var d2 = this.sampleCurveDerivativeX(t);
            if (Math.abs(d2) < 0.000001)
                break;
            t = t - x2 / d2;
        }
        // Fall back to the bisection method for reliability.
        var t0 = 0;
        var t1 = 1;
        t = x;
        for (i = 0; i < 20; i++) {
            x2 = this.sampleCurveX(t);
            if (Math.abs(x2 - x) < epsilon)
                break;
            if (x > x2) {
                t0 = t;
            } else {
                t1 = t;
            }
            t = (t1 - t0) * 0.5 + t0;
        }
        return t;
    },
    solve: function (x, epsilon) {
        return this.sampleCurveY(this.solveCurveX(x, epsilon));
    }
};

var UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs(unitbezier);

var pointGeometry = Point$1;
/**
 * A standalone point geometry with useful accessor, comparison, and
 * modification methods.
 *
 * @class Point
 * @param {Number} x the x-coordinate. this could be longitude or screen
 * pixels, or any other sort of unit.
 * @param {Number} y the y-coordinate. this could be latitude or screen
 * pixels, or any other sort of unit.
 * @example
 * var point = new Point(-77, 38);
 */
function Point$1(x, y) {
    this.x = x;
    this.y = y;
}
Point$1.prototype = {
    /**
     * Clone this point, returning a new point that can be modified
     * without affecting the old one.
     * @return {Point} the clone
     */
    clone: function () {
        return new Point$1(this.x, this.y);
    },
    /**
     * Add this point's x & y coordinates to another point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    add: function (p) {
        return this.clone()._add(p);
    },
    /**
     * Subtract this point's x & y coordinates to from point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    sub: function (p) {
        return this.clone()._sub(p);
    },
    /**
     * Multiply this point's x & y coordinates by point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    multByPoint: function (p) {
        return this.clone()._multByPoint(p);
    },
    /**
     * Divide this point's x & y coordinates by point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    divByPoint: function (p) {
        return this.clone()._divByPoint(p);
    },
    /**
     * Multiply this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {Point} k factor
     * @return {Point} output point
     */
    mult: function (k) {
        return this.clone()._mult(k);
    },
    /**
     * Divide this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {Point} k factor
     * @return {Point} output point
     */
    div: function (k) {
        return this.clone()._div(k);
    },
    /**
     * Rotate this point around the 0, 0 origin by an angle a,
     * given in radians
     * @param {Number} a angle to rotate around, in radians
     * @return {Point} output point
     */
    rotate: function (a) {
        return this.clone()._rotate(a);
    },
    /**
     * Rotate this point around p point by an angle a,
     * given in radians
     * @param {Number} a angle to rotate around, in radians
     * @param {Point} p Point to rotate around
     * @return {Point} output point
     */
    rotateAround: function (a, p) {
        return this.clone()._rotateAround(a, p);
    },
    /**
     * Multiply this point by a 4x1 transformation matrix
     * @param {Array<Number>} m transformation matrix
     * @return {Point} output point
     */
    matMult: function (m) {
        return this.clone()._matMult(m);
    },
    /**
     * Calculate this point but as a unit vector from 0, 0, meaning
     * that the distance from the resulting point to the 0, 0
     * coordinate will be equal to 1 and the angle from the resulting
     * point to the 0, 0 coordinate will be the same as before.
     * @return {Point} unit vector point
     */
    unit: function () {
        return this.clone()._unit();
    },
    /**
     * Compute a perpendicular point, where the new y coordinate
     * is the old x coordinate and the new x coordinate is the old y
     * coordinate multiplied by -1
     * @return {Point} perpendicular point
     */
    perp: function () {
        return this.clone()._perp();
    },
    /**
     * Return a version of this point with the x & y coordinates
     * rounded to integers.
     * @return {Point} rounded point
     */
    round: function () {
        return this.clone()._round();
    },
    /**
     * Return the magitude of this point: this is the Euclidean
     * distance from the 0, 0 coordinate to this point's x and y
     * coordinates.
     * @return {Number} magnitude
     */
    mag: function () {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    },
    /**
     * Judge whether this point is equal to another point, returning
     * true or false.
     * @param {Point} other the other point
     * @return {boolean} whether the points are equal
     */
    equals: function (other) {
        return this.x === other.x && this.y === other.y;
    },
    /**
     * Calculate the distance from this point to another point
     * @param {Point} p the other point
     * @return {Number} distance
     */
    dist: function (p) {
        return Math.sqrt(this.distSqr(p));
    },
    /**
     * Calculate the distance from this point to another point,
     * without the square root step. Useful if you're comparing
     * relative distances.
     * @param {Point} p the other point
     * @return {Number} distance
     */
    distSqr: function (p) {
        var dx = p.x - this.x, dy = p.y - this.y;
        return dx * dx + dy * dy;
    },
    /**
     * Get the angle from the 0, 0 coordinate to this point, in radians
     * coordinates.
     * @return {Number} angle
     */
    angle: function () {
        return Math.atan2(this.y, this.x);
    },
    /**
     * Get the angle from this point to another point, in radians
     * @param {Point} b the other point
     * @return {Number} angle
     */
    angleTo: function (b) {
        return Math.atan2(this.y - b.y, this.x - b.x);
    },
    /**
     * Get the angle between this point and another point, in radians
     * @param {Point} b the other point
     * @return {Number} angle
     */
    angleWith: function (b) {
        return this.angleWithSep(b.x, b.y);
    },
    /*
     * Find the angle of the two vectors, solving the formula for
     * the cross product a x b = |a||b|sin(θ) for θ.
     * @param {Number} x the x-coordinate
     * @param {Number} y the y-coordinate
     * @return {Number} the angle in radians
     */
    angleWithSep: function (x, y) {
        return Math.atan2(this.x * y - this.y * x, this.x * x + this.y * y);
    },
    _matMult: function (m) {
        var x = m[0] * this.x + m[1] * this.y, y = m[2] * this.x + m[3] * this.y;
        this.x = x;
        this.y = y;
        return this;
    },
    _add: function (p) {
        this.x += p.x;
        this.y += p.y;
        return this;
    },
    _sub: function (p) {
        this.x -= p.x;
        this.y -= p.y;
        return this;
    },
    _mult: function (k) {
        this.x *= k;
        this.y *= k;
        return this;
    },
    _div: function (k) {
        this.x /= k;
        this.y /= k;
        return this;
    },
    _multByPoint: function (p) {
        this.x *= p.x;
        this.y *= p.y;
        return this;
    },
    _divByPoint: function (p) {
        this.x /= p.x;
        this.y /= p.y;
        return this;
    },
    _unit: function () {
        this._div(this.mag());
        return this;
    },
    _perp: function () {
        var y = this.y;
        this.y = this.x;
        this.x = -y;
        return this;
    },
    _rotate: function (angle) {
        var cos = Math.cos(angle), sin = Math.sin(angle), x = cos * this.x - sin * this.y, y = sin * this.x + cos * this.y;
        this.x = x;
        this.y = y;
        return this;
    },
    _rotateAround: function (angle, p) {
        var cos = Math.cos(angle), sin = Math.sin(angle), x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);
        this.x = x;
        this.y = y;
        return this;
    },
    _round: function () {
        this.x = Math.round(this.x);
        this.y = Math.round(this.y);
        return this;
    }
};
/**
 * Construct a point from an array if necessary, otherwise if the input
 * is already a Point, or an unknown type, return it unchanged
 * @param {Array<Number>|Point|*} a any kind of input value
 * @return {Point} constructed point, or passed-through value.
 * @example
 * // this
 * var point = Point.convert([0, 1]);
 * // is equivalent to
 * var point = new Point(0, 1);
 */
Point$1.convert = function (a) {
    if (a instanceof Point$1) {
        return a;
    }
    if (Array.isArray(a)) {
        return new Point$1(a[0], a[1]);
    }
    return a;
};

var Point$2 = /*@__PURE__*/getDefaultExportFromCjs(pointGeometry);

//      
/**
 * Deeply compares two object literals.
 *
 * @private
 */
function deepEqual(a, b) {
    if (Array.isArray(a)) {
        if (!Array.isArray(b) || a.length !== b.length)
            return false;
        for (let i = 0; i < a.length; i++) {
            if (!deepEqual(a[i], b[i]))
                return false;
        }
        return true;
    }
    if (typeof a === 'object' && a !== null && b !== null) {
        if (!(typeof b === 'object'))
            return false;
        const keys = Object.keys(a);
        if (keys.length !== Object.keys(b).length)
            return false;
        for (const key in a) {
            if (!deepEqual(a[key], b[key]))
                return false;
        }
        return true;
    }
    return a === b;
}

//      
const DEG_TO_RAD = Math.PI / 180;
const RAD_TO_DEG = 180 / Math.PI;
/**
 * Converts an angle in degrees to radians
 * copy all properties from the source objects into the destination.
 * The last source object given overrides properties from previous
 * source objects.
 *
 * @param a angle to convert
 * @returns the angle in radians
 * @private
 */
function degToRad(a) {
    return a * DEG_TO_RAD;
}
/**
 * Converts an angle in radians to degrees
 * copy all properties from the source objects into the destination.
 * The last source object given overrides properties from previous
 * source objects.
 *
 * @param a angle to convert
 * @returns the angle in degrees
 * @private
 */
function radToDeg(a) {
    return a * RAD_TO_DEG;
}
const TILE_CORNERS = [
    [
        0,
        0
    ],
    [
        1,
        0
    ],
    [
        1,
        1
    ],
    [
        0,
        1
    ]
];
/**
 * Given a particular bearing, returns the corner of the tile thats farthest
 * along the bearing.
 *
 * @param {number} bearing angle in degrees (-180, 180]
 * @returns {QuadCorner}
 * @private
 */
function furthestTileCorner(bearing) {
    const alignedBearing = (bearing + 45 + 360) % 360;
    const cornerIdx = Math.round(alignedBearing / 90) % 4;
    return TILE_CORNERS[cornerIdx];
}
/**
 * @module util
 * @private
 */
/**
 * Given a value `t` that varies between 0 and 1, return
 * an interpolation function that eases between 0 and 1 in a pleasing
 * cubic in-out fashion.
 *
 * @private
 */
function easeCubicInOut(t) {
    if (t <= 0)
        return 0;
    if (t >= 1)
        return 1;
    const t2 = t * t, t3 = t2 * t;
    return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75);
}
/**
 * Computes an AABB for a set of points.
 *
 * @param {Point[]} points
 * @returns {{ min: Point, max: Point}}
 * @private
 */
function getBounds(points) {
    let minX = Infinity;
    let minY = Infinity;
    let maxX = -Infinity;
    let maxY = -Infinity;
    for (const p of points) {
        minX = Math.min(minX, p.x);
        minY = Math.min(minY, p.y);
        maxX = Math.max(maxX, p.x);
        maxY = Math.max(maxY, p.y);
    }
    return {
        min: new Point$2(minX, minY),
        max: new Point$2(maxX, maxY)
    };
}
/**
 * Returns the square of the 2D distance between an AABB defined by min and max and a point.
 * If point is null or undefined, the AABB distance from the origin (0,0) is returned.
 *
 * @param {Array<number>} min The minimum extent of the AABB.
 * @param {Array<number>} max The maximum extent of the AABB.
 * @param {Array<number>} [point] The point to compute the distance from, may be undefined.
 * @returns {number} The square distance from the AABB, 0.0 if the AABB contains the point.
 */
function getAABBPointSquareDist(min, max, point) {
    let sqDist = 0;
    for (let i = 0; i < 2; ++i) {
        const v = point ? point[i] : 0;
        if (min[i] > v)
            sqDist += (min[i] - v) * (min[i] - v);
        if (max[i] < v)
            sqDist += (v - max[i]) * (v - max[i]);
    }
    return sqDist;
}
/**
 * Converts a AABB into a polygon with clockwise winding order.
 *
 * @param {Point} min The top left point.
 * @param {Point} max The bottom right point.
 * @param {number} [buffer=0] The buffer width.
 * @param {boolean} [close=true] Whether to close the polygon or not.
 * @returns {Point[]} The polygon.
 */
function polygonizeBounds(min, max, buffer = 0, close = true) {
    const offset = new Point$2(buffer, buffer);
    const minBuf = min.sub(offset);
    const maxBuf = max.add(offset);
    const polygon = [
        minBuf,
        new Point$2(maxBuf.x, minBuf.y),
        maxBuf,
        new Point$2(minBuf.x, maxBuf.y)
    ];
    if (close) {
        polygon.push(minBuf.clone());
    }
    return polygon;
}
/**
 * Takes a convex ring and expands it outward by applying a buffer around it.
 * This function assumes that the ring is in clockwise winding order.
 *
 * @param {Point[]} ring The input ring.
 * @param {number} buffer The buffer width.
 * @returns {Point[]} The expanded ring.
 */
function bufferConvexPolygon(ring, buffer) {
    const output = [];
    for (let currIdx = 0; currIdx < ring.length; currIdx++) {
        const prevIdx = wrap$1(currIdx - 1, -1, ring.length - 1);
        const nextIdx = wrap$1(currIdx + 1, -1, ring.length - 1);
        const prev = ring[prevIdx];
        const curr = ring[currIdx];
        const next = ring[nextIdx];
        const p1 = prev.sub(curr).unit();
        const p2 = next.sub(curr).unit();
        const interiorAngle = p2.angleWithSep(p1.x, p1.y);
        // Calcuate a vector that points in the direction of the angle bisector between two sides.
        // Scale it based on a right angled triangle constructed at that corner.
        const offset = p1.add(p2).unit().mult(-1 * buffer / Math.sin(interiorAngle / 2));
        output.push(curr.add(offset));
    }
    return output;
}
/**
 * Given given (x, y), (x1, y1) control points for a bezier curve,
 * return a function that interpolates along that curve.
 *
 * @param p1x control point 1 x coordinate
 * @param p1y control point 1 y coordinate
 * @param p2x control point 2 x coordinate
 * @param p2y control point 2 y coordinate
 * @private
 */
function bezier$1(p1x, p1y, p2x, p2y) {
    const bezier = new UnitBezier$1(p1x, p1y, p2x, p2y);
    return function (t) {
        return bezier.solve(t);
    };
}
/**
 * A default bezier-curve powered easing function with
 * control points (0.25, 0.1) and (0.25, 1)
 *
 * @private
 */
const ease = bezier$1(0.25, 0.1, 0.25, 1);
/**
 * constrain n to the given range via min + max
 *
 * @param n value
 * @param min the minimum value to be returned
 * @param max the maximum value to be returned
 * @returns the clamped value
 * @private
 */
function clamp(n, min, max) {
    return Math.min(max, Math.max(min, n));
}
/**
 * Equivalent to GLSL smoothstep.
 *
 * @param {number} e0 The lower edge of the sigmoid
 * @param {number} e1 The upper edge of the sigmoid
 * @param {number} x the value to be interpolated
 * @returns {number} in the range [0, 1]
 * @private
 */
function smoothstep(e0, e1, x) {
    x = clamp((x - e0) / (e1 - e0), 0, 1);
    return x * x * (3 - 2 * x);
}
/**
 * constrain n to the given range, excluding the minimum, via modular arithmetic
 *
 * @param n value
 * @param min the minimum value to be returned, exclusive
 * @param max the maximum value to be returned, inclusive
 * @returns constrained number
 * @private
 */
function wrap$1(n, min, max) {
    const d = max - min;
    const w = ((n - min) % d + d) % d + min;
    return w === min ? max : w;
}
/**
 * Computes shortest angle in range [-180, 180) between two angles.
 *
 * @param {*} a First angle in degrees
 * @param {*} b Second angle in degrees
 * @returns Shortest angle
 * @private
 */
function shortestAngle(a, b) {
    const diff = (b - a + 180) % 360 - 180;
    return diff < -180 ? diff + 360 : diff;
}
/*
 * Call an asynchronous function on an array of arguments,
 * calling `callback` with the completed results of all calls.
 *
 * @param array input to each call of the async function.
 * @param fn an async function with signature (data, callback)
 * @param callback a callback run after all async work is done.
 * called with an array, containing the results of each async call.
 * @private
 */
function asyncAll(array, fn, callback) {
    if (!array.length) {
        return callback(null, []);
    }
    let remaining = array.length;
    const results = new Array(array.length);
    let error = null;
    array.forEach((item, i) => {
        fn(item, (err, result) => {
            if (err)
                error = err;
            results[i] = result;
            // https://github.com/facebook/flow/issues/2123
            if (--remaining === 0)
                callback(error, results);
        });
    });
}
/*
 * Polyfill for Object.values. Not fully spec compliant, but we don't
 * need it to be.
 *
 * @private
 */
function values(obj) {
    const result = [];
    for (const k in obj) {
        result.push(obj[k]);
    }
    return result;
}
/*
 * Compute the difference between the keys in one object and the keys
 * in another object.
 *
 * @returns keys difference
 * @private
 */
function keysDifference(obj, other) {
    const difference = [];
    for (const i in obj) {
        if (!(i in other)) {
            difference.push(i);
        }
    }
    return difference;
}
/**
 * Given a destination object and optionally many source objects,
 * copy all properties from the source objects into the destination.
 * The last source object given overrides properties from previous
 * source objects.
 *
 * @param dest destination object
 * @param sources sources from which properties are pulled
 * @private
 */
function extend$1(dest, ...sources) {
    for (const src of sources) {
        for (const k in src) {
            dest[k] = src[k];
        }
    }
    return dest;
}
/**
 * Given an object and a number of properties as strings, return version
 * of that object with only those properties.
 *
 * @param src the object
 * @param properties an array of property names chosen
 * to appear on the resulting object.
 * @returns object with limited properties.
 * @example
 * var foo = { name: 'Charlie', age: 10 };
 * var justName = pick(foo, ['name']);
 * // justName = { name: 'Charlie' }
 * @private
 */
function pick(src, properties) {
    const result = {};
    for (let i = 0; i < properties.length; i++) {
        const k = properties[i];
        if (k in src) {
            result[k] = src[k];
        }
    }
    return result;
}
let id = 1;
/**
 * Return a unique numeric id, starting at 1 and incrementing with
 * each call.
 *
 * @returns unique numeric id.
 * @private
 */
function uniqueId() {
    return id++;
}
/**
 * Return a random UUID (v4). Taken from: https://gist.github.com/jed/982883
 * @private
 */
function uuid() {
    function b(a) {
        return a ? (a ^ Math.random() * (16 >> a / 4)).toString(16) : //$FlowFixMe: Flow doesn't like the implied array literal conversion here
        ([10000000] + -[1000] + -4000 + -8000 + -100000000000).replace(/[018]/g, b);
    }
    return b();
}
/**
 * Return the next power of two, or the input value if already a power of two
 * @private
 */
function nextPowerOfTwo(value) {
    if (value <= 1)
        return 1;
    return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
}
/**
 * Return the previous power of two, or the input value if already a power of two
 * @private
 */
function prevPowerOfTwo(value) {
    if (value <= 1)
        return 1;
    return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
}
/**
 * Validate a string to match UUID(v4) of the
 * form: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx
 * @param str string to validate.
 * @private
 */
function validateUuid(str) {
    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;
}
/**
 * Given an array of member function names as strings, replace all of them
 * with bound versions that will always refer to `context` as `this`. This
 * is useful for classes where otherwise event bindings would reassign
 * `this` to the evented object or some other value: this lets you ensure
 * the `this` value always.
 *
 * @param fns list of member function names
 * @param context the context value
 * @example
 * function MyClass() {
 *   bindAll(['ontimer'], this);
 *   this.name = 'Tom';
 * }
 * MyClass.prototype.ontimer = function() {
 *   alert(this.name);
 * };
 * var myClass = new MyClass();
 * setTimeout(myClass.ontimer, 100);
 * @private
 */
function bindAll(fns, context) {
    fns.forEach(fn => {
        if (!context[fn]) {
            return;
        }
        context[fn] = context[fn].bind(context);
    });
}
/**
 * Determine if a string ends with a particular substring
 *
 * @private
 */
function endsWith(string, suffix) {
    return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
/**
 * Create an object by mapping all the values of an existing object while
 * preserving their keys.
 *
 * @private
 */
// $FlowFixMe[missing-this-annot]
function mapObject(input, iterator, context) {
    const output = {};
    for (const key in input) {
        output[key] = iterator.call(context || this, input[key], key, input);
    }
    return output;
}
/**
 * Create an object by filtering out values of an existing object.
 *
 * @private
 */
// $FlowFixMe[missing-this-annot]
function filterObject(input, iterator, context) {
    const output = {};
    for (const key in input) {
        if (iterator.call(context || this, input[key], key, input)) {
            output[key] = input[key];
        }
    }
    return output;
}
/**
 * Deeply clones two objects.
 *
 * @private
 */
function clone$9(input) {
    if (Array.isArray(input)) {
        return input.map(clone$9);
    } else if (typeof input === 'object' && input) {
        return mapObject(input, clone$9);
    } else {
        return input;
    }
}
/**
 * Maps a value from a range between [min, max] to the range [outMin, outMax]
 *
 * @private
 */
function mapValue(value, min, max, outMin, outMax) {
    return clamp((value - min) / (max - min) * (outMax - outMin) + outMin, outMin, outMax);
}
/**
 * Check if two arrays have at least one common element.
 *
 * @private
 */
function arraysIntersect(a, b) {
    for (let l = 0; l < a.length; l++) {
        if (b.indexOf(a[l]) >= 0)
            return true;
    }
    return false;
}
/**
 * Print a warning message to the console and ensure duplicate warning messages
 * are not printed.
 *
 * @private
 */
const warnOnceHistory = {};
function warnOnce(message) {
    if (!warnOnceHistory[message]) {
        // console isn't defined in some WebWorkers, see #2558
        if (typeof console !== 'undefined')
            console.warn(message);
        warnOnceHistory[message] = true;
    }
}
/**
 * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order
 *
 * @private
 * @returns true for a counter clockwise set of points
 */
// http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
function isCounterClockwise(a, b, c) {
    return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
}
/**
 * Returns the signed area for the polygon ring.  Postive areas are exterior rings and
 * have a clockwise winding.  Negative areas are interior rings and have a counter clockwise
 * ordering.
 *
 * @private
 * @param ring Exterior or interior ring
 */
function calculateSignedArea$1(ring) {
    let sum = 0;
    for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {
        p1 = ring[i];
        p2 = ring[j];
        sum += (p2.x - p1.x) * (p1.y + p2.y);
    }
    return sum;
}
/**
 * Converts spherical coordinates to cartesian position coordinates.
 *
 * @private
 * @param spherical Spherical coordinates, in [radial, azimuthal, polar]
 * @return Position cartesian coordinates
 */
function sphericalPositionToCartesian([r, azimuthal, polar]) {
    // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2):
    // correct for that here
    const a = degToRad(azimuthal + 90), p = degToRad(polar);
    return {
        x: r * Math.cos(a) * Math.sin(p),
        y: r * Math.sin(a) * Math.sin(p),
        z: r * Math.cos(p),
        azimuthal,
        polar
    };
}
/**
 * Converts spherical direction to cartesian coordinates.
 *
 * @private
 * @param spherical Spherical direction, in [azimuthal, polar]
 * @return Direction cartesian direction
 */
function sphericalDirectionToCartesian([azimuthal, polar]) {
    const position = sphericalPositionToCartesian([
        1,
        azimuthal,
        polar
    ]);
    return {
        x: position.x,
        y: position.y,
        z: position.z
    };
}
function cartesianPositionToSpherical(x, y, z) {
    const radial = Math.sqrt(x * x + y * y + z * z);
    const polar = radial > 0 ? Math.acos(z / radial) * RAD_TO_DEG : 0;
    // Domain error may occur if x && y are both 0.0
    let azimuthal = x !== 0 || y !== 0 ? Math.atan2(-y, -x) * RAD_TO_DEG + 90 : 0;
    if (azimuthal < 0) {
        azimuthal += 360;
    }
    return [
        radial,
        azimuthal,
        polar
    ];
}
/* global self, WorkerGlobalScope */
/**
 *  Returns true if run in the web-worker context.
 *
 * @private
 * @returns {boolean}
 */
function isWorker() {
    return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope;
}
/**
 * Parses data from 'Cache-Control' headers.
 *
 * @private
 * @param cacheControl Value of 'Cache-Control' header
 * @return object containing parsed header info.
 */
function parseCacheControl(cacheControl) {
    // Taken from [Wreck](https://github.com/hapijs/wreck)
    const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g;
    const header = {};
    cacheControl.replace(re, ($0, $1, $2, $3) => {
        const value = $2 || $3;
        header[$1] = value ? value.toLowerCase() : true;
        return '';
    });
    if (header['max-age']) {
        const maxAge = parseInt(header['max-age'], 10);
        if (isNaN(maxAge))
            delete header['max-age'];
        else
            header['max-age'] = maxAge;
    }
    return header;
}
let _isSafari = null;
/**
 * Returns true when run in WebKit derived browsers.
 * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to
 * transfer data between WebWorkers and the main thread.
 * https://github.com/mapbox/mapbox-gl-js/issues/8771
 *
 * This should be removed once the underlying Safari issue is fixed.
 *
 * @private
 * @param scope {WindowOrWorkerGlobalScope} Since this function is used both on the main thread and WebWorker context,
 *      let the calling scope pass in the global scope object.
 * @returns {boolean}
 */
function isSafari(scope) {
    if (_isSafari == null) {
        const userAgent = scope.navigator ? scope.navigator.userAgent : null;
        _isSafari = !!scope.safari || !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || !!userAgent.match('Safari') && !userAgent.match('Chrome')));
    }
    return _isSafari;
}
function isSafariWithAntialiasingBug(scope) {
    const userAgent = scope.navigator ? scope.navigator.userAgent : null;
    if (!isSafari(scope))
        return false;
    // 15.4 is known to be buggy.
    // 15.5 may or may not include the fix. Mark it as buggy to be on the safe side.
    return userAgent && (userAgent.match('Version/15.4') || userAgent.match('Version/15.5') || userAgent.match(/CPU (OS|iPhone OS) (15_4|15_5) like Mac OS X/));
}
function isFullscreen() {
    return !!window$1.document.fullscreenElement || !!window$1.document.webkitFullscreenElement;
}
function storageAvailable(type) {
    try {
        const storage = window$1[type];
        storage.setItem('_mapbox_test_', 1);
        storage.removeItem('_mapbox_test_');
        return true;
    } catch (e) {
        return false;
    }
}
// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
//Unicode compliant base64 encoder for strings
function b64EncodeUnicode(str) {
    return window$1.btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => {
        return String.fromCharCode(Number('0x' + p1));    //eslint-disable-line
    }));
}
// Unicode compliant decoder for base64-encoded strings
function b64DecodeUnicode(str) {
    return decodeURIComponent(window$1.atob(str).split('').map(c => {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);    //eslint-disable-line
    }).join(''));
}
function base64DecToArr(sBase64) {
    const str = atob(sBase64);
    const arr = new Uint8Array(str.length);
    for (let i = 0; i < str.length; i++)
        arr[i] = str.codePointAt(i);
    return arr;
}
function getColumn(matrix, col) {
    return [
        matrix[col * 4],
        matrix[col * 4 + 1],
        matrix[col * 4 + 2],
        matrix[col * 4 + 3]
    ];
}
function setColumn(matrix, col, values) {
    matrix[col * 4 + 0] = values[0];
    matrix[col * 4 + 1] = values[1];
    matrix[col * 4 + 2] = values[2];
    matrix[col * 4 + 3] = values[3];
}
function sRGBToLinearAndScale(v, s) {
    return [
        Math.pow(v[0], 2.2) * s,
        Math.pow(v[1], 2.2) * s,
        Math.pow(v[2], 2.2) * s
    ];
}
function linearVec3TosRGB(v) {
    return [
        Math.pow(v[0], 1 / 2.2),
        Math.pow(v[1], 1 / 2.2),
        Math.pow(v[2], 1 / 2.2)
    ];
}

//      
const CACHE_NAME = 'mapbox-tiles';
let cacheLimit = 500;
// 50MB / (100KB/tile) ~= 500 tiles
let cacheCheckThreshold = 50;
const MIN_TIME_UNTIL_EXPIRY = 1000 * 60 * 7;
// 7 minutes. Skip caching tiles with a short enough max age.
// We're using a global shared cache object. Normally, requesting ad-hoc Cache objects is fine, but
// Safari has a memory leak in which it fails to release memory when requesting keys() from a Cache
// object. See https://bugs.webkit.org/show_bug.cgi?id=203991 for more information.
let sharedCache;
function getCaches() {
    try {
        return window$1.caches;
    } catch (e) {
    }
}
function cacheOpen() {
    const caches = getCaches();
    if (caches && !sharedCache) {
        sharedCache = window$1.caches.open(CACHE_NAME);
    }
}
let responseConstructorSupportsReadableStream;
function prepareBody(response, callback) {
    if (responseConstructorSupportsReadableStream === undefined) {
        try {
            new Response(new ReadableStream());
            // eslint-disable-line no-undef
            responseConstructorSupportsReadableStream = true;
        } catch (e) {
            // Edge
            responseConstructorSupportsReadableStream = false;
        }
    }
    if (responseConstructorSupportsReadableStream) {
        callback(response.body);
    } else {
        response.blob().then(callback);
    }
}
function cachePut(request, response, requestTime) {
    cacheOpen();
    if (!sharedCache)
        return;
    const options = {
        status: response.status,
        statusText: response.statusText,
        headers: new window$1.Headers()
    };
    response.headers.forEach((v, k) => options.headers.set(k, v));
    const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');
    if (cacheControl['no-store']) {
        return;
    }
    if (cacheControl['max-age']) {
        options.headers.set('Expires', new Date(requestTime + cacheControl['max-age'] * 1000).toUTCString());
    }
    const expires = options.headers.get('Expires');
    if (!expires)
        return;
    const timeUntilExpiry = new Date(expires).getTime() - requestTime;
    if (timeUntilExpiry < MIN_TIME_UNTIL_EXPIRY)
        return;
    prepareBody(response, body => {
        const clonedResponse = new window$1.Response(body, options);
        cacheOpen();
        if (!sharedCache)
            return;
        sharedCache.then(cache => cache.put(stripQueryParameters(request.url), clonedResponse)).catch(e => warnOnce(e.message));
    });
}
function getQueryParameters(url) {
    const paramStart = url.indexOf('?');
    return paramStart > 0 ? url.slice(paramStart + 1).split('&') : [];
}
function stripQueryParameters(url) {
    const start = url.indexOf('?');
    if (start < 0)
        return url;
    // preserve `language` and `worldview` params if any
    const params = getQueryParameters(url);
    const filteredParams = params.filter(param => {
        const entry = param.split('=');
        return entry[0] === 'language' || entry[0] === 'worldview';
    });
    if (filteredParams.length) {
        return `${ url.slice(0, start) }?${ filteredParams.join('&') }`;
    }
    return url.slice(0, start);
}
function cacheGet(request, callback) {
    cacheOpen();
    if (!sharedCache)
        return callback(null);
    const strippedURL = stripQueryParameters(request.url);
    sharedCache.then(cache => {
        // manually strip URL instead of `ignoreSearch: true` because of a known
        // performance issue in Chrome https://github.com/mapbox/mapbox-gl-js/issues/8431
        cache.match(strippedURL).then(response => {
            const fresh = isFresh(response);
            // Reinsert into cache so that order of keys in the cache is the order of access.
            // This line makes the cache a LRU instead of a FIFO cache.
            cache.delete(strippedURL);
            if (fresh) {
                cache.put(strippedURL, response.clone());
            }
            callback(null, response, fresh);
        }).catch(callback);
    }).catch(callback);
}
function isFresh(response) {
    if (!response)
        return false;
    const expires = new Date(response.headers.get('Expires') || 0);
    const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');
    return expires > Date.now() && !cacheControl['no-cache'];
}
// `Infinity` triggers a cache check after the first tile is loaded
// so that a check is run at least once on each page load.
let globalEntryCounter = Infinity;
// The cache check gets run on a worker. The reason for this is that
// profiling sometimes shows this as taking up significant time on the
// thread it gets called from. And sometimes it doesn't. It *may* be
// fine to run this on the main thread but out of caution this is being
// dispatched on a worker. This can be investigated further in the future.
function cacheEntryPossiblyAdded(dispatcher) {
    globalEntryCounter++;
    if (globalEntryCounter > cacheCheckThreshold) {
        dispatcher.getActor().send('enforceCacheSizeLimit', cacheLimit);
        globalEntryCounter = 0;
    }
}
// runs on worker, see above comment
function enforceCacheSizeLimit(limit) {
    cacheOpen();
    if (!sharedCache)
        return;
    sharedCache.then(cache => {
        cache.keys().then(keys => {
            for (let i = 0; i < keys.length - limit; i++) {
                cache.delete(keys[i]);
            }
        });
    });
}
function clearTileCache(callback) {
    const caches = getCaches();
    if (!caches)
        return;
    const promise = window$1.caches.delete(CACHE_NAME);
    if (callback) {
        promise.catch(callback).then(() => callback());
    }
}
function setCacheLimits(limit, checkThreshold) {
    cacheLimit = limit;
    cacheCheckThreshold = checkThreshold;
}

//      
/**
 * The type of a resource.
 * @private
 * @readonly
 * @enum {string}
 */
const ResourceType = {
    Unknown: 'Unknown',
    Style: 'Style',
    Source: 'Source',
    Tile: 'Tile',
    Glyphs: 'Glyphs',
    SpriteImage: 'SpriteImage',
    SpriteJSON: 'SpriteJSON',
    Image: 'Image',
    Model: 'Model'
};
if (typeof Object.freeze == 'function') {
    Object.freeze(ResourceType);
}
/**
 * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.
 * @typedef {Object} RequestParameters
 * @property {string} url The URL to be requested.
 * @property {Object} headers The headers to be sent with the request.
 * @property {string} method Request method `'GET' | 'POST' | 'PUT'`.
 * @property {string} body Request body.
 * @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`.
 * @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.
 * @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.
 * @property {string} referrerPolicy A string representing the request's referrerPolicy. For more information and possible values, see the [Referrer-Policy HTTP header page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy).
 * @example
 * // use transformRequest to modify requests that begin with `http://myHost`
 * const map = new Map({
 *     container: 'map',
 *     style: 'mapbox://styles/mapbox/streets-v11',
 *     transformRequest: (url, resourceType) => {
 *         if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {
 *             return {
 *                 url: url.replace('http', 'https'),
 *                 headers: {'my-custom-header': true},
 *                 credentials: 'include'  // Include cookies for cross-origin requests
 *             };
 *         }
 *     }
 * });
 *
 */
class AJAXError extends Error {
    constructor(message, status, url) {
        if (status === 401 && isMapboxHTTPURL(url)) {
            message += ': you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes';
        }
        super(message);
        this.status = status;
        this.url = url;
    }
    toString() {
        return `${ this.name }: ${ this.message } (${ this.status }): ${ this.url }`;
    }
}
// Ensure that we're sending the correct referrer from blob URL worker bundles.
// For files loaded from the local file system, `location.origin` will be set
// to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge, IE),
// and we will set an empty referrer. Otherwise, we're using the document's URL.
/* global self */
const getReferrer = isWorker() ? () => self.worker && self.worker.referrer : () => (window$1.location.protocol === 'blob:' ? window$1.parent : window$1).location.href;
// Determines whether a URL is a file:// URL. This is obviously the case if it begins
// with file://. Relative URLs are also file:// URLs iff the original document was loaded
// via a file:// URL.
const isFileURL = url => /^file:/.test(url) || /^file:/.test(getReferrer()) && !/^\w+:/.test(url);
function makeFetchRequest(requestParameters, callback) {
    const controller = new window$1.AbortController();
    const request = new window$1.Request(requestParameters.url, {
        method: requestParameters.method || 'GET',
        body: requestParameters.body,
        credentials: requestParameters.credentials,
        headers: requestParameters.headers,
        referrer: getReferrer(),
        referrerPolicy: requestParameters.referrerPolicy,
        signal: controller.signal
    });
    let complete = false;
    let aborted = false;
    const cacheIgnoringSearch = hasCacheDefeatingSku(request.url);
    if (requestParameters.type === 'json') {
        request.headers.set('Accept', 'application/json');
    }
    const validateOrFetch = (err, cachedResponse, responseIsFresh) => {
        if (aborted)
            return;
        if (err) {
            // Do fetch in case of cache error.
            // HTTP pages in Edge trigger a security error that can be ignored.
            if (err.message !== 'SecurityError') {
                warnOnce(err.toString());
            }
        }
        if (cachedResponse && responseIsFresh) {
            return finishRequest(cachedResponse);
        }
        const requestTime = Date.now();
        window$1.fetch(request).then(response => {
            if (response.ok) {
                const cacheableResponse = cacheIgnoringSearch ? response.clone() : null;
                return finishRequest(response, cacheableResponse, requestTime);
            } else {
                return callback(new AJAXError(response.statusText, response.status, requestParameters.url));
            }
        }).catch(error => {
            if (error.name === 'AbortError') {
                // silence expected AbortError
                return;
            }
            callback(new Error(`${ error.message } ${ requestParameters.url }`));
        });
    };
    const finishRequest = (response, cacheableResponse, requestTime) => {
        (requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() : requestParameters.type === 'json' ? response.json() : response.text()).then(result => {
            if (aborted)
                return;
            if (cacheableResponse && requestTime) {
                // The response needs to be inserted into the cache after it has completely loaded.
                // Until it is fully loaded there is a chance it will be aborted. Aborting while
                // reading the body can cause the cache insertion to error. We could catch this error
                // in most browsers but in Firefox it seems to sometimes crash the tab. Adding
                // it to the cache here avoids that error.
                cachePut(request, cacheableResponse, requestTime);
            }
            complete = true;
            callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires'));
        }).catch(err => {
            if (!aborted)
                callback(new Error(err.message));
        });
    };
    if (cacheIgnoringSearch) {
        cacheGet(request, validateOrFetch);
    } else {
        validateOrFetch(null, null);
    }
    return {
        cancel: () => {
            aborted = true;
            if (!complete)
                controller.abort();
        }
    };
}
function makeXMLHttpRequest(requestParameters, callback) {
    const xhr = new window$1.XMLHttpRequest();
    xhr.open(requestParameters.method || 'GET', requestParameters.url, true);
    if (requestParameters.type === 'arrayBuffer') {
        xhr.responseType = 'arraybuffer';
    }
    for (const k in requestParameters.headers) {
        xhr.setRequestHeader(k, requestParameters.headers[k]);
    }
    if (requestParameters.type === 'json') {
        xhr.responseType = 'text';
        xhr.setRequestHeader('Accept', 'application/json');
    }
    xhr.withCredentials = requestParameters.credentials === 'include';
    xhr.onerror = () => {
        callback(new Error(xhr.statusText));
    };
    xhr.onload = () => {
        if ((xhr.status >= 200 && xhr.status < 300 || xhr.status === 0) && xhr.response !== null) {
            let data = xhr.response;
            if (requestParameters.type === 'json') {
                // We're manually parsing JSON here to get better error messages.
                try {
                    data = JSON.parse(xhr.response);
                } catch (err) {
                    return callback(err);
                }
            }
            callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires'));
        } else {
            callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));
        }
    };
    xhr.send(requestParameters.body);
    return { cancel: () => xhr.abort() };
}
const makeRequest = function (requestParameters, callback) {
    // We're trying to use the Fetch API if possible. However, in some situations we can't use it:
    // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in
    //   older versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2). In this case,
    //   we dispatch the request to the main thread so that we can get an accurate referrer header.
    // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In
    //   this case we unconditionally use XHR on the current thread since referrers don't matter.
    if (!isFileURL(requestParameters.url)) {
        if (window$1.fetch && window$1.Request && window$1.AbortController && window$1.Request.prototype.hasOwnProperty('signal')) {
            return makeFetchRequest(requestParameters, callback);
        }
        if (isWorker() && self.worker && self.worker.actor) {
            const queueOnMainThread = true;
            return self.worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread);
        }
    }
    return makeXMLHttpRequest(requestParameters, callback);
};
const getJSON = function (requestParameters, callback) {
    return makeRequest(extend$1(requestParameters, { type: 'json' }), callback);
};
const getArrayBuffer = function (requestParameters, callback) {
    return makeRequest(extend$1(requestParameters, { type: 'arrayBuffer' }), callback);
};
const postData = function (requestParameters, callback) {
    return makeRequest(extend$1(requestParameters, { method: 'POST' }), callback);
};
const getData = function (requestParameters, callback) {
    return makeRequest(extend$1(requestParameters, { method: 'GET' }), callback);
};
function sameOrigin(url) {
    const a = window$1.document.createElement('a');
    a.href = url;
    return a.protocol === window$1.document.location.protocol && a.host === window$1.document.location.host;
}
const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';
function arrayBufferToImage(data, callback) {
    const img = new window$1.Image();
    const URL = window$1.URL;
    img.onload = () => {
        callback(null, img);
        URL.revokeObjectURL(img.src);
        // prevent image dataURI memory leak in Safari;
        // but don't free the image immediately because it might be uploaded in the next frame
        // https://github.com/mapbox/mapbox-gl-js/issues/10226
        img.onload = null;
        window$1.requestAnimationFrame(() => {
            img.src = transparentPngUrl;
        });
    };
    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.'));
    const blob = new window$1.Blob([new Uint8Array(data)], { type: 'image/png' });
    img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;
}
function arrayBufferToImageBitmap(data, callback) {
    const blob = new window$1.Blob([new Uint8Array(data)], { type: 'image/png' });
    window$1.createImageBitmap(blob).then(imgBitmap => {
        callback(null, imgBitmap);
    }).catch(e => {
        callback(new Error(`Could not load image because of ${ e.message }. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`));
    });
}
let imageQueue, numImageRequests;
const resetImageRequestQueue = () => {
    imageQueue = [];
    numImageRequests = 0;
};
resetImageRequestQueue();
const getImage = function (requestParameters, callback) {
    if (exported$2.supported) {
        if (!requestParameters.headers) {
            requestParameters.headers = {};
        }
        requestParameters.headers.accept = 'image/webp,*/*';
    }
    // limit concurrent image loads to help with raster sources performance on big screens
    if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {
        const queued = {
            requestParameters,
            callback,
            cancelled: false,
            // $FlowFixMe[object-this-reference]
            cancel() {
                this.cancelled = true;
            }
        };
        imageQueue.push(queued);
        return queued;
    }
    numImageRequests++;
    let advanced = false;
    const advanceImageRequestQueue = () => {
        if (advanced)
            return;
        advanced = true;
        numImageRequests--;
        while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) {
            // eslint-disable-line
            const request = imageQueue.shift();
            const {requestParameters, callback, cancelled} = request;
            if (!cancelled) {
                // $FlowFixMe[cannot-write] - Flow can't infer that cancel is a writable property
                request.cancel = getImage(requestParameters, callback).cancel;
            }
        }
    };
    // request the image with XHR to work around caching issues
    // see https://github.com/mapbox/mapbox-gl-js/issues/1470
    const request = getArrayBuffer(requestParameters, (err, data, cacheControl, expires) => {
        advanceImageRequestQueue();
        if (err) {
            callback(err);
        } else if (data) {
            if (window$1.createImageBitmap) {
                arrayBufferToImageBitmap(data, (err, imgBitmap) => callback(err, imgBitmap, cacheControl, expires));
            } else {
                arrayBufferToImage(data, (err, img) => callback(err, img, cacheControl, expires));
            }
        }
    });
    return {
        cancel: () => {
            request.cancel();
            advanceImageRequestQueue();
        }
    };
};
const getVideo = function (urls, callback) {
    const video = window$1.document.createElement('video');
    video.muted = true;
    video.onloadstart = function () {
        callback(null, video);
    };
    for (let i = 0; i < urls.length; i++) {
        const s = window$1.document.createElement('source');
        if (!sameOrigin(urls[i])) {
            video.crossOrigin = 'Anonymous';
        }
        s.src = urls[i];
        video.appendChild(s);
    }
    return {
        cancel: () => {
        }
    };
};

//      
/***** START WARNING REMOVAL OR MODIFICATION OF THE
* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE  ******
* The following code is used to access Mapbox's APIs. Removal or modification
* of this code can result in higher fees and/or
* termination of your account with Mapbox.
*
* Under the Mapbox Terms of Service, you may not use this code to access Mapbox
* Mapping APIs other than through Mapbox SDKs.
*
* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps
* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/
******************************************************************************/
const AUTH_ERR_MSG = 'NO_ACCESS_TOKEN';
class RequestManager {
    constructor(transformRequestFn, customAccessToken, silenceAuthErrors) {
        this._transformRequestFn = transformRequestFn;
        this._customAccessToken = customAccessToken;
        this._silenceAuthErrors = !!silenceAuthErrors;
        this._createSkuToken();
    }
    _createSkuToken() {
        const skuToken = createSkuToken();
        this._skuToken = skuToken.token;
        this._skuTokenExpiresAt = skuToken.tokenExpiresAt;
    }
    _isSkuTokenExpired() {
        return Date.now() > this._skuTokenExpiresAt;
    }
    transformRequest(url, type) {
        if (this._transformRequestFn) {
            return this._transformRequestFn(url, type) || { url };
        }
        return { url };
    }
    normalizeStyleURL(url, accessToken) {
        if (!isMapboxURL(url))
            return url;
        const urlObject = parseUrl(url);
        urlObject.params.push(`sdk=js-${ version }`);
        urlObject.path = `/styles/v1${ urlObject.path }`;
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeGlyphsURL(url, accessToken) {
        if (!isMapboxURL(url))
            return url;
        const urlObject = parseUrl(url);
        urlObject.path = `/fonts/v1${ urlObject.path }`;
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeModelURL(url, accessToken) {
        if (!isMapboxURL(url))
            return url;
        const urlObject = parseUrl(url);
        urlObject.path = `/models/v1${ urlObject.path }`;
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeSourceURL(url, accessToken, language, worldview) {
        if (!isMapboxURL(url))
            return url;
        const urlObject = parseUrl(url);
        urlObject.path = `/v4/${ urlObject.authority }.json`;
        // TileJSON requests need a secure flag appended to their URLs so
        // that the server knows to send SSL-ified resource references.
        urlObject.params.push('secure');
        if (language) {
            urlObject.params.push(`language=${ language }`);
        }
        if (worldview) {
            urlObject.params.push(`worldview=${ worldview }`);
        }
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeSpriteURL(url, format, extension, accessToken) {
        const urlObject = parseUrl(url);
        if (!isMapboxURL(url)) {
            urlObject.path += `${ format }${ extension }`;
            return formatUrl(urlObject);
        }
        urlObject.path = `/styles/v1${ urlObject.path }/sprite${ format }${ extension }`;
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeTileURL(tileURL, use2x, rasterTileSize) {
        if (this._isSkuTokenExpired()) {
            this._createSkuToken();
        }
        if (tileURL && !isMapboxURL(tileURL))
            return tileURL;
        const urlObject = parseUrl(tileURL);
        const imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/;
        const extension = exported$2.supported ? '.webp' : '$1';
        // The v4 mapbox tile API supports 512x512 image tiles but they must be requested as '@2x' tiles.
        const use2xAs512 = rasterTileSize && urlObject.authority !== 'raster' && rasterTileSize === 512;
        const suffix = use2x || use2xAs512 ? '@2x' : '';
        urlObject.path = urlObject.path.replace(imageExtensionRe, `${ suffix }${ extension }`);
        if (urlObject.authority === 'raster') {
            urlObject.path = `/${ config.RASTER_URL_PREFIX }${ urlObject.path }`;
        } else {
            const tileURLAPIPrefixRe = /^.+\/v4\//;
            urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');
            urlObject.path = `/${ config.TILE_URL_VERSION }${ urlObject.path }`;
        }
        const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN;
        if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) {
            urlObject.params.push(`sku=${ this._skuToken }`);
        }
        return this._makeAPIURL(urlObject, accessToken);
    }
    canonicalizeTileURL(url, removeAccessToken) {
        // matches any file extension specified by a dot and one or more alphanumeric characters
        const extensionRe = /\.[\w]+$/;
        const urlObject = parseUrl(url);
        // Make sure that we are dealing with a valid Mapbox tile URL.
        // Has to begin with /v4/ or /raster/v1, with a valid filename + extension
        if (!urlObject.path.match(/^(\/v4\/|\/raster\/v1\/)/) || !urlObject.path.match(extensionRe)) {
            // Not a proper Mapbox tile URL.
            return url;
        }
        // Reassemble the canonical URL from the parts we've parsed before.
        let result = 'mapbox://';
        if (urlObject.path.match(/^\/raster\/v1\//)) {
            // If the tile url has /raster/v1/, make the final URL mapbox://raster/....
            const rasterPrefix = `/${ config.RASTER_URL_PREFIX }/`;
            result += `raster/${ urlObject.path.replace(rasterPrefix, '') }`;
        } else {
            const tilesPrefix = `/${ config.TILE_URL_VERSION }/`;
            result += `tiles/${ urlObject.path.replace(tilesPrefix, '') }`;
        }
        // Append the query string, minus the access token parameter.
        let params = urlObject.params;
        if (removeAccessToken) {
            params = params.filter(p => !p.match(/^access_token=/));
        }
        if (params.length)
            result += `?${ params.join('&') }`;
        return result;
    }
    canonicalizeTileset(tileJSON, sourceURL) {
        const removeAccessToken = sourceURL ? isMapboxURL(sourceURL) : false;
        const canonical = [];
        for (const url of tileJSON.tiles || []) {
            if (isMapboxHTTPURL(url)) {
                canonical.push(this.canonicalizeTileURL(url, removeAccessToken));
            } else {
                canonical.push(url);
            }
        }
        return canonical;
    }
    _makeAPIURL(urlObject, accessToken) {
        const help = 'See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes';
        const apiUrlObject = parseUrl(config.API_URL);
        urlObject.protocol = apiUrlObject.protocol;
        urlObject.authority = apiUrlObject.authority;
        if (urlObject.protocol === 'http') {
            const i = urlObject.params.indexOf('secure');
            if (i >= 0)
                urlObject.params.splice(i, 1);
        }
        if (apiUrlObject.path !== '/') {
            urlObject.path = `${ apiUrlObject.path }${ urlObject.path }`;
        }
        if (!config.REQUIRE_ACCESS_TOKEN)
            return formatUrl(urlObject);
        accessToken = accessToken || config.ACCESS_TOKEN;
        if (!this._silenceAuthErrors) {
            if (!accessToken)
                throw new Error(`An API access token is required to use Mapbox GL. ${ help }`);
            if (accessToken[0] === 's')
                throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${ help }`);
        }
        urlObject.params = urlObject.params.filter(d => d.indexOf('access_token') === -1);
        urlObject.params.push(`access_token=${ accessToken || '' }`);
        return formatUrl(urlObject);
    }
}
function isMapboxURL(url) {
    return url.indexOf('mapbox:') === 0;
}
function isMapboxHTTPURL(url) {
    return config.API_URL_REGEX.test(url);
}
function isMapboxHTTPCDNURL(url) {
    return config.API_CDN_URL_REGEX.test(url);
}
function isMapboxHTTPStyleURL(url) {
    return config.API_STYLE_REGEX.test(url) && !isMapboxHTTPSpriteURL(url);
}
function isMapboxHTTPTileJSONURL(url) {
    return config.API_TILEJSON_REGEX.test(url);
}
function isMapboxHTTPSpriteURL(url) {
    return config.API_SPRITE_REGEX.test(url);
}
function isMapboxHTTPFontsURL(url) {
    return config.API_FONTS_REGEX.test(url);
}
function hasCacheDefeatingSku(url) {
    return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);
}
function getAccessToken(params) {
    for (const param of params) {
        const match = param.match(/^access_token=(.*)$/);
        if (match) {
            return match[1];
        }
    }
    return null;
}
const urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;
function parseUrl(url) {
    const parts = url.match(urlRe);
    if (!parts) {
        throw new Error('Unable to parse URL object');
    }
    return {
        protocol: parts[1],
        authority: parts[2],
        path: parts[3] || '/',
        params: parts[4] ? parts[4].split('&') : []
    };
}
function formatUrl(obj) {
    const params = obj.params.length ? `?${ obj.params.join('&') }` : '';
    return `${ obj.protocol }://${ obj.authority }${ obj.path }${ params }`;
}
const telemEventKey = 'mapbox.eventData';
function parseAccessToken(accessToken) {
    if (!accessToken) {
        return null;
    }
    const parts = accessToken.split('.');
    if (!parts || parts.length !== 3) {
        return null;
    }
    try {
        const jsonData = JSON.parse(b64DecodeUnicode(parts[1]));
        return jsonData;
    } catch (e) {
        return null;
    }
}
class TelemetryEvent {
    constructor(type) {
        this.type = type;
        this.anonId = null;
        this.eventData = {};
        this.queue = [];
        this.pendingRequest = null;
    }
    getStorageKey(domain) {
        const tokenData = parseAccessToken(config.ACCESS_TOKEN);
        let u = '';
        if (tokenData && tokenData['u']) {
            u = b64EncodeUnicode(tokenData['u']);
        } else {
            u = config.ACCESS_TOKEN || '';
        }
        return domain ? `${ telemEventKey }.${ domain }:${ u }` : `${ telemEventKey }:${ u }`;
    }
    fetchEventData() {
        const isLocalStorageAvailable = storageAvailable('localStorage');
        const storageKey = this.getStorageKey();
        const uuidKey = this.getStorageKey('uuid');
        if (isLocalStorageAvailable) {
            //Retrieve cached data
            try {
                const data = window$1.localStorage.getItem(storageKey);
                if (data) {
                    this.eventData = JSON.parse(data);
                }
                const uuid = window$1.localStorage.getItem(uuidKey);
                if (uuid)
                    this.anonId = uuid;
            } catch (e) {
                warnOnce('Unable to read from LocalStorage');
            }
        }
    }
    saveEventData() {
        const isLocalStorageAvailable = storageAvailable('localStorage');
        const storageKey = this.getStorageKey();
        const uuidKey = this.getStorageKey('uuid');
        if (isLocalStorageAvailable) {
            try {
                window$1.localStorage.setItem(uuidKey, this.anonId);
                if (Object.keys(this.eventData).length >= 1) {
                    window$1.localStorage.setItem(storageKey, JSON.stringify(this.eventData));
                }
            } catch (e) {
                warnOnce('Unable to write to LocalStorage');
            }
        }
    }
    processRequests(_) {
    }
    /*
    * If any event data should be persisted after the POST request, the callback should modify eventData`
    * to the values that should be saved. For this reason, the callback should be invoked prior to the call
    * to TelemetryEvent#saveData
    */
    postEvent(timestamp, additionalPayload, callback, customAccessToken) {
        if (!config.EVENTS_URL)
            return;
        const eventsUrlObject = parseUrl(config.EVENTS_URL);
        eventsUrlObject.params.push(`access_token=${ customAccessToken || config.ACCESS_TOKEN || '' }`);
        const payload = {
            event: this.type,
            created: new Date(timestamp).toISOString()
        };
        const finalPayload = additionalPayload ? extend$1(payload, additionalPayload) : payload;
        const request = {
            url: formatUrl(eventsUrlObject),
            headers: {
                'Content-Type': 'text/plain'    //Skip the pre-flight OPTIONS request
            },
            body: JSON.stringify([finalPayload])
        };
        this.pendingRequest = postData(request, error => {
            this.pendingRequest = null;
            callback(error);
            this.saveEventData();
            this.processRequests(customAccessToken);
        });
    }
    queueRequest(event, customAccessToken) {
        this.queue.push(event);
        this.processRequests(customAccessToken);
    }
}
class PerformanceEvent extends TelemetryEvent {
    constructor() {
        super('gljs.performance');
    }
    postPerformanceEvent(customAccessToken, performanceData) {
        if (config.EVENTS_URL) {
            if (customAccessToken || config.ACCESS_TOKEN) {
                this.queueRequest({
                    timestamp: Date.now(),
                    performanceData
                }, customAccessToken);
            }
        }
    }
    processRequests(customAccessToken) {
        if (this.pendingRequest || this.queue.length === 0) {
            return;
        }
        const {timestamp, performanceData} = this.queue.shift();
        const additionalPayload = getLivePerformanceMetrics(performanceData);
        // Server will only process string for these entries
        for (const metadata of additionalPayload.metadata) {
        }
        for (const counter of additionalPayload.counters) {
        }
        for (const attribute of additionalPayload.attributes) {
        }
        this.postEvent(timestamp, additionalPayload, () => {
        }, customAccessToken);
    }
}
class MapLoadEvent extends TelemetryEvent {
    constructor() {
        super('map.load');
        this.success = {};
        this.skuToken = '';
    }
    postMapLoadEvent(mapId, skuToken, customAccessToken, callback) {
        this.skuToken = skuToken;
        this.errorCb = callback;
        if (config.EVENTS_URL) {
            if (customAccessToken || config.ACCESS_TOKEN) {
                this.queueRequest({
                    id: mapId,
                    timestamp: Date.now()
                }, customAccessToken);
            } else {
                this.errorCb(new Error(AUTH_ERR_MSG));
            }
        }
    }
    processRequests(customAccessToken) {
        if (this.pendingRequest || this.queue.length === 0)
            return;
        const {id, timestamp} = this.queue.shift();
        // Only one load event should fire per map
        if (id && this.success[id])
            return;
        if (!this.anonId) {
            this.fetchEventData();
        }
        if (!validateUuid(this.anonId)) {
            this.anonId = uuid();
        }
        const additionalPayload = {
            sdkIdentifier: 'mapbox-gl-js',
            sdkVersion: version,
            skuId: SKU_ID,
            skuToken: this.skuToken,
            userId: this.anonId
        };
        this.postEvent(timestamp, additionalPayload, err => {
            if (err) {
                this.errorCb(err);
            } else {
                if (id)
                    this.success[id] = true;
            }
        }, customAccessToken);
    }
}
class MapSessionAPI extends TelemetryEvent {
    constructor() {
        super('map.auth');
        this.success = {};
        this.skuToken = '';
    }
    getSession(timestamp, token, callback, customAccessToken) {
        if (!config.API_URL || !config.SESSION_PATH)
            return;
        const authUrlObject = parseUrl(config.API_URL + config.SESSION_PATH);
        authUrlObject.params.push(`sku=${ token || '' }`);
        authUrlObject.params.push(`access_token=${ customAccessToken || config.ACCESS_TOKEN || '' }`);
        const request = {
            url: formatUrl(authUrlObject),
            headers: { 'Content-Type': 'text/plain' }
        };
        this.pendingRequest = getData(request, error => {
            this.pendingRequest = null;
            callback(error);
            this.saveEventData();
            this.processRequests(customAccessToken);
        });
    }
    getSessionAPI(mapId, skuToken, customAccessToken, callback) {
        this.skuToken = skuToken;
        this.errorCb = callback;
        if (config.SESSION_PATH && config.API_URL) {
            if (customAccessToken || config.ACCESS_TOKEN) {
                this.queueRequest({
                    id: mapId,
                    timestamp: Date.now()
                }, customAccessToken);
            } else {
                this.errorCb(new Error(AUTH_ERR_MSG));
            }
        }
    }
    processRequests(customAccessToken) {
        if (this.pendingRequest || this.queue.length === 0)
            return;
        const {id, timestamp} = this.queue.shift();
        // Only one load event should fire per map
        if (id && this.success[id])
            return;
        this.getSession(timestamp, this.skuToken, err => {
            if (err) {
                this.errorCb(err);
            } else {
                if (id)
                    this.success[id] = true;
            }
        }, customAccessToken);
    }
}
class TurnstileEvent extends TelemetryEvent {
    constructor(customAccessToken) {
        super('appUserTurnstile');
        this._customAccessToken = customAccessToken;
    }
    postTurnstileEvent(tileUrls, customAccessToken) {
        //Enabled only when Mapbox Access Token is set and a source uses
        // mapbox tiles.
        if (config.EVENTS_URL && config.ACCESS_TOKEN && Array.isArray(tileUrls) && tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) {
            this.queueRequest(Date.now(), customAccessToken);
        }
    }
    processRequests(customAccessToken) {
        if (this.pendingRequest || this.queue.length === 0) {
            return;
        }
        if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) {
            //Retrieve cached data
            this.fetchEventData();
        }
        const tokenData = parseAccessToken(config.ACCESS_TOKEN);
        const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN;
        //Reset event data cache if the access token owner changed.
        let dueForEvent = tokenU !== this.eventData.tokenU;
        if (!validateUuid(this.anonId)) {
            this.anonId = uuid();
            dueForEvent = true;
        }
        const nextUpdate = this.queue.shift();
        // Record turnstile event once per calendar day.
        if (this.eventData.lastSuccess) {
            const lastUpdate = new Date(this.eventData.lastSuccess);
            const nextDate = new Date(nextUpdate);
            const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000);
            dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate();
        } else {
            dueForEvent = true;
        }
        if (!dueForEvent) {
            this.processRequests();
            return;
        }
        const additionalPayload = {
            sdkIdentifier: 'mapbox-gl-js',
            sdkVersion: version,
            skuId: SKU_ID,
            'enabled.telemetry': false,
            userId: this.anonId
        };
        this.postEvent(nextUpdate, additionalPayload, err => {
            if (!err) {
                this.eventData.lastSuccess = nextUpdate;
                this.eventData.tokenU = tokenU;
            }
        }, customAccessToken);
    }
}
const turnstileEvent_ = new TurnstileEvent();
// $FlowFixMe[method-unbinding]
const postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);
const mapLoadEvent_ = new MapLoadEvent();
// $FlowFixMe[method-unbinding]
const postMapLoadEvent = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_);
const performanceEvent_ = new PerformanceEvent();
// $FlowFixMe[method-unbinding]
const postPerformanceEvent = performanceEvent_.postPerformanceEvent.bind(performanceEvent_);
const mapSessionAPI_ = new MapSessionAPI();
// $FlowFixMe[method-unbinding]
const getMapSessionAPI = mapSessionAPI_.getSessionAPI.bind(mapSessionAPI_);
const authenticatedMaps = new Set();
function storeAuthState(gl, state) {
    if (state) {
        authenticatedMaps.add(gl);
    } else {
        authenticatedMaps.delete(gl);
    }
}
function isMapAuthenticated(gl) {
    return authenticatedMaps.has(gl);
}
function removeAuthState(gl) {
    authenticatedMaps.delete(gl);
}    /***** END WARNING - REMOVAL OR MODIFICATION OF THE
PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE  ******/

//      
const PerformanceMarkers = {
    create: 'create',
    load: 'load',
    fullLoad: 'fullLoad'
};
const LivePerformanceUtils = {
    mark(marker) {
        window$1.performance.mark(marker);
    },
    measure(name, begin, end) {
        window$1.performance.measure(name, begin, end);
    }
};
function categorize(arr, fn) {
    const obj = {};
    if (arr) {
        for (const item of arr) {
            const category = fn(item);
            if (obj[category] === undefined) {
                obj[category] = [];
            }
            obj[category].push(item);
        }
    }
    return obj;
}
function getCountersPerResourceType(resourceTimers) {
    const obj = {};
    if (resourceTimers) {
        for (const category in resourceTimers) {
            if (category !== 'other') {
                for (const timer of resourceTimers[category]) {
                    const min = `${ category }ResolveRangeMin`;
                    const max = `${ category }ResolveRangeMax`;
                    const reqCount = `${ category }RequestCount`;
                    const reqCachedCount = `${ category }RequestCachedCount`;
                    // Resource -TransferStart and -TransferEnd represent the wall time
                    // between the start of a request to when the data is available
                    obj[min] = Math.min(obj[min] || +Infinity, timer.startTime);
                    obj[max] = Math.max(obj[max] || -Infinity, timer.responseEnd);
                    const increment = key => {
                        if (obj[key] === undefined) {
                            obj[key] = 0;
                        }
                        ++obj[key];
                    };
                    const transferSizeSupported = timer.transferSize !== undefined;
                    if (transferSizeSupported) {
                        const resourceFetchedFromCache = timer.transferSize === 0;
                        if (resourceFetchedFromCache) {
                            increment(reqCachedCount);
                        }
                    }
                    increment(reqCount);
                }
            }
        }
    }
    return obj;
}
function getResourceCategory(entry) {
    const url = entry.name.split('?')[0];
    if (isMapboxHTTPCDNURL(url) && url.includes('mapbox-gl.js'))
        return 'javascript';
    if (isMapboxHTTPCDNURL(url) && url.includes('mapbox-gl.css'))
        return 'css';
    if (isMapboxHTTPFontsURL(url))
        return 'fontRange';
    if (isMapboxHTTPSpriteURL(url))
        return 'sprite';
    if (isMapboxHTTPStyleURL(url))
        return 'style';
    if (isMapboxHTTPTileJSONURL(url))
        return 'tilejson';
    return 'other';
}
function getStyle(resourceTimers) {
    if (resourceTimers) {
        for (const timer of resourceTimers) {
            const url = timer.name.split('?')[0];
            if (isMapboxHTTPStyleURL(url)) {
                const split = url.split('/').slice(-2);
                if (split.length === 2) {
                    return `mapbox://styles/${ split[0] }/${ split[1] }`;
                }
            }
        }
    }
}
function getLivePerformanceMetrics(data) {
    const resourceTimers = window$1.performance.getEntriesByType('resource');
    const markerTimers = window$1.performance.getEntriesByType('mark');
    const resourcesByType = categorize(resourceTimers, getResourceCategory);
    const counters = getCountersPerResourceType(resourcesByType);
    const devicePixelRatio = window$1.devicePixelRatio;
    const connection = window$1.navigator.connection || window$1.navigator.mozConnection || window$1.navigator.webkitConnection;
    const metrics = {
        counters: [],
        metadata: [],
        attributes: []
    };
    // Please read carefully before adding or modifying the following metrics:
    // https://github.com/mapbox/gl-js-team/blob/main/docs/live_performance_metrics.md
    const addMetric = (arr, name, value) => {
        if (value !== undefined && value !== null) {
            arr.push({
                name,
                value: value.toString()
            });
        }
    };
    for (const counter in counters) {
        addMetric(metrics.counters, counter, counters[counter]);
    }
    if (data.interactionRange[0] !== +Infinity && data.interactionRange[1] !== -Infinity) {
        addMetric(metrics.counters, 'interactionRangeMin', data.interactionRange[0]);
        addMetric(metrics.counters, 'interactionRangeMax', data.interactionRange[1]);
    }
    if (markerTimers) {
        for (const marker of Object.keys(PerformanceMarkers)) {
            const markerName = PerformanceMarkers[marker];
            const markerTimer = markerTimers.find(entry => entry.name === markerName);
            if (markerTimer) {
                addMetric(metrics.counters, markerName, markerTimer.startTime);
            }
        }
    }
    addMetric(metrics.counters, 'visibilityHidden', data.visibilityHidden);
    addMetric(metrics.attributes, 'style', getStyle(resourceTimers));
    addMetric(metrics.attributes, 'terrainEnabled', data.terrainEnabled ? 'true' : 'false');
    addMetric(metrics.attributes, 'fogEnabled', data.fogEnabled ? 'true' : 'false');
    addMetric(metrics.attributes, 'projection', data.projection);
    addMetric(metrics.attributes, 'zoom', data.zoom);
    addMetric(metrics.metadata, 'devicePixelRatio', devicePixelRatio);
    addMetric(metrics.metadata, 'connectionEffectiveType', connection ? connection.effectiveType : undefined);
    addMetric(metrics.metadata, 'navigatorUserAgent', window$1.navigator.userAgent);
    addMetric(metrics.metadata, 'screenWidth', window$1.screen.width);
    addMetric(metrics.metadata, 'screenHeight', window$1.screen.height);
    addMetric(metrics.metadata, 'windowWidth', window$1.innerWidth);
    addMetric(metrics.metadata, 'windowHeight', window$1.innerHeight);
    addMetric(metrics.metadata, 'mapWidth', data.width / devicePixelRatio);
    addMetric(metrics.metadata, 'mapHeight', data.height / devicePixelRatio);
    addMetric(metrics.metadata, 'webglRenderer', data.renderer);
    addMetric(metrics.metadata, 'webglVendor', data.vendor);
    addMetric(metrics.metadata, 'sdkVersion', version);
    addMetric(metrics.metadata, 'sdkIdentifier', 'mapbox-gl-js');
    return metrics;
}

//      
const performance$1 = window$1.performance;
function getPerformanceMeasurement(request) {
    const url = request ? request.url.toString() : undefined;
    return performance$1.getEntriesByName(url);
}

var supported = isSupported;
/**
 * Test whether the current browser supports Mapbox GL JS
 * @param {Object} options
 * @param {boolean} [options.failIfMajorPerformanceCaveat=false] Return `false`
 *   if the performance of Mapbox GL JS would be dramatically worse than
 *   expected (i.e. a software renderer is would be used)
 * @return {boolean}
 */
function isSupported(options) {
    return !notSupportedReason(options);
}
function notSupportedReason(options) {
    if (!isBrowser())
        return 'not a browser';
    if (!isArraySupported())
        return 'insufficent Array support';
    if (!isFunctionSupported())
        return 'insufficient Function support';
    if (!isObjectSupported())
        return 'insufficient Object support';
    if (!isJSONSupported())
        return 'insufficient JSON support';
    if (!isWorkerSupported())
        return 'insufficient worker support';
    if (!isUint8ClampedArraySupported())
        return 'insufficient Uint8ClampedArray support';
    if (!isArrayBufferSupported())
        return 'insufficient ArrayBuffer support';
    if (!isCanvasGetImageDataSupported())
        return 'insufficient Canvas/getImageData support';
    if (!isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat))
        return 'insufficient WebGL support';
    if (!isNotIE())
        return 'insufficient ECMAScript 6 support';
}
function isBrowser() {
    return typeof window !== 'undefined' && typeof document !== 'undefined';
}
function isArraySupported() {
    return Array.prototype && Array.prototype.every && Array.prototype.filter && Array.prototype.forEach && Array.prototype.indexOf && Array.prototype.lastIndexOf && Array.prototype.map && Array.prototype.some && Array.prototype.reduce && Array.prototype.reduceRight && Array.isArray;
}
function isFunctionSupported() {
    return Function.prototype && Function.prototype.bind;
}
function isObjectSupported() {
    return Object.keys && Object.create && Object.getPrototypeOf && Object.getOwnPropertyNames && Object.isSealed && Object.isFrozen && Object.isExtensible && Object.getOwnPropertyDescriptor && Object.defineProperty && Object.defineProperties && Object.seal && Object.freeze && Object.preventExtensions;
}
function isJSONSupported() {
    return 'JSON' in window && 'parse' in JSON && 'stringify' in JSON;
}
function isWorkerSupported() {
    if (!('Worker' in window && 'Blob' in window && 'URL' in window)) {
        return false;
    }
    var blob = new Blob([''], { type: 'text/javascript' });
    var workerURL = URL.createObjectURL(blob);
    var supported;
    var worker;
    try {
        worker = new Worker(workerURL);
        supported = true;
    } catch (e) {
        supported = false;
    }
    if (worker) {
        worker.terminate();
    }
    URL.revokeObjectURL(workerURL);
    return supported;
}
// IE11 only supports `Uint8ClampedArray` as of version
// [KB2929437](https://support.microsoft.com/en-us/kb/2929437)
function isUint8ClampedArraySupported() {
    return 'Uint8ClampedArray' in window;
}
// https://github.com/mapbox/mapbox-gl-supported/issues/19
function isArrayBufferSupported() {
    return ArrayBuffer.isView;
}
// Some browsers or browser extensions block access to canvas data to prevent fingerprinting.
// Mapbox GL uses this API to load sprites and images in general.
function isCanvasGetImageDataSupported() {
    var canvas = document.createElement('canvas');
    canvas.width = canvas.height = 1;
    var context = canvas.getContext('2d');
    if (!context) {
        return false;
    }
    var imageData = context.getImageData(0, 0, 1, 1);
    return imageData && imageData.width === canvas.width;
}
var isWebGLSupportedCache = {};
function isWebGLSupportedCached(failIfMajorPerformanceCaveat) {
    if (isWebGLSupportedCache[failIfMajorPerformanceCaveat] === undefined) {
        isWebGLSupportedCache[failIfMajorPerformanceCaveat] = isWebGLSupported(failIfMajorPerformanceCaveat);
    }
    return isWebGLSupportedCache[failIfMajorPerformanceCaveat];
}
isSupported.webGLContextAttributes = {
    antialias: false,
    alpha: true,
    stencil: true,
    depth: true
};
function getWebGLContext(failIfMajorPerformanceCaveat) {
    var canvas = document.createElement('canvas');
    var attributes = Object.create(isSupported.webGLContextAttributes);
    attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
    return canvas.getContext('webgl', attributes) || canvas.getContext('experimental-webgl', attributes);
}
function isWebGLSupported(failIfMajorPerformanceCaveat) {
    var gl = getWebGLContext(failIfMajorPerformanceCaveat);
    if (!gl) {
        return false;
    }
    // Try compiling a shader and get its compile status. Some browsers like Brave block this API
    // to prevent fingerprinting. Unfortunately, this also means that Mapbox GL won't work.
    var shader;
    try {
        shader = gl.createShader(gl.VERTEX_SHADER);
    } catch (e) {
        // some older browsers throw an exception that `createShader` is not defined
        // so handle this separately from the case where browsers block `createShader`
        // for security reasons
        return false;
    }
    if (!shader || gl.isContextLost()) {
        return false;
    }
    gl.shaderSource(shader, 'void main() {}');
    gl.compileShader(shader);
    return gl.getShaderParameter(shader, gl.COMPILE_STATUS) === true;
}
function isNotIE() {
    return !document.documentMode;
}

//       strict
let linkEl;
let reducedMotionQuery;
let stubTime;
let canvas;
/**
 * @private
 */
const exported$1 = {
    /**
     * Returns either performance.now() or a value set by setNow.
     * @returns {number} Time value in milliseconds.
     */
    now() {
        if (stubTime !== undefined) {
            return stubTime;
        }
        return window$1.performance.now();
    },
    setNow(time) {
        stubTime = time;
    },
    restoreNow() {
        stubTime = undefined;
    },
    frame(fn) {
        const frame = window$1.requestAnimationFrame(fn);
        return { cancel: () => window$1.cancelAnimationFrame(frame) };
    },
    getImageData(img, padding = 0) {
        const {width, height} = img;
        if (!canvas) {
            canvas = window$1.document.createElement('canvas');
        }
        const context = canvas.getContext('2d', { willReadFrequently: true });
        if (!context) {
            throw new Error('failed to create canvas 2d context');
        }
        if (width > canvas.width || height > canvas.height) {
            canvas.width = width;
            canvas.height = height;
        }
        context.clearRect(-padding, -padding, width + 2 * padding, height + 2 * padding);
        context.drawImage(img, 0, 0, width, height);
        return context.getImageData(-padding, -padding, width + 2 * padding, height + 2 * padding);
    },
    resolveURL(path) {
        if (!linkEl)
            linkEl = window$1.document.createElement('a');
        linkEl.href = path;
        return linkEl.href;
    },
    get devicePixelRatio() {
        return window$1.devicePixelRatio;
    },
    get prefersReducedMotion() {
        if (!window$1.matchMedia)
            return false;
        // Lazily initialize media query.
        if (reducedMotionQuery == null) {
            reducedMotionQuery = window$1.matchMedia('(prefers-reduced-motion: reduce)');
        }
        return reducedMotionQuery.matches;
    }
};

//       strict
// refine the return type based on tagName, e.g. 'button' -> HTMLButtonElement
// $FlowFixMe[method-unbinding]
function create$a(tagName, className, container) {
    const el = window$1.document.createElement(tagName);
    if (className !== undefined)
        el.className = className;
    if (container)
        container.appendChild(el);
    return el;
}
function createSVG(tagName, attributes, container) {
    const el = window$1.document.createElementNS('http://www.w3.org/2000/svg', tagName);
    for (const name of Object.keys(attributes)) {
        el.setAttributeNS(null, name, attributes[name]);
    }
    if (container)
        container.appendChild(el);
    return el;
}
const docStyle = window$1.document && window$1.document.documentElement.style;
const selectProp = docStyle && docStyle.userSelect !== undefined ? 'userSelect' : 'WebkitUserSelect';
let userSelect;
function disableDrag() {
    if (docStyle && selectProp) {
        userSelect = docStyle[selectProp];
        docStyle[selectProp] = 'none';
    }
}
function enableDrag() {
    if (docStyle && selectProp) {
        docStyle[selectProp] = userSelect;
    }
}
// Suppress the next click, but only if it's immediate.
function suppressClickListener(e) {
    e.preventDefault();
    e.stopPropagation();
    window$1.removeEventListener('click', suppressClickListener, true);
}
function suppressClick() {
    window$1.addEventListener('click', suppressClickListener, true);
    window$1.setTimeout(() => {
        window$1.removeEventListener('click', suppressClickListener, true);
    }, 0);
}
function mousePos(el, e) {
    const rect = el.getBoundingClientRect();
    return getScaledPoint(el, rect, e);
}
function touchPos(el, touches) {
    const rect = el.getBoundingClientRect(), points = [];
    for (let i = 0; i < touches.length; i++) {
        points.push(getScaledPoint(el, rect, touches[i]));
    }
    return points;
}
function mouseButton(e) {
    if (typeof window$1.InstallTrigger !== 'undefined' && e.button === 2 && e.ctrlKey && window$1.navigator.platform.toUpperCase().indexOf('MAC') >= 0) {
        // Fix for https://github.com/mapbox/mapbox-gl-js/issues/3131:
        // Firefox (detected by InstallTrigger) on Mac determines e.button = 2 when
        // using Control + left click
        return 0;
    }
    return e.button;
}
function getScaledPoint(el, rect, e) {
    // Until we get support for pointer events (https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent)
    // we use this dirty trick which would not work for the case of rotated transforms, but works well for
    // the case of simple scaling.
    // Note: `el.offsetWidth === rect.width` eliminates the `0/0` case.
    const scaling = el.offsetWidth === rect.width ? 1 : el.offsetWidth / rect.width;
    return new Point$2((e.clientX - rect.left) * scaling, (e.clientY - rect.top) * scaling);
}

//      
function _addEventListener(type, listener, listenerList) {
    const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1;
    if (!listenerExists) {
        listenerList[type] = listenerList[type] || [];
        listenerList[type].push(listener);
    }
}
function _removeEventListener(type, listener, listenerList) {
    if (listenerList && listenerList[type]) {
        const index = listenerList[type].indexOf(listener);
        if (index !== -1) {
            listenerList[type].splice(index, 1);
        }
    }
}
class Event {
    constructor(type, data = {}) {
        extend$1(this, data);
        this.type = type;
    }
}
class ErrorEvent extends Event {
    constructor(error, data = {}) {
        super('error', extend$1({ error }, data));
    }
}
/**
 * `Evented` mixes methods into other classes for event capabilities.
 *
 * Unless you are developing a plugin you will most likely use these methods through classes like `Map` or `Popup`.
 *
 * For lists of events you can listen for, see API documentation for specific classes: [`Map`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events), [`Marker`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events), [`Popup`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events), and [`GeolocationControl`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events).
 *
 * @mixin Evented
 */
class Evented {
    /**
     * Adds a listener to a specified event type.
     *
     * @param {string} type The event type to add a listen for.
     * @param {Function} listener The function to be called when the event is fired.
     *   The listener function is called with the data object passed to `fire`,
     *   extended with `target` and `type` properties.
     * @returns {Object} Returns itself to allow for method chaining.
     */
    on(type, listener) {
        this._listeners = this._listeners || {};
        _addEventListener(type, listener, this._listeners);
        return this;
    }
    /**
     * Removes a previously registered event listener.
     *
     * @param {string} type The event type to remove listeners for.
     * @param {Function} listener The listener function to remove.
     * @returns {Object} Returns itself to allow for method chaining.
     */
    off(type, listener) {
        _removeEventListener(type, listener, this._listeners);
        _removeEventListener(type, listener, this._oneTimeListeners);
        return this;
    }
    /**
     * Adds a listener that will be called only once to a specified event type.
     *
     * The listener will be called first time the event fires after the listener is registered.
     *
     * @param {string} type The event type to listen for.
     * @param {Function} listener (Optional) The function to be called when the event is fired once.
     *   If not provided, returns a Promise that will be resolved when the event is fired once.
     * @returns {Object} Returns `this` | Promise.
     */
    once(type, listener) {
        if (!listener) {
            return new Promise(resolve => this.once(type, resolve));
        }
        this._oneTimeListeners = this._oneTimeListeners || {};
        _addEventListener(type, listener, this._oneTimeListeners);
        return this;
    }
    fire(event, properties) {
        // Compatibility with (type: string, properties: Object) signature from previous versions.
        // See https://github.com/mapbox/mapbox-gl-js/issues/6522,
        //     https://github.com/mapbox/mapbox-gl-draw/issues/766
        if (typeof event === 'string') {
            event = new Event(event, properties || {});
        }
        const type = event.type;
        if (this.listens(type)) {
            event.target = this;
            // make sure adding or removing listeners inside other listeners won't cause an infinite loop
            const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : [];
            for (const listener of listeners) {
                listener.call(this, event);
            }
            const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : [];
            for (const listener of oneTimeListeners) {
                _removeEventListener(type, listener, this._oneTimeListeners);
                listener.call(this, event);
            }
            const parent = this._eventedParent;
            if (parent) {
                extend$1(event, typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData);
                parent.fire(event);
            }    // To ensure that no error events are dropped, print them to the
                 // console if they have no listeners.
        } else if (event instanceof ErrorEvent) {
            console.error(event.error);
        }
        return this;
    }
    /**
     * Returns true if this instance of Evented or any forwarded instances of Evented have a listener for the specified type.
     *
     * @param {string} type The event type.
     * @returns {boolean} Returns `true` if there is at least one registered listener for specified event type, `false` otherwise.
     * @private
     */
    listens(type) {
        return !!(this._listeners && this._listeners[type] && this._listeners[type].length > 0 || this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0 || this._eventedParent && this._eventedParent.listens(type));
    }
    /**
     * Bubble all events fired by this instance of Evented to this parent instance of Evented.
     *
     * @returns {Object} `this`
     * @private
     */
    setEventedParent(parent, data) {
        this._eventedParent = parent;
        this._eventedParentData = data;
        return this;
    }
}

var spec = JSON.parse('{"$version":8,"$root":{"version":{"required":true,"type":"enum","values":[8]},"fragment":{"type":"boolean"},"name":{"type":"string"},"metadata":{"type":"*"},"center":{"type":"array","value":"number"},"zoom":{"type":"number"},"bearing":{"type":"number","default":0,"period":360},"pitch":{"type":"number","default":0},"light":{"type":"light"},"lights":{"required":false,"type":"array","value":"light-3d"},"terrain":{"type":"terrain"},"fog":{"type":"fog"},"camera":{"type":"camera"},"imports":{"type":"array","value":"import"},"schema":{"type":"schema"},"sources":{"required":true,"type":"sources"},"sprite":{"type":"string"},"glyphs":{"type":"string","default":"mapbox://fonts/mapbox/{fontstack}/{range}.pbf"},"transition":{"type":"transition"},"projection":{"type":"projection"},"layers":{"required":true,"type":"array","value":"layer"},"models":{"type":"models"}},"model":{"type":"string","required":true},"import":{"id":{"type":"string","required":true},"url":{"type":"string","required":true},"config":{"type":"config"},"data":{"type":"$root"}},"config":{"*":{"type":"*"}},"schema":{"*":{"type":"option"}},"option":{"default":{"type":"*","required":true},"type":{"type":"enum","values":{"string":1,"number":1,"boolean":1,"color":1}},"array":{"type":"boolean"},"minValue":{"type":"number"},"maxValue":{"type":"number"},"stepValue":{"type":"number"},"values":{"type":"array","value":"*"},"metadata":{"type":"*"}},"models":{"*":{"type":"model"}},"light-3d":{"id":{"type":"string","required":true},"properties":{"type":"properties"},"type":{"type":"enum","values":{"ambient":{},"directional":{},"flat":{}}}},"properties":["properties_light_directional","properties_light_ambient","properties_light_flat"],"properties_light_directional":{"direction":{"type":"array","default":[210,30],"minimum":[0,0],"maximum":[360,90],"length":2,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"cast-shadows":{"type":"boolean","default":false,"expression":{},"property-type":"data-constant"},"shadow-intensity":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"properties_light_ambient":{"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"properties_light_flat":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"property-type":"data-constant","expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"sources":{"*":{"type":"source"}},"source":["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image","source_model"],"source_vector":{"type":{"required":true,"type":"enum","values":{"vector":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"scheme":{"type":"enum","values":{"xyz":1,"tms":1},"default":"xyz"},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"attribution":{"type":"string"},"promoteId":{"type":"promoteId"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_raster":{"type":{"required":true,"type":"enum","values":{"raster":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"tileSize":{"type":"number","default":512},"scheme":{"type":"enum","values":{"xyz":1,"tms":1},"default":"xyz"},"attribution":{"type":"string"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_raster_dem":{"type":{"required":true,"type":"enum","values":{"raster-dem":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"tileSize":{"type":"number","default":512},"attribution":{"type":"string"},"encoding":{"type":"enum","values":{"terrarium":1,"mapbox":1},"default":"mapbox"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_geojson":{"type":{"required":true,"type":"enum","values":{"geojson":1}},"data":{"type":"*"},"maxzoom":{"type":"number","default":18},"attribution":{"type":"string"},"buffer":{"type":"number","default":128,"maximum":512,"minimum":0},"filter":{"type":"*"},"tolerance":{"type":"number","default":0.375},"cluster":{"type":"boolean","default":false},"clusterRadius":{"type":"number","default":50,"minimum":0},"clusterMaxZoom":{"type":"number"},"clusterMinPoints":{"type":"number"},"clusterProperties":{"type":"*"},"lineMetrics":{"type":"boolean","default":false},"generateId":{"type":"boolean","default":false},"promoteId":{"type":"promoteId"}},"source_video":{"type":{"required":true,"type":"enum","values":{"video":1}},"urls":{"required":true,"type":"array","value":"string"},"coordinates":{"required":true,"type":"array","length":4,"value":{"type":"array","length":2,"value":"number"}}},"source_image":{"type":{"required":true,"type":"enum","values":{"image":1}},"url":{"required":false,"type":"string"},"coordinates":{"required":true,"type":"array","length":4,"value":{"type":"array","length":2,"value":"number"}}},"source_model":{"type":{"required":true,"type":"enum","values":{"model":1,"batched-model":1}},"maxzoom":{"type":"number","default":18},"minzoom":{"type":"number","default":0},"tiles":{"type":"array","value":"string"}},"layer":{"id":{"type":"string","required":true},"type":{"type":"enum","values":{"fill":{},"line":{},"symbol":{},"circle":{},"heatmap":{},"fill-extrusion":{},"raster":{},"hillshade":{},"model":{},"background":{},"sky":{},"slot":{}},"required":true},"metadata":{"type":"*"},"source":{"type":"string"},"source-layer":{"type":"string"},"slot":{"type":"string"},"minzoom":{"type":"number","minimum":0,"maximum":24},"maxzoom":{"type":"number","minimum":0,"maximum":24},"filter":{"type":"filter"},"layout":{"type":"layout"},"paint":{"type":"paint"}},"layout":["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background","layout_sky","layout_model"],"layout_background":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_sky":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_model":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"},"model-id":{"type":"string","default":"","property-type":"data-driven","expression":{"parameters":["zoom","feature"]}}},"layout_fill":{"fill-sort-key":{"type":"number","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_circle":{"circle-sort-key":{"type":"number","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_heatmap":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_fill-extrusion":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"},"fill-extrusion-edge-radius":{"type":"number","private":true,"default":0,"minimum":0,"maximum":1,"expression":{},"property-type":"constant"}},"layout_line":{"line-cap":{"type":"enum","values":{"butt":1,"round":1,"square":1},"default":"butt","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-join":{"type":"enum","values":{"bevel":1,"round":1,"miter":1},"default":"miter","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{"type":"number","default":2,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"line-round-limit":{"type":"number","default":1.05,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"line-sort-key":{"type":"number","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_symbol":{"symbol-placement":{"type":"enum","values":{"point":1,"line":1,"line-center":1},"default":"point","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"symbol-spacing":{"type":"number","default":250,"minimum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{"type":"number","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{"type":"enum","values":{"auto":1,"viewport-y":1,"source":1},"default":"auto","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"symbol-z-elevate":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-optional":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{"type":"enum","values":{"map":1,"viewport":1,"auto":1},"default":"auto","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-size":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{"type":"enum","values":{"none":1,"width":1,"height":1,"both":1},"default":"none","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit-padding":{"type":"array","value":"number","length":4,"default":[0,0,0,0],"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-image":{"type":"resolvedImage","tokens":true,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{"type":"number","default":0,"period":360,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{"type":"number","default":2,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"icon-keep-upright":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-offset":{"type":"array","value":"number","length":2,"default":[0,0],"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{"type":"enum","values":{"center":1,"left":1,"right":1,"top":1,"bottom":1,"top-left":1,"top-right":1,"bottom-left":1,"bottom-right":1},"default":"center","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1,"auto":1},"default":"auto","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1,"auto":1},"default":"auto","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{"type":"enum","values":{"map":1,"viewport":1,"auto":1},"default":"auto","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-field":{"type":"formatted","default":"","tokens":true,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-font":{"type":"array","value":"string","default":["Open Sans Regular","Arial Unicode MS Regular"],"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-size":{"type":"number","default":16,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{"type":"number","default":10,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{"type":"number","default":1.2,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-letter-spacing":{"type":"number","default":0,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-justify":{"type":"enum","values":{"auto":1,"left":1,"center":1,"right":1},"default":"center","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{"type":"number","default":0,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["zoom","feature"]}},"text-variable-anchor":{"type":"array","value":"enum","values":{"center":1,"left":1,"right":1,"top":1,"bottom":1,"top-left":1,"top-right":1,"bottom-left":1,"bottom-right":1},"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-anchor":{"type":"enum","values":{"center":1,"left":1,"right":1,"top":1,"bottom":1,"top-left":1,"top-right":1,"bottom-left":1,"bottom-right":1},"default":"center","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{"type":"number","default":45,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"text-writing-mode":{"type":"array","value":"enum","values":{"horizontal":1,"vertical":1},"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-rotate":{"type":"number","default":0,"period":360,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-padding":{"type":"number","default":2,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"text-keep-upright":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-transform":{"type":"enum","values":{"none":1,"uppercase":1,"lowercase":1},"default":"none","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-offset":{"type":"array","value":"number","length":2,"default":[0,0],"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"text-optional":{"type":"boolean","default":false,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_raster":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"layout_hillshade":{"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"}},"filter":{"type":"array","value":"*"},"filter_symbol":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature","pitch","distance-from-center"]}},"filter_fill":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_line":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_circle":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_fill-extrusion":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_heatmap":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_operator":{"type":"enum","values":{"==":1,"!=":1,">":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*","required":false}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"high-color":{"type":"color","property-type":"data-constant","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"space-color":{"type":"color","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"horizon-blend":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective","property-type":"data-constant"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"property-type":"data-constant","expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator","required":true},"center":{"type":"array","length":2,"value":"number","property-type":"data-constant","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","property-type":"data-constant","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string","required":true},"exaggeration":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"fill-extrusion-ambient-occlusion-intensity":{"property-type":"data-constant","type":"number","private":true,"default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"property-type":"data-constant","type":"number","private":true,"default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"property-type":"data-constant","type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"property-type":"data-constant","type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"property-type":"data-constant","type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"property-type":"data-constant","type":"color","default":"#ffffff","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"property-type":"data-constant","type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"property-type":"data-constant","type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"property-type":"data-constant","type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"property-type":"data-constant","type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{},"property-type":"data-constant"}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-gradient":{"type":"color","expression":{"interpolated":true,"parameters":["line-progress"]},"property-type":"color-ramp"},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"property-type":"constant"},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"line-border-width":{"type":"number","private":true,"default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","private":true,"default":"rgba(0, 0, 0, 0)","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"heatmap-color":{"type":"color","default":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"],"expression":{"interpolated":true,"parameters":["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"icon-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-image-cross-fade":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"transition":true},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-color":{"type":"color","expression":{"interpolated":true,"parameters":["raster-value"]},"property-type":"color-ramp"},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color-range":{"type":"array","default":[0,1],"length":2,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"hillshade-accent-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"}},"paint_background":{"background-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"}},"paint_sky":{"sky-type":{"type":"enum","values":{"gradient":1,"atmosphere":1},"default":"atmosphere","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"sky-atmosphere-sun":{"type":"array","value":"number","length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100,"property-type":"data-constant"},"sky-gradient-center":{"type":"array","value":"number","default":[0,0],"length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"sky-gradient-radius":{"type":"number","default":90,"minimum":0,"maximum":180,"expression":{"parameters":["zoom"]},"property-type":"data-constant"},"sky-gradient":{"type":"color","default":["interpolate",["linear"],["sky-radial-progress"],0.8,"#87ceeb",1,"white"],"expression":{"interpolated":true,"parameters":["sky-radial-progress"]},"property-type":"color-ramp"},"sky-atmosphere-halo-color":{"type":"color","default":"white","property-type":"data-constant"},"sky-atmosphere-color":{"type":"color","default":"white","property-type":"data-constant"},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"model-rotation":{"type":"array","value":"number","length":3,"default":[0,0,0],"period":360,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-scale":{"type":"array","value":"number","length":3,"default":[1,1,1],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-translation":{"type":"array","value":"number","length":3,"default":[0,0,0],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-color":{"type":"color","default":"#ffffff","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":true},"model-color-mix-intensity":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-type":{"type":"enum","values":{"common-3d":1,"location-indicator":1},"default":"common-3d","property-type":"data-constant"},"model-cast-shadows":{"type":"boolean","default":true,"expression":{},"property-type":"data-constant"},"model-receive-shadows":{"type":"boolean","default":true,"expression":{},"property-type":"data-constant"},"model-ambient-occlusion-intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant","transition":true},"model-emissive-strength":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state"]},"transition":true},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{},"property-type":"data-constant"}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"property-type":{"data-driven":{"type":"property-type"},"color-ramp":{"type":"property-type"},"data-constant":{"type":"property-type"},"constant":{"type":"property-type"}},"promoteId":{"*":{"type":"string"}}}');

//      
// Note: Do not inherit from Error. It breaks when transpiling to ES5.
class ValidationError {
    constructor(key, value, message, identifier) {
        this.message = (key ? `${ key }: ` : '') + message;
        if (identifier)
            this.identifier = identifier;
        if (value !== null && value !== undefined && value.__line__) {
            this.line = value.__line__;
        }
    }
}
class ValidationWarning extends ValidationError {
}

//      
function extend (output, ...inputs) {
    for (const input of inputs) {
        for (const k in input) {
            output[k] = input[k];
        }
    }
    return output;
}

//      
// Turn jsonlint-lines-primitives objects into primitive objects
function unbundle(value) {
    if (value instanceof Number || value instanceof String || value instanceof Boolean) {
        return value.valueOf();
    } else {
        return value;
    }
}
function deepUnbundle(value) {
    if (Array.isArray(value)) {
        return value.map(deepUnbundle);
    } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {
        const unbundledValue = {};
        for (const key in value) {
            unbundledValue[key] = deepUnbundle(value[key]);
        }
        return unbundledValue;
    }
    return unbundle(value);
}

//      
class ParsingError extends Error {
    constructor(key, message) {
        super(message);
        this.message = message;
        this.key = key;
    }
}
var ParsingError$1 = ParsingError;

//      
/**
 * Tracks `let` bindings during expression parsing.
 * @private
 */
class Scope {
    constructor(parent, bindings = []) {
        this.parent = parent;
        this.bindings = {};
        for (const [name, expression] of bindings) {
            this.bindings[name] = expression;
        }
    }
    concat(bindings) {
        return new Scope(this, bindings);
    }
    get(name) {
        if (this.bindings[name]) {
            return this.bindings[name];
        }
        if (this.parent) {
            return this.parent.get(name);
        }
        throw new Error(`${ name } not found in scope.`);
    }
    has(name) {
        if (this.bindings[name])
            return true;
        return this.parent ? this.parent.has(name) : false;
    }
}
var Scope$1 = Scope;

//      
const NullType = { kind: 'null' };
const NumberType = { kind: 'number' };
const StringType = { kind: 'string' };
const BooleanType = { kind: 'boolean' };
const ColorType = { kind: 'color' };
const ObjectType = { kind: 'object' };
const ValueType = { kind: 'value' };
const ErrorType = { kind: 'error' };
const CollatorType = { kind: 'collator' };
const FormattedType = { kind: 'formatted' };
const ResolvedImageType = { kind: 'resolvedImage' };
function array$1(itemType, N) {
    return {
        kind: 'array',
        itemType,
        N
    };
}
function toString$1(type) {
    if (type.kind === 'array') {
        const itemType = toString$1(type.itemType);
        return typeof type.N === 'number' ? `array<${ itemType }, ${ type.N }>` : type.itemType.kind === 'value' ? 'array' : `array<${ itemType }>`;
    } else {
        return type.kind;
    }
}
const valueMemberTypes = [
    NullType,
    NumberType,
    StringType,
    BooleanType,
    ColorType,
    FormattedType,
    ObjectType,
    array$1(ValueType),
    ResolvedImageType
];
/**
 * Returns null if `t` is a subtype of `expected`; otherwise returns an
 * error message.
 * @private
 */
function checkSubtype(expected, t) {
    if (t.kind === 'error') {
        // Error is a subtype of every type
        return null;
    } else if (expected.kind === 'array') {
        if (t.kind === 'array' && (t.N === 0 && t.itemType.kind === 'value' || !checkSubtype(expected.itemType, t.itemType)) && (typeof expected.N !== 'number' || expected.N === t.N)) {
            return null;
        }
    } else if (expected.kind === t.kind) {
        return null;
    } else if (expected.kind === 'value') {
        for (const memberType of valueMemberTypes) {
            if (!checkSubtype(memberType, t)) {
                return null;
            }
        }
    }
    return `Expected ${ toString$1(expected) } but found ${ toString$1(t) } instead.`;
}
function isValidType(provided, allowedTypes) {
    return allowedTypes.some(t => t.kind === provided.kind);
}
function isValidNativeType(provided, allowedTypes) {
    return allowedTypes.some(t => {
        if (t === 'null') {
            return provided === null;
        } else if (t === 'array') {
            return Array.isArray(provided);
        } else if (t === 'object') {
            return provided && !Array.isArray(provided) && typeof provided === 'object';
        } else {
            return t === typeof provided;
        }
    });
}

var csscolorparser = {};

var parseCSSColor_1;
// (c) Dean McNamee <dean@gmail.com>, 2012.
//
// https://github.com/deanm/css-color-parser-js
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// http://www.w3.org/TR/css3-color/
var kCSSColorTable = {
    'transparent': [
        0,
        0,
        0,
        0
    ],
    'aliceblue': [
        240,
        248,
        255,
        1
    ],
    'antiquewhite': [
        250,
        235,
        215,
        1
    ],
    'aqua': [
        0,
        255,
        255,
        1
    ],
    'aquamarine': [
        127,
        255,
        212,
        1
    ],
    'azure': [
        240,
        255,
        255,
        1
    ],
    'beige': [
        245,
        245,
        220,
        1
    ],
    'bisque': [
        255,
        228,
        196,
        1
    ],
    'black': [
        0,
        0,
        0,
        1
    ],
    'blanchedalmond': [
        255,
        235,
        205,
        1
    ],
    'blue': [
        0,
        0,
        255,
        1
    ],
    'blueviolet': [
        138,
        43,
        226,
        1
    ],
    'brown': [
        165,
        42,
        42,
        1
    ],
    'burlywood': [
        222,
        184,
        135,
        1
    ],
    'cadetblue': [
        95,
        158,
        160,
        1
    ],
    'chartreuse': [
        127,
        255,
        0,
        1
    ],
    'chocolate': [
        210,
        105,
        30,
        1
    ],
    'coral': [
        255,
        127,
        80,
        1
    ],
    'cornflowerblue': [
        100,
        149,
        237,
        1
    ],
    'cornsilk': [
        255,
        248,
        220,
        1
    ],
    'crimson': [
        220,
        20,
        60,
        1
    ],
    'cyan': [
        0,
        255,
        255,
        1
    ],
    'darkblue': [
        0,
        0,
        139,
        1
    ],
    'darkcyan': [
        0,
        139,
        139,
        1
    ],
    'darkgoldenrod': [
        184,
        134,
        11,
        1
    ],
    'darkgray': [
        169,
        169,
        169,
        1
    ],
    'darkgreen': [
        0,
        100,
        0,
        1
    ],
    'darkgrey': [
        169,
        169,
        169,
        1
    ],
    'darkkhaki': [
        189,
        183,
        107,
        1
    ],
    'darkmagenta': [
        139,
        0,
        139,
        1
    ],
    'darkolivegreen': [
        85,
        107,
        47,
        1
    ],
    'darkorange': [
        255,
        140,
        0,
        1
    ],
    'darkorchid': [
        153,
        50,
        204,
        1
    ],
    'darkred': [
        139,
        0,
        0,
        1
    ],
    'darksalmon': [
        233,
        150,
        122,
        1
    ],
    'darkseagreen': [
        143,
        188,
        143,
        1
    ],
    'darkslateblue': [
        72,
        61,
        139,
        1
    ],
    'darkslategray': [
        47,
        79,
        79,
        1
    ],
    'darkslategrey': [
        47,
        79,
        79,
        1
    ],
    'darkturquoise': [
        0,
        206,
        209,
        1
    ],
    'darkviolet': [
        148,
        0,
        211,
        1
    ],
    'deeppink': [
        255,
        20,
        147,
        1
    ],
    'deepskyblue': [
        0,
        191,
        255,
        1
    ],
    'dimgray': [
        105,
        105,
        105,
        1
    ],
    'dimgrey': [
        105,
        105,
        105,
        1
    ],
    'dodgerblue': [
        30,
        144,
        255,
        1
    ],
    'firebrick': [
        178,
        34,
        34,
        1
    ],
    'floralwhite': [
        255,
        250,
        240,
        1
    ],
    'forestgreen': [
        34,
        139,
        34,
        1
    ],
    'fuchsia': [
        255,
        0,
        255,
        1
    ],
    'gainsboro': [
        220,
        220,
        220,
        1
    ],
    'ghostwhite': [
        248,
        248,
        255,
        1
    ],
    'gold': [
        255,
        215,
        0,
        1
    ],
    'goldenrod': [
        218,
        165,
        32,
        1
    ],
    'gray': [
        128,
        128,
        128,
        1
    ],
    'green': [
        0,
        128,
        0,
        1
    ],
    'greenyellow': [
        173,
        255,
        47,
        1
    ],
    'grey': [
        128,
        128,
        128,
        1
    ],
    'honeydew': [
        240,
        255,
        240,
        1
    ],
    'hotpink': [
        255,
        105,
        180,
        1
    ],
    'indianred': [
        205,
        92,
        92,
        1
    ],
    'indigo': [
        75,
        0,
        130,
        1
    ],
    'ivory': [
        255,
        255,
        240,
        1
    ],
    'khaki': [
        240,
        230,
        140,
        1
    ],
    'lavender': [
        230,
        230,
        250,
        1
    ],
    'lavenderblush': [
        255,
        240,
        245,
        1
    ],
    'lawngreen': [
        124,
        252,
        0,
        1
    ],
    'lemonchiffon': [
        255,
        250,
        205,
        1
    ],
    'lightblue': [
        173,
        216,
        230,
        1
    ],
    'lightcoral': [
        240,
        128,
        128,
        1
    ],
    'lightcyan': [
        224,
        255,
        255,
        1
    ],
    'lightgoldenrodyellow': [
        250,
        250,
        210,
        1
    ],
    'lightgray': [
        211,
        211,
        211,
        1
    ],
    'lightgreen': [
        144,
        238,
        144,
        1
    ],
    'lightgrey': [
        211,
        211,
        211,
        1
    ],
    'lightpink': [
        255,
        182,
        193,
        1
    ],
    'lightsalmon': [
        255,
        160,
        122,
        1
    ],
    'lightseagreen': [
        32,
        178,
        170,
        1
    ],
    'lightskyblue': [
        135,
        206,
        250,
        1
    ],
    'lightslategray': [
        119,
        136,
        153,
        1
    ],
    'lightslategrey': [
        119,
        136,
        153,
        1
    ],
    'lightsteelblue': [
        176,
        196,
        222,
        1
    ],
    'lightyellow': [
        255,
        255,
        224,
        1
    ],
    'lime': [
        0,
        255,
        0,
        1
    ],
    'limegreen': [
        50,
        205,
        50,
        1
    ],
    'linen': [
        250,
        240,
        230,
        1
    ],
    'magenta': [
        255,
        0,
        255,
        1
    ],
    'maroon': [
        128,
        0,
        0,
        1
    ],
    'mediumaquamarine': [
        102,
        205,
        170,
        1
    ],
    'mediumblue': [
        0,
        0,
        205,
        1
    ],
    'mediumorchid': [
        186,
        85,
        211,
        1
    ],
    'mediumpurple': [
        147,
        112,
        219,
        1
    ],
    'mediumseagreen': [
        60,
        179,
        113,
        1
    ],
    'mediumslateblue': [
        123,
        104,
        238,
        1
    ],
    'mediumspringgreen': [
        0,
        250,
        154,
        1
    ],
    'mediumturquoise': [
        72,
        209,
        204,
        1
    ],
    'mediumvioletred': [
        199,
        21,
        133,
        1
    ],
    'midnightblue': [
        25,
        25,
        112,
        1
    ],
    'mintcream': [
        245,
        255,
        250,
        1
    ],
    'mistyrose': [
        255,
        228,
        225,
        1
    ],
    'moccasin': [
        255,
        228,
        181,
        1
    ],
    'navajowhite': [
        255,
        222,
        173,
        1
    ],
    'navy': [
        0,
        0,
        128,
        1
    ],
    'oldlace': [
        253,
        245,
        230,
        1
    ],
    'olive': [
        128,
        128,
        0,
        1
    ],
    'olivedrab': [
        107,
        142,
        35,
        1
    ],
    'orange': [
        255,
        165,
        0,
        1
    ],
    'orangered': [
        255,
        69,
        0,
        1
    ],
    'orchid': [
        218,
        112,
        214,
        1
    ],
    'palegoldenrod': [
        238,
        232,
        170,
        1
    ],
    'palegreen': [
        152,
        251,
        152,
        1
    ],
    'paleturquoise': [
        175,
        238,
        238,
        1
    ],
    'palevioletred': [
        219,
        112,
        147,
        1
    ],
    'papayawhip': [
        255,
        239,
        213,
        1
    ],
    'peachpuff': [
        255,
        218,
        185,
        1
    ],
    'peru': [
        205,
        133,
        63,
        1
    ],
    'pink': [
        255,
        192,
        203,
        1
    ],
    'plum': [
        221,
        160,
        221,
        1
    ],
    'powderblue': [
        176,
        224,
        230,
        1
    ],
    'purple': [
        128,
        0,
        128,
        1
    ],
    'rebeccapurple': [
        102,
        51,
        153,
        1
    ],
    'red': [
        255,
        0,
        0,
        1
    ],
    'rosybrown': [
        188,
        143,
        143,
        1
    ],
    'royalblue': [
        65,
        105,
        225,
        1
    ],
    'saddlebrown': [
        139,
        69,
        19,
        1
    ],
    'salmon': [
        250,
        128,
        114,
        1
    ],
    'sandybrown': [
        244,
        164,
        96,
        1
    ],
    'seagreen': [
        46,
        139,
        87,
        1
    ],
    'seashell': [
        255,
        245,
        238,
        1
    ],
    'sienna': [
        160,
        82,
        45,
        1
    ],
    'silver': [
        192,
        192,
        192,
        1
    ],
    'skyblue': [
        135,
        206,
        235,
        1
    ],
    'slateblue': [
        106,
        90,
        205,
        1
    ],
    'slategray': [
        112,
        128,
        144,
        1
    ],
    'slategrey': [
        112,
        128,
        144,
        1
    ],
    'snow': [
        255,
        250,
        250,
        1
    ],
    'springgreen': [
        0,
        255,
        127,
        1
    ],
    'steelblue': [
        70,
        130,
        180,
        1
    ],
    'tan': [
        210,
        180,
        140,
        1
    ],
    'teal': [
        0,
        128,
        128,
        1
    ],
    'thistle': [
        216,
        191,
        216,
        1
    ],
    'tomato': [
        255,
        99,
        71,
        1
    ],
    'turquoise': [
        64,
        224,
        208,
        1
    ],
    'violet': [
        238,
        130,
        238,
        1
    ],
    'wheat': [
        245,
        222,
        179,
        1
    ],
    'white': [
        255,
        255,
        255,
        1
    ],
    'whitesmoke': [
        245,
        245,
        245,
        1
    ],
    'yellow': [
        255,
        255,
        0,
        1
    ],
    'yellowgreen': [
        154,
        205,
        50,
        1
    ]
};
function clamp_css_byte(i) {
    // Clamp to integer 0 .. 255.
    i = Math.round(i);
    // Seems to be what Chrome does (vs truncation).
    return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clamp_css_float(f) {
    // Clamp to float 0.0 .. 1.0.
    return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parse_css_int(str) {
    // int or percentage.
    if (str[str.length - 1] === '%')
        return clamp_css_byte(parseFloat(str) / 100 * 255);
    return clamp_css_byte(parseInt(str));
}
function parse_css_float(str) {
    // float or percentage.
    if (str[str.length - 1] === '%')
        return clamp_css_float(parseFloat(str) / 100);
    return clamp_css_float(parseFloat(str));
}
function css_hue_to_rgb(m1, m2, h) {
    if (h < 0)
        h += 1;
    else if (h > 1)
        h -= 1;
    if (h * 6 < 1)
        return m1 + (m2 - m1) * h * 6;
    if (h * 2 < 1)
        return m2;
    if (h * 3 < 2)
        return m1 + (m2 - m1) * (2 / 3 - h) * 6;
    return m1;
}
function parseCSSColor(css_str) {
    // Remove all whitespace, not compliant, but should just be more accepting.
    var str = css_str.replace(/ /g, '').toLowerCase();
    // Color keywords (and transparent) lookup.
    if (str in kCSSColorTable)
        return kCSSColorTable[str].slice();
    // dup.
    // #abc and #abc123 syntax.
    if (str[0] === '#') {
        if (str.length === 4) {
            var iv = parseInt(str.substr(1), 16);
            // TODO(deanm): Stricter parsing.
            if (!(iv >= 0 && iv <= 4095))
                return null;
            // Covers NaN.
            return [
                (iv & 3840) >> 4 | (iv & 3840) >> 8,
                iv & 240 | (iv & 240) >> 4,
                iv & 15 | (iv & 15) << 4,
                1
            ];
        } else if (str.length === 7) {
            var iv = parseInt(str.substr(1), 16);
            // TODO(deanm): Stricter parsing.
            if (!(iv >= 0 && iv <= 16777215))
                return null;
            // Covers NaN.
            return [
                (iv & 16711680) >> 16,
                (iv & 65280) >> 8,
                iv & 255,
                1
            ];
        }
        return null;
    }
    var op = str.indexOf('('), ep = str.indexOf(')');
    if (op !== -1 && ep + 1 === str.length) {
        var fname = str.substr(0, op);
        var params = str.substr(op + 1, ep - (op + 1)).split(',');
        var alpha = 1;
        // To allow case fallthrough.
        switch (fname) {
        case 'rgba':
            if (params.length !== 4)
                return null;
            alpha = parse_css_float(params.pop());
        // Fall through.
        case 'rgb':
            if (params.length !== 3)
                return null;
            return [
                parse_css_int(params[0]),
                parse_css_int(params[1]),
                parse_css_int(params[2]),
                alpha
            ];
        case 'hsla':
            if (params.length !== 4)
                return null;
            alpha = parse_css_float(params.pop());
        // Fall through.
        case 'hsl':
            if (params.length !== 3)
                return null;
            var h = (parseFloat(params[0]) % 360 + 360) % 360 / 360;
            // 0 .. 1
            // NOTE(deanm): According to the CSS spec s/l should only be
            // percentages, but we don't bother and let float or percentage.
            var s = parse_css_float(params[1]);
            var l = parse_css_float(params[2]);
            var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
            var m1 = l * 2 - m2;
            return [
                clamp_css_byte(css_hue_to_rgb(m1, m2, h + 1 / 3) * 255),
                clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),
                clamp_css_byte(css_hue_to_rgb(m1, m2, h - 1 / 3) * 255),
                alpha
            ];
        default:
            return null;
        }
    }
    return null;
}
try {
    parseCSSColor_1 = csscolorparser.parseCSSColor = parseCSSColor;
} catch (e) {
}

//      
/**
 * An RGBA color value. Create instances from color strings using the static
 * method `Color.parse`. The constructor accepts RGB channel values in the range
 * `[0, 1]`, premultiplied by A.
 *
 * @param {number} r The red channel.
 * @param {number} g The green channel.
 * @param {number} b The blue channel.
 * @param {number} a The alpha channel.
 * @private
 */
class Color {
    constructor(r, g, b, a = 1) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }
    /**
     * Parses valid CSS color strings and returns a `Color` instance.
     * @returns A `Color` instance, or `undefined` if the input is not a valid color string.
     */
    static parse(input) {
        if (!input) {
            return undefined;
        }
        if (input instanceof Color) {
            return input;
        }
        if (typeof input !== 'string') {
            return undefined;
        }
        const rgba = parseCSSColor_1(input);
        if (!rgba) {
            return undefined;
        }
        return new Color(rgba[0] / 255 * rgba[3], rgba[1] / 255 * rgba[3], rgba[2] / 255 * rgba[3], rgba[3]);
    }
    /**
     * Returns an RGBA string representing the color value.
     *
     * @returns An RGBA string.
     * @example
     * var purple = new Color.parse('purple');
     * purple.toString; // = "rgba(128,0,128,1)"
     * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');
     * translucentGreen.toString(); // = "rgba(26,207,26,0.73)"
     */
    toString() {
        const [r, g, b, a] = this.toArray();
        return `rgba(${ Math.round(r) },${ Math.round(g) },${ Math.round(b) },${ a })`;
    }
    /**
     * Returns an RGBA array of values representing the color, unpremultiplied by A.
     *
     * @returns An array of RGBA color values in the range [0, 255].
     */
    toArray() {
        const {r, g, b, a} = this;
        return a === 0 ? [
            0,
            0,
            0,
            0
        ] : [
            r * 255 / a,
            g * 255 / a,
            b * 255 / a,
            a
        ];
    }
    /**
     * Returns a RGBA array of float values representing the color, unpremultiplied by A.
     *
     * @returns An array of RGBA color values in the range [0, 1].
     */
    toArray01() {
        const {r, g, b, a} = this;
        return a === 0 ? [
            0,
            0,
            0,
            0
        ] : [
            r / a,
            g / a,
            b / a,
            a
        ];
    }
    /**
     * Returns an RGB array of values representing the color, unpremultiplied by A and multiplied by a scalar.
     *
     * @param {number} scale A scale to apply to the unpremultiplied-alpha values.
     * @returns An array of RGB color values in the range [0, 1].
     */
    toArray01Scaled(scale) {
        const {r, g, b, a} = this;
        return a === 0 ? [
            0,
            0,
            0
        ] : [
            r / a * scale,
            g / a * scale,
            b / a * scale
        ];
    }
    /**
     * Returns an RGBA array of values representing the color, premultiplied by A.
     *
     * @returns An array of RGBA color values in the range [0, 1].
     */
    toArray01PremultipliedAlpha() {
        const {r, g, b, a} = this;
        return [
            r,
            g,
            b,
            a
        ];
    }
    /**
     * Returns an RGBA array of values representing the color, unpremultiplied by A, and converted to linear color space.
     * The color is defined by sRGB primaries, but the sRGB transfer function is reversed to obtain linear energy.
     *
     * @returns An array of RGBA color values in the range [0, 1].
     */
    toArray01Linear() {
        const {r, g, b, a} = this;
        return a === 0 ? [
            0,
            0,
            0,
            0
        ] : [
            Math.pow(r / a, 2.2),
            Math.pow(g / a, 2.2),
            Math.pow(b / a, 2.2),
            a
        ];
    }
}
Color.black = new Color(0, 0, 0, 1);
Color.white = new Color(1, 1, 1, 1);
Color.transparent = new Color(0, 0, 0, 0);
Color.red = new Color(1, 0, 0, 1);
Color.blue = new Color(0, 0, 1, 1);
var Color$1 = Color;

//      
// Flow type declarations for Intl cribbed from
// https://github.com/facebook/flow/issues/1270
class Collator {
    constructor(caseSensitive, diacriticSensitive, locale) {
        if (caseSensitive)
            this.sensitivity = diacriticSensitive ? 'variant' : 'case';
        else
            this.sensitivity = diacriticSensitive ? 'accent' : 'base';
        this.locale = locale;
        this.collator = new Intl.Collator(this.locale ? this.locale : [], {
            sensitivity: this.sensitivity,
            usage: 'search'
        });
    }
    compare(lhs, rhs) {
        return this.collator.compare(lhs, rhs);
    }
    resolvedLocale() {
        // We create a Collator without "usage: search" because we don't want
        // the search options encoded in our result (e.g. "en-u-co-search")
        return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale;
    }
}

//      
class FormattedSection {
    constructor(text, image, scale, fontStack, textColor) {
        // combine characters so that diacritic marks are not separate code points
        this.text = text.normalize ? text.normalize() : text;
        this.image = image;
        this.scale = scale;
        this.fontStack = fontStack;
        this.textColor = textColor;
    }
}
class Formatted {
    constructor(sections) {
        this.sections = sections;
    }
    static fromString(unformatted) {
        return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);
    }
    isEmpty() {
        if (this.sections.length === 0)
            return true;
        return !this.sections.some(section => section.text.length !== 0 || section.image && section.image.namePrimary.length !== 0);
    }
    static factory(text) {
        if (text instanceof Formatted) {
            return text;
        } else {
            return Formatted.fromString(text);
        }
    }
    toString() {
        if (this.sections.length === 0)
            return '';
        return this.sections.map(section => section.text).join('');
    }
    serialize() {
        const serialized = ['format'];
        for (const section of this.sections) {
            if (section.image) {
                serialized.push([
                    'image',
                    section.image.namePrimary
                ]);
                continue;
            }
            serialized.push(section.text);
            const options = {};
            if (section.fontStack) {
                options['text-font'] = [
                    'literal',
                    section.fontStack.split(',')
                ];
            }
            if (section.scale) {
                options['font-scale'] = section.scale;
            }
            if (section.textColor) {
                options['text-color'] = ['rgba'].concat(section.textColor.toArray());
            }
            serialized.push(options);
        }
        return serialized;
    }
}

//      
class ResolvedImage {
    constructor(options) {
        this.namePrimary = options.namePrimary;
        if (options.nameSecondary) {
            this.nameSecondary = options.nameSecondary;
        }
        this.available = options.available;
    }
    toString() {
        if (this.nameSecondary) {
            return `[${ this.namePrimary },${ this.nameSecondary }]`;
        }
        return this.namePrimary;
    }
    static fromString(namePrimary, nameSecondary) {
        if (!namePrimary)
            return null;
        // treat empty values as no image
        return new ResolvedImage({
            namePrimary,
            nameSecondary,
            available: false
        });
    }
    serialize() {
        if (this.nameSecondary) {
            return [
                'image',
                this.namePrimary,
                this.nameSecondary
            ];
        }
        return [
            'image',
            this.namePrimary
        ];
    }
}

function validateRGBA(r, g, b, a) {
    if (!(typeof r === 'number' && r >= 0 && r <= 255 && typeof g === 'number' && g >= 0 && g <= 255 && typeof b === 'number' && b >= 0 && b <= 255)) {
        const value = typeof a === 'number' ? [
            r,
            g,
            b,
            a
        ] : [
            r,
            g,
            b
        ];
        return `Invalid rgba value [${ value.join(', ') }]: 'r', 'g', and 'b' must be between 0 and 255.`;
    }
    if (!(typeof a === 'undefined' || typeof a === 'number' && a >= 0 && a <= 1)) {
        return `Invalid rgba value [${ [
            r,
            g,
            b,
            a
        ].join(', ') }]: 'a' must be between 0 and 1.`;
    }
    return null;
}
function validateHSLA(h, s, l, a) {
    if (!(typeof h === 'number' && h >= 0 && h <= 360)) {
        const value = typeof a === 'number' ? [
            h,
            s,
            l,
            a
        ] : [
            h,
            s,
            l
        ];
        return `Invalid hsla value [${ value.join(', ') }]: 'h' must be between 0 and 360.`;
    }
    if (!(typeof s === 'number' && s >= 0 && s <= 100 && typeof l === 'number' && l >= 0 && l <= 100)) {
        const value = typeof a === 'number' ? [
            h,
            s,
            l,
            a
        ] : [
            h,
            s,
            l
        ];
        return `Invalid hsla value [${ value.join(', ') }]: 's', and 'l' must be between 0 and 100.`;
    }
    if (!(typeof a === 'undefined' || typeof a === 'number' && a >= 0 && a <= 1)) {
        return `Invalid hsla value [${ [
            h,
            s,
            l,
            a
        ].join(', ') }]: 'a' must be between 0 and 1.`;
    }
    return null;
}
function isValue(mixed) {
    if (mixed === null) {
        return true;
    } else if (typeof mixed === 'string') {
        return true;
    } else if (typeof mixed === 'boolean') {
        return true;
    } else if (typeof mixed === 'number') {
        return true;
    } else if (mixed instanceof Color$1) {
        return true;
    } else if (mixed instanceof Collator) {
        return true;
    } else if (mixed instanceof Formatted) {
        return true;
    } else if (mixed instanceof ResolvedImage) {
        return true;
    } else if (Array.isArray(mixed)) {
        for (const item of mixed) {
            if (!isValue(item)) {
                return false;
            }
        }
        return true;
    } else if (typeof mixed === 'object') {
        for (const key in mixed) {
            if (!isValue(mixed[key])) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}
function typeOf(value) {
    if (value === null) {
        return NullType;
    } else if (typeof value === 'string') {
        return StringType;
    } else if (typeof value === 'boolean') {
        return BooleanType;
    } else if (typeof value === 'number') {
        return NumberType;
    } else if (value instanceof Color$1) {
        return ColorType;
    } else if (value instanceof Collator) {
        return CollatorType;
    } else if (value instanceof Formatted) {
        return FormattedType;
    } else if (value instanceof ResolvedImage) {
        return ResolvedImageType;
    } else if (Array.isArray(value)) {
        const length = value.length;
        let itemType;
        for (const item of value) {
            const t = typeOf(item);
            if (!itemType) {
                itemType = t;
            } else if (itemType === t) {
                continue;
            } else {
                itemType = ValueType;
                break;
            }
        }
        return array$1(itemType || ValueType, length);
    } else {
        return ObjectType;
    }
}
function toString(value) {
    const type = typeof value;
    if (value === null) {
        return '';
    } else if (type === 'string' || type === 'number' || type === 'boolean') {
        return String(value);
    } else if (value instanceof Color$1 || value instanceof Formatted || value instanceof ResolvedImage) {
        return value.toString();
    } else {
        return JSON.stringify(value);
    }
}

class Literal {
    constructor(type, value) {
        this.type = type;
        this.value = value;
    }
    static parse(args, context) {
        if (args.length !== 2)
            return context.error(`'literal' expression requires exactly one argument, but found ${ args.length - 1 } instead.`);
        if (!isValue(args[1]))
            return context.error(`invalid value`);
        const value = args[1];
        let type = typeOf(value);
        // special case: infer the item type if possible for zero-length arrays
        const expected = context.expectedType;
        if (type.kind === 'array' && type.N === 0 && expected && expected.kind === 'array' && (typeof expected.N !== 'number' || expected.N === 0)) {
            type = expected;
        }
        return new Literal(type, value);
    }
    evaluate() {
        return this.value;
    }
    eachChild() {
    }
    outputDefined() {
        return true;
    }
    serialize() {
        if (this.type.kind === 'array' || this.type.kind === 'object') {
            return [
                'literal',
                this.value
            ];
        } else if (this.value instanceof Color$1) {
            // Constant-folding can generate Literal expressions that you
            // couldn't actually generate with a "literal" expression,
            // so we have to implement an equivalent serialization here
            return ['rgba'].concat(this.value.toArray());
        } else if (this.value instanceof Formatted) {
            // Same as Color
            return this.value.serialize();
        } else {
            return this.value;
        }
    }
}
var Literal$1 = Literal;

//      
class RuntimeError {
    constructor(message) {
        this.name = 'ExpressionEvaluationError';
        this.message = message;
    }
    toJSON() {
        return this.message;
    }
}
var RuntimeError$1 = RuntimeError;

const types$1 = {
    string: StringType,
    number: NumberType,
    boolean: BooleanType,
    object: ObjectType
};
class Assertion {
    constructor(type, args) {
        this.type = type;
        this.args = args;
    }
    static parse(args, context) {
        if (args.length < 2)
            return context.error(`Expected at least one argument.`);
        let i = 1;
        let type;
        const name = args[0];
        if (name === 'array') {
            let itemType;
            if (args.length > 2) {
                const type = args[1];
                if (typeof type !== 'string' || !(type in types$1) || type === 'object')
                    return context.error('The item type argument of "array" must be one of string, number, boolean', 1);
                itemType = types$1[type];
                i++;
            } else {
                itemType = ValueType;
            }
            let N;
            if (args.length > 3) {
                if (args[2] !== null && (typeof args[2] !== 'number' || args[2] < 0 || args[2] !== Math.floor(args[2]))) {
                    return context.error('The length argument to "array" must be a positive integer literal', 2);
                }
                N = args[2];
                i++;
            }
            type = array$1(itemType, N);
        } else {
            type = types$1[name];
        }
        const parsed = [];
        for (; i < args.length; i++) {
            const input = context.parse(args[i], i, ValueType);
            if (!input)
                return null;
            parsed.push(input);
        }
        return new Assertion(type, parsed);
    }
    evaluate(ctx) {
        for (let i = 0; i < this.args.length; i++) {
            const value = this.args[i].evaluate(ctx);
            const error = checkSubtype(this.type, typeOf(value));
            if (!error) {
                return value;
            } else if (i === this.args.length - 1) {
                throw new RuntimeError$1(`Expected value to be of type ${ toString$1(this.type) }, but found ${ toString$1(typeOf(value)) } instead.`);
            }
        }
        return null;
    }
    eachChild(fn) {
        this.args.forEach(fn);
    }
    outputDefined() {
        return this.args.every(arg => arg.outputDefined());
    }
    serialize() {
        const type = this.type;
        const serialized = [type.kind];
        if (type.kind === 'array') {
            const itemType = type.itemType;
            if (itemType.kind === 'string' || itemType.kind === 'number' || itemType.kind === 'boolean') {
                serialized.push(itemType.kind);
                const N = type.N;
                if (typeof N === 'number' || this.args.length > 1) {
                    serialized.push(N);
                }
            }
        }
        return serialized.concat(this.args.map(arg => arg.serialize()));
    }
}
var Assertion$1 = Assertion;

//      
class FormatExpression {
    constructor(sections) {
        this.type = FormattedType;
        this.sections = sections;
    }
    static parse(args, context) {
        if (args.length < 2) {
            return context.error(`Expected at least one argument.`);
        }
        const firstArg = args[1];
        if (!Array.isArray(firstArg) && typeof firstArg === 'object') {
            return context.error(`First argument must be an image or text section.`);
        }
        const sections = [];
        let nextTokenMayBeObject = false;
        for (let i = 1; i <= args.length - 1; ++i) {
            const arg = args[i];
            if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) {
                nextTokenMayBeObject = false;
                let scale = null;
                if (arg['font-scale']) {
                    scale = context.parse(arg['font-scale'], 1, NumberType);
                    if (!scale)
                        return null;
                }
                let font = null;
                if (arg['text-font']) {
                    font = context.parse(arg['text-font'], 1, array$1(StringType));
                    if (!font)
                        return null;
                }
                let textColor = null;
                if (arg['text-color']) {
                    textColor = context.parse(arg['text-color'], 1, ColorType);
                    if (!textColor)
                        return null;
                }
                const lastExpression = sections[sections.length - 1];
                lastExpression.scale = scale;
                lastExpression.font = font;
                lastExpression.textColor = textColor;
            } else {
                const content = context.parse(args[i], 1, ValueType);
                if (!content)
                    return null;
                const kind = content.type.kind;
                if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')
                    return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`);
                nextTokenMayBeObject = true;
                sections.push({
                    content,
                    scale: null,
                    font: null,
                    textColor: null
                });
            }
        }
        return new FormatExpression(sections);
    }
    evaluate(ctx) {
        const evaluateSection = section => {
            const evaluatedContent = section.content.evaluate(ctx);
            if (typeOf(evaluatedContent) === ResolvedImageType) {
                return new FormattedSection('', evaluatedContent, null, null, null);
            }
            return new FormattedSection(toString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null);
        };
        return new Formatted(this.sections.map(evaluateSection));
    }
    eachChild(fn) {
        for (const section of this.sections) {
            fn(section.content);
            if (section.scale) {
                fn(section.scale);
            }
            if (section.font) {
                fn(section.font);
            }
            if (section.textColor) {
                fn(section.textColor);
            }
        }
    }
    outputDefined() {
        // Technically the combinatoric set of all children
        // Usually, this.text will be undefined anyway
        return false;
    }
    serialize() {
        const serialized = ['format'];
        for (const section of this.sections) {
            serialized.push(section.content.serialize());
            const options = {};
            if (section.scale) {
                options['font-scale'] = section.scale.serialize();
            }
            if (section.font) {
                options['text-font'] = section.font.serialize();
            }
            if (section.textColor) {
                options['text-color'] = section.textColor.serialize();
            }
            serialized.push(options);
        }
        return serialized;
    }
}

//      
class ImageExpression {
    constructor(inputPrimary, inputSecondary) {
        this.type = ResolvedImageType;
        this.inputPrimary = inputPrimary;
        this.inputSecondary = inputSecondary;
    }
    static parse(args, context) {
        if (args.length < 2) {
            return context.error(`Expected two or more arguments.`);
        }
        const namePrimary = context.parse(args[1], 1, StringType);
        if (!namePrimary)
            return context.error(`No image name provided.`);
        if (args.length === 2) {
            return new ImageExpression(namePrimary);
        }
        const nameSecondary = context.parse(args[2], 1, StringType);
        if (!nameSecondary)
            return context.error(`Secondary image variant is not a string.`);
        return new ImageExpression(namePrimary, nameSecondary);
    }
    evaluate(ctx) {
        const value = ResolvedImage.fromString(this.inputPrimary.evaluate(ctx), this.inputSecondary ? this.inputSecondary.evaluate(ctx) : undefined);
        if (value && ctx.availableImages) {
            value.available = ctx.availableImages.indexOf(value.namePrimary) > -1;
            // If there's a secondary variant, only mark it available if both are present
            if (value.nameSecondary && value.available && ctx.availableImages) {
                value.available = ctx.availableImages.indexOf(value.nameSecondary) > -1;
            }
        }
        return value;
    }
    eachChild(fn) {
        fn(this.inputPrimary);
        if (this.inputSecondary) {
            fn(this.inputSecondary);
        }
    }
    outputDefined() {
        // The output of image is determined by the list of available images in the evaluation context
        return false;
    }
    serialize() {
        if (this.inputSecondary) {
            // $FlowIgnore
            return [
                'image',
                this.inputPrimary.serialize(),
                this.inputSecondary.serialize()
            ];
        }
        return [
            'image',
            this.inputPrimary.serialize()
        ];
    }
}

//      
function getType$1(val) {
    if (val instanceof Number) {
        return 'number';
    } else if (val instanceof String) {
        return 'string';
    } else if (val instanceof Boolean) {
        return 'boolean';
    } else if (Array.isArray(val)) {
        return 'array';
    } else if (val === null) {
        return 'null';
    } else {
        return typeof val;
    }
}

const types = {
    'to-boolean': BooleanType,
    'to-color': ColorType,
    'to-number': NumberType,
    'to-string': StringType
};
/**
 * Special form for error-coalescing coercion expressions "to-number",
 * "to-color".  Since these coercions can fail at runtime, they accept multiple
 * arguments, only evaluating one at a time until one succeeds.
 *
 * @private
 */
class Coercion {
    constructor(type, args) {
        this.type = type;
        this.args = args;
    }
    static parse(args, context) {
        if (args.length < 2)
            return context.error(`Expected at least one argument.`);
        const name = args[0];
        const parsed = [];
        let type = NullType;
        if (name === 'to-array') {
            if (!Array.isArray(args[1])) {
                return null;
            }
            const arrayLength = args[1].length;
            if (context.expectedType) {
                if (context.expectedType.kind === 'array') {
                    type = array$1(context.expectedType.itemType, arrayLength);
                } else {
                    return context.error(`Expected ${ context.expectedType.kind } but found array.`);
                }
            } else if (arrayLength > 0 && isValue(args[1][0])) {
                const value = args[1][0];
                type = array$1(typeOf(value), arrayLength);
            } else {
                return null;
            }
            for (let i = 0; i < arrayLength; i++) {
                // $FlowIgnore
                const member = args[1][i];
                let parsedMember;
                if (getType$1(member) === 'array') {
                    parsedMember = context.parse(member, undefined, type.itemType);
                } else {
                    const memberType = getType$1(member);
                    if (memberType !== type.itemType.kind) {
                        return context.error(`Expected ${ type.itemType.kind } but found ${ memberType }.`);
                    }
                    parsedMember = context.registry['literal'].parse([
                        'literal',
                        member === undefined ? null : member
                    ], context);
                }
                if (!parsedMember)
                    return null;
                parsed.push(parsedMember);
            }
        } else {
            if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)
                return context.error(`Expected one argument.`);
            type = types[name];
            for (let i = 1; i < args.length; i++) {
                const input = context.parse(args[i], i, ValueType);
                if (!input)
                    return null;
                parsed.push(input);
            }
        }
        return new Coercion(type, parsed);
    }
    evaluate(ctx) {
        if (this.type.kind === 'boolean') {
            return Boolean(this.args[0].evaluate(ctx));
        } else if (this.type.kind === 'color') {
            let input;
            let error;
            for (const arg of this.args) {
                input = arg.evaluate(ctx);
                error = null;
                if (input instanceof Color$1) {
                    return input;
                } else if (typeof input === 'string') {
                    const c = ctx.parseColor(input);
                    if (c)
                        return c;
                } else if (Array.isArray(input)) {
                    if (input.length < 3 || input.length > 4) {
                        error = `Invalid rbga value ${ JSON.stringify(input) }: expected an array containing either three or four numeric values.`;
                    } else {
                        error = validateRGBA(input[0], input[1], input[2], input[3]);
                    }
                    if (!error) {
                        return new Color$1(input[0] / 255, input[1] / 255, input[2] / 255, input[3]);
                    }
                }
            }
            throw new RuntimeError$1(error || `Could not parse color from value '${ typeof input === 'string' ? input : String(JSON.stringify(input)) }'`);
        } else if (this.type.kind === 'number') {
            let value = null;
            for (const arg of this.args) {
                value = arg.evaluate(ctx);
                if (value === null)
                    return 0;
                const num = Number(value);
                if (isNaN(num))
                    continue;
                return num;
            }
            throw new RuntimeError$1(`Could not convert ${ JSON.stringify(value) } to number.`);
        } else if (this.type.kind === 'formatted') {
            // There is no explicit 'to-formatted' but this coercion can be implicitly
            // created by properties that expect the 'formatted' type.
            return Formatted.fromString(toString(this.args[0].evaluate(ctx)));
        } else if (this.type.kind === 'resolvedImage') {
            return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx)));
        } else if (this.type.kind === 'array') {
            return this.args.map(arg => {
                return arg.evaluate(ctx);
            });
        } else {
            return toString(this.args[0].evaluate(ctx));
        }
    }
    eachChild(fn) {
        this.args.forEach(fn);
    }
    outputDefined() {
        return this.args.every(arg => arg.outputDefined());
    }
    serialize() {
        if (this.type.kind === 'formatted') {
            return new FormatExpression([{
                    content: this.args[0],
                    scale: null,
                    font: null,
                    textColor: null
                }]).serialize();
        }
        if (this.type.kind === 'resolvedImage') {
            return new ImageExpression(this.args[0]).serialize();
        }
        const serialized = this.type.kind === 'array' ? [] : [`to-${ this.type.kind }`];
        this.eachChild(child => {
            serialized.push(child.serialize());
        });
        return serialized;
    }
}
var Coercion$1 = Coercion;

//      
const geometryTypes = [
    'Unknown',
    'Point',
    'LineString',
    'Polygon'
];
class EvaluationContext {
    constructor(options) {
        this.globals = null;
        this.feature = null;
        this.featureState = null;
        this.formattedSection = null;
        this._parseColorCache = {};
        this.availableImages = null;
        this.canonical = null;
        this.featureTileCoord = null;
        this.featureDistanceData = null;
        this.options = options;
    }
    id() {
        return this.feature && this.feature.id !== undefined ? this.feature.id : null;
    }
    geometryType() {
        return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;
    }
    geometry() {
        return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;
    }
    canonicalID() {
        return this.canonical;
    }
    properties() {
        return this.feature && this.feature.properties || {};
    }
    measureLight(_) {
        return this.globals.brightness || 0;
    }
    distanceFromCenter() {
        if (this.featureTileCoord && this.featureDistanceData) {
            const c = this.featureDistanceData.center;
            const scale = this.featureDistanceData.scale;
            const {x, y} = this.featureTileCoord;
            // Calculate the distance vector `d` (left handed)
            const dX = x * scale - c[0];
            const dY = y * scale - c[1];
            // The bearing vector `b` (left handed)
            const bX = this.featureDistanceData.bearing[0];
            const bY = this.featureDistanceData.bearing[1];
            // Distance is calculated as `dot(d, v)`
            const dist = bX * dX + bY * dY;
            return dist;
        }
        return 0;
    }
    parseColor(input) {
        let cached = this._parseColorCache[input];
        if (!cached) {
            cached = this._parseColorCache[input] = Color$1.parse(input);
        }
        return cached;
    }
    getConfig(id) {
        return this.options ? this.options.get(id) : null;
    }
}
var EvaluationContext$1 = EvaluationContext;

//      
class CompoundExpression {
    constructor(name, type, evaluate, args) {
        this.name = name;
        this.type = type;
        this._evaluate = evaluate;
        this.args = args;
    }
    evaluate(ctx) {
        return this._evaluate(ctx, this.args);
    }
    eachChild(fn) {
        this.args.forEach(fn);
    }
    outputDefined() {
        return false;
    }
    serialize() {
        return [this.name].concat(this.args.map(arg => arg.serialize()));
    }
    static parse(args, context) {
        const op = args[0];
        const definition = CompoundExpression.definitions[op];
        if (!definition) {
            return context.error(`Unknown expression "${ op }". If you wanted a literal array, use ["literal", [...]].`, 0);
        }
        // Now check argument types against each signature
        const type = Array.isArray(definition) ? definition[0] : definition.type;
        const availableOverloads = Array.isArray(definition) ? [[
                definition[1],
                definition[2]
            ]] : definition.overloads;
        const overloads = availableOverloads.filter(([signature]) => !Array.isArray(signature) || // varags
        signature.length === args.length - 1    // correct param count
);
        let signatureContext = null;
        for (const [params, evaluate] of overloads) {
            // Use a fresh context for each attempted signature so that, if
            // we eventually succeed, we haven't polluted `context.errors`.
            signatureContext = new ParsingContext$1(context.registry, context.path, null, context.scope, undefined, context.options);
            // First parse all the args, potentially coercing to the
            // types expected by this overload.
            const parsedArgs = [];
            let argParseFailed = false;
            for (let i = 1; i < args.length; i++) {
                const arg = args[i];
                const expectedType = Array.isArray(params) ? params[i - 1] : params.type;
                const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);
                if (!parsed) {
                    argParseFailed = true;
                    break;
                }
                parsedArgs.push(parsed);
            }
            if (argParseFailed) {
                // Couldn't coerce args of this overload to expected type, move
                // on to next one.
                continue;
            }
            if (Array.isArray(params)) {
                if (params.length !== parsedArgs.length) {
                    signatureContext.error(`Expected ${ params.length } arguments, but found ${ parsedArgs.length } instead.`);
                    continue;
                }
            }
            for (let i = 0; i < parsedArgs.length; i++) {
                const expected = Array.isArray(params) ? params[i] : params.type;
                const arg = parsedArgs[i];
                signatureContext.concat(i + 1).checkSubtype(expected, arg.type);
            }
            if (signatureContext.errors.length === 0) {
                return new CompoundExpression(op, type, evaluate, parsedArgs);
            }
        }
        if (overloads.length === 1) {
            context.errors.push(...signatureContext.errors);
        } else {
            const expected = overloads.length ? overloads : availableOverloads;
            const signatures = expected.map(([params]) => stringifySignature(params)).join(' | ');
            const actualTypes = [];
            // For error message, re-parse arguments without trying to
            // apply any coercions
            for (let i = 1; i < args.length; i++) {
                const parsed = context.parse(args[i], 1 + actualTypes.length);
                if (!parsed)
                    return null;
                actualTypes.push(toString$1(parsed.type));
            }
            context.error(`Expected arguments of type ${ signatures }, but found (${ actualTypes.join(', ') }) instead.`);
        }
        return null;
    }
    static register(registry, definitions) {
        CompoundExpression.definitions = definitions;
        for (const name in definitions) {
            // $FlowFixMe[method-unbinding]
            registry[name] = CompoundExpression;
        }
    }
}
function stringifySignature(signature) {
    if (Array.isArray(signature)) {
        return `(${ signature.map(toString$1).join(', ') })`;
    } else {
        return `(${ toString$1(signature.type) }...)`;
    }
}
var CompoundExpression$1 = CompoundExpression;

//      
class CollatorExpression {
    constructor(caseSensitive, diacriticSensitive, locale) {
        this.type = CollatorType;
        this.locale = locale;
        this.caseSensitive = caseSensitive;
        this.diacriticSensitive = diacriticSensitive;
    }
    static parse(args, context) {
        if (args.length !== 2)
            return context.error(`Expected one argument.`);
        const options = args[1];
        if (typeof options !== 'object' || Array.isArray(options))
            return context.error(`Collator options argument must be an object.`);
        const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);
        if (!caseSensitive)
            return null;
        const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);
        if (!diacriticSensitive)
            return null;
        let locale = null;
        if (options['locale']) {
            locale = context.parse(options['locale'], 1, StringType);
            if (!locale)
                return null;
        }
        return new CollatorExpression(caseSensitive, diacriticSensitive, locale);
    }
    evaluate(ctx) {
        return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);
    }
    eachChild(fn) {
        fn(this.caseSensitive);
        fn(this.diacriticSensitive);
        if (this.locale) {
            fn(this.locale);
        }
    }
    outputDefined() {
        // Technically the set of possible outputs is the combinatoric set of Collators produced
        // by all possible outputs of locale/caseSensitive/diacriticSensitive
        // But for the primary use of Collators in comparison operators, we ignore the Collator's
        // possible outputs anyway, so we can get away with leaving this false for now.
        return false;
    }
    serialize() {
        const options = {};
        options['case-sensitive'] = this.caseSensitive.serialize();
        options['diacritic-sensitive'] = this.diacriticSensitive.serialize();
        if (this.locale) {
            options['locale'] = this.locale.serialize();
        }
        return [
            'collator',
            options
        ];
    }
}

var quickselect$1 = {exports: {}};

(function (module, exports) {
	(function (global, factory) {
	    module.exports = factory() ;
	}(this, function () {
	    function quickselect(arr, k, left, right, compare) {
	        quickselectStep(arr, k, left || 0, right || arr.length - 1, compare || defaultCompare);
	    }
	    function quickselectStep(arr, k, left, right, compare) {
	        while (right > left) {
	            if (right - left > 600) {
	                var n = right - left + 1;
	                var m = k - left + 1;
	                var z = Math.log(n);
	                var s = 0.5 * Math.exp(2 * z / 3);
	                var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
	                var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
	                var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
	                quickselectStep(arr, k, newLeft, newRight, compare);
	            }
	            var t = arr[k];
	            var i = left;
	            var j = right;
	            swap(arr, left, k);
	            if (compare(arr[right], t) > 0)
	                swap(arr, left, right);
	            while (i < j) {
	                swap(arr, i, j);
	                i++;
	                j--;
	                while (compare(arr[i], t) < 0)
	                    i++;
	                while (compare(arr[j], t) > 0)
	                    j--;
	            }
	            if (compare(arr[left], t) === 0)
	                swap(arr, left, j);
	            else {
	                j++;
	                swap(arr, j, right);
	            }
	            if (j <= k)
	                left = j + 1;
	            if (k <= j)
	                right = j - 1;
	        }
	    }
	    function swap(arr, i, j) {
	        var tmp = arr[i];
	        arr[i] = arr[j];
	        arr[j] = tmp;
	    }
	    function defaultCompare(a, b) {
	        return a < b ? -1 : a > b ? 1 : 0;
	    }
	    return quickselect;
	})); 
} (quickselect$1));

var quickselectExports = quickselect$1.exports;
var quickselect = /*@__PURE__*/getDefaultExportFromCjs(quickselectExports);

//      
// minX, minY, maxX, maxY
/**
 * Returns the signed area for the polygon ring.  Postive areas are exterior rings and
 * have a clockwise winding.  Negative areas are interior rings and have a counter clockwise
 * ordering.
 */
function calculateSignedArea(ring) {
    let sum = 0;
    for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {
        p1 = ring[i];
        p2 = ring[j];
        sum += (p2.x - p1.x) * (p1.y + p2.y);
    }
    return sum;
}
function compareAreas$1(a, b) {
    return b.area - a.area;
}
// classifies an array of rings into polygons with outer rings and holes
function classifyRings$2(rings, maxRings) {
    const len = rings.length;
    if (len <= 1)
        return [rings];
    const polygons = [];
    let polygon, ccw;
    for (let i = 0; i < len; i++) {
        const area = calculateSignedArea(rings[i]);
        if (area === 0)
            continue;
        rings[i].area = Math.abs(area);
        if (ccw === undefined)
            ccw = area < 0;
        if (ccw === area < 0) {
            if (polygon)
                polygons.push(polygon);
            polygon = [rings[i]];
        } else {
            polygon.push(rings[i]);
        }
    }
    if (polygon)
        polygons.push(polygon);
    // Earcut performance degrades with the # of rings in a polygon. For this
    // reason, we limit strip out all but the `maxRings` largest rings.
    if (maxRings > 1) {
        for (let j = 0; j < polygons.length; j++) {
            if (polygons[j].length <= maxRings)
                continue;
            quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas$1);
            polygons[j] = polygons[j].slice(0, maxRings);
        }
    }
    return polygons;
}
function updateBBox(bbox, coord) {
    bbox[0] = Math.min(bbox[0], coord[0]);
    bbox[1] = Math.min(bbox[1], coord[1]);
    bbox[2] = Math.max(bbox[2], coord[0]);
    bbox[3] = Math.max(bbox[3], coord[1]);
}
function boxWithinBox(bbox1, bbox2) {
    if (bbox1[0] <= bbox2[0])
        return false;
    if (bbox1[2] >= bbox2[2])
        return false;
    if (bbox1[1] <= bbox2[1])
        return false;
    if (bbox1[3] >= bbox2[3])
        return false;
    return true;
}
function onBoundary(p, p1, p2) {
    const x1 = p[0] - p1[0];
    const y1 = p[1] - p1[1];
    const x2 = p[0] - p2[0];
    const y2 = p[1] - p2[1];
    return x1 * y2 - x2 * y1 === 0 && x1 * x2 <= 0 && y1 * y2 <= 0;
}
function rayIntersect(p, p1, p2) {
    return p1[1] > p[1] !== p2[1] > p[1] && p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0];
}
// ray casting algorithm for detecting if point is in polygon
function pointWithinPolygon(point, rings, trueOnBoundary = false) {
    let inside = false;
    for (let i = 0, len = rings.length; i < len; i++) {
        const ring = rings[i];
        for (let j = 0, len2 = ring.length, k = len2 - 1; j < len2; k = j++) {
            const q1 = ring[k];
            const q2 = ring[j];
            if (onBoundary(point, q1, q2))
                return trueOnBoundary;
            if (rayIntersect(point, q1, q2))
                inside = !inside;
        }
    }
    return inside;
}
function perp(v1, v2) {
    return v1[0] * v2[1] - v1[1] * v2[0];
}
// check if p1 and p2 are in different sides of line segment q1->q2
function twoSided(p1, p2, q1, q2) {
    // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)
    const x1 = p1[0] - q1[0];
    const y1 = p1[1] - q1[1];
    const x2 = p2[0] - q1[0];
    const y2 = p2[1] - q1[1];
    const x3 = q2[0] - q1[0];
    const y3 = q2[1] - q1[1];
    const det1 = x1 * y3 - x3 * y1;
    const det2 = x2 * y3 - x3 * y2;
    if (det1 > 0 && det2 < 0 || det1 < 0 && det2 > 0)
        return true;
    return false;
}
// a, b are end points for line segment1, c and d are end points for line segment2
function segmentIntersectSegment(a, b, c, d) {
    // check if two segments are parallel or not
    // precondition is end point a, b is inside polygon, if line a->b is
    // parallel to polygon edge c->d, then a->b won't intersect with c->d
    const vectorP = [
        b[0] - a[0],
        b[1] - a[1]
    ];
    const vectorQ = [
        d[0] - c[0],
        d[1] - c[1]
    ];
    if (perp(vectorQ, vectorP) === 0)
        return false;
    // If lines are intersecting with each other, the relative location should be:
    // a and b lie in different sides of segment c->d
    // c and d lie in different sides of segment a->b
    if (twoSided(a, b, c, d) && twoSided(c, d, a, b))
        return true;
    return false;
}

//      
const EXTENT$1 = 8192;
function mercatorXfromLng$1(lng) {
    return (180 + lng) / 360;
}
function mercatorYfromLat$1(lat) {
    return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
}
function getTileCoordinates(p, canonical) {
    const x = mercatorXfromLng$1(p[0]);
    const y = mercatorYfromLat$1(p[1]);
    const tilesAtZoom = Math.pow(2, canonical.z);
    return [
        Math.round(x * tilesAtZoom * EXTENT$1),
        Math.round(y * tilesAtZoom * EXTENT$1)
    ];
}
function pointWithinPolygons(point, polygons) {
    for (let i = 0; i < polygons.length; i++) {
        if (pointWithinPolygon(point, polygons[i]))
            return true;
    }
    return false;
}
function lineIntersectPolygon(p1, p2, polygon) {
    for (const ring of polygon) {
        // loop through every edge of the ring
        for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) {
            const q1 = ring[k];
            const q2 = ring[j];
            if (segmentIntersectSegment(p1, p2, q1, q2)) {
                return true;
            }
        }
    }
    return false;
}
function lineStringWithinPolygon(line, polygon) {
    // First, check if geometry points of line segments are all inside polygon
    for (let i = 0; i < line.length; ++i) {
        if (!pointWithinPolygon(line[i], polygon)) {
            return false;
        }
    }
    // Second, check if there is line segment intersecting polygon edge
    for (let i = 0; i < line.length - 1; ++i) {
        if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {
            return false;
        }
    }
    return true;
}
function lineStringWithinPolygons(line, polygons) {
    for (let i = 0; i < polygons.length; i++) {
        if (lineStringWithinPolygon(line, polygons[i]))
            return true;
    }
    return false;
}
function getTilePolygon(coordinates, bbox, canonical) {
    const polygon = [];
    for (let i = 0; i < coordinates.length; i++) {
        const ring = [];
        for (let j = 0; j < coordinates[i].length; j++) {
            const coord = getTileCoordinates(coordinates[i][j], canonical);
            updateBBox(bbox, coord);
            ring.push(coord);
        }
        polygon.push(ring);
    }
    return polygon;
}
function getTilePolygons(coordinates, bbox, canonical) {
    const polygons = [];
    for (let i = 0; i < coordinates.length; i++) {
        const polygon = getTilePolygon(coordinates[i], bbox, canonical);
        polygons.push(polygon);
    }
    return polygons;
}
function updatePoint(p, bbox, polyBBox, worldSize) {
    if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {
        const halfWorldSize = worldSize * 0.5;
        let shift = p[0] - polyBBox[0] > halfWorldSize ? -worldSize : polyBBox[0] - p[0] > halfWorldSize ? worldSize : 0;
        if (shift === 0) {
            shift = p[0] - polyBBox[2] > halfWorldSize ? -worldSize : polyBBox[2] - p[0] > halfWorldSize ? worldSize : 0;
        }
        p[0] += shift;
    }
    updateBBox(bbox, p);
}
function resetBBox(bbox) {
    bbox[0] = bbox[1] = Infinity;
    bbox[2] = bbox[3] = -Infinity;
}
function getTilePoints(geometry, pointBBox, polyBBox, canonical) {
    const worldSize = Math.pow(2, canonical.z) * EXTENT$1;
    const shifts = [
        canonical.x * EXTENT$1,
        canonical.y * EXTENT$1
    ];
    const tilePoints = [];
    if (!geometry)
        return tilePoints;
    for (const points of geometry) {
        for (const point of points) {
            const p = [
                point.x + shifts[0],
                point.y + shifts[1]
            ];
            updatePoint(p, pointBBox, polyBBox, worldSize);
            tilePoints.push(p);
        }
    }
    return tilePoints;
}
function getTileLines(geometry, lineBBox, polyBBox, canonical) {
    const worldSize = Math.pow(2, canonical.z) * EXTENT$1;
    const shifts = [
        canonical.x * EXTENT$1,
        canonical.y * EXTENT$1
    ];
    const tileLines = [];
    if (!geometry)
        return tileLines;
    for (const line of geometry) {
        const tileLine = [];
        for (const point of line) {
            const p = [
                point.x + shifts[0],
                point.y + shifts[1]
            ];
            updateBBox(lineBBox, p);
            tileLine.push(p);
        }
        tileLines.push(tileLine);
    }
    if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {
        resetBBox(lineBBox);
        for (const line of tileLines) {
            for (const p of line) {
                updatePoint(p, lineBBox, polyBBox, worldSize);
            }
        }
    }
    return tileLines;
}
function pointsWithinPolygons(ctx, polygonGeometry) {
    const pointBBox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    const polyBBox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    const canonical = ctx.canonicalID();
    if (!canonical) {
        return false;
    }
    if (polygonGeometry.type === 'Polygon') {
        const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
        const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
        if (!boxWithinBox(pointBBox, polyBBox))
            return false;
        for (const point of tilePoints) {
            if (!pointWithinPolygon(point, tilePolygon))
                return false;
        }
    }
    if (polygonGeometry.type === 'MultiPolygon') {
        const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
        const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
        if (!boxWithinBox(pointBBox, polyBBox))
            return false;
        for (const point of tilePoints) {
            if (!pointWithinPolygons(point, tilePolygons))
                return false;
        }
    }
    return true;
}
function linesWithinPolygons(ctx, polygonGeometry) {
    const lineBBox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    const polyBBox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    const canonical = ctx.canonicalID();
    if (!canonical) {
        return false;
    }
    if (polygonGeometry.type === 'Polygon') {
        const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
        const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
        if (!boxWithinBox(lineBBox, polyBBox))
            return false;
        for (const line of tileLines) {
            if (!lineStringWithinPolygon(line, tilePolygon))
                return false;
        }
    }
    if (polygonGeometry.type === 'MultiPolygon') {
        const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
        const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
        if (!boxWithinBox(lineBBox, polyBBox))
            return false;
        for (const line of tileLines) {
            if (!lineStringWithinPolygons(line, tilePolygons))
                return false;
        }
    }
    return true;
}
class Within {
    constructor(geojson, geometries) {
        this.type = BooleanType;
        this.geojson = geojson;
        this.geometries = geometries;
    }
    static parse(args, context) {
        if (args.length !== 2)
            return context.error(`'within' expression requires exactly one argument, but found ${ args.length - 1 } instead.`);
        if (isValue(args[1])) {
            const geojson = args[1];
            if (geojson.type === 'FeatureCollection') {
                for (let i = 0; i < geojson.features.length; ++i) {
                    const type = geojson.features[i].geometry.type;
                    if (type === 'Polygon' || type === 'MultiPolygon') {
                        return new Within(geojson, geojson.features[i].geometry);
                    }
                }
            } else if (geojson.type === 'Feature') {
                const type = geojson.geometry.type;
                if (type === 'Polygon' || type === 'MultiPolygon') {
                    return new Within(geojson, geojson.geometry);
                }
            } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {
                return new Within(geojson, geojson);
            }
        }
        return context.error(`'within' expression requires valid geojson object that contains polygon geometry type.`);
    }
    evaluate(ctx) {
        if (ctx.geometry() != null && ctx.canonicalID() != null) {
            if (ctx.geometryType() === 'Point') {
                return pointsWithinPolygons(ctx, this.geometries);
            } else if (ctx.geometryType() === 'LineString') {
                return linesWithinPolygons(ctx, this.geometries);
            }
        }
        return false;
    }
    eachChild() {
    }
    outputDefined() {
        return true;
    }
    serialize() {
        return [
            'within',
            this.geojson
        ];
    }
}
var Within$1 = Within;

var cheapRuler = {exports: {}};

(function (module, exports) {
	(function (global, factory) {
	    module.exports = factory() ;
	}(this, function () {
	    var factors = {
	        kilometers: 1,
	        miles: 1000 / 1609.344,
	        nauticalmiles: 1000 / 1852,
	        meters: 1000,
	        metres: 1000,
	        yards: 1000 / 0.9144,
	        feet: 1000 / 0.3048,
	        inches: 1000 / 0.0254
	    };
	    // Values that define WGS84 ellipsoid model of the Earth
	    var RE = 6378.137;
	    // equatorial radius
	    var FE = 1 / 298.257223563;
	    // flattening
	    var E2 = FE * (2 - FE);
	    var RAD = Math.PI / 180;
	    /**
	 * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale.
	 *
	 * @param {number} lat latitude
	 * @param {string} [units='kilometers']
	 * @returns {CheapRuler}
	 * @example
	 * const ruler = cheapRuler(35.05, 'miles');
	 * //=ruler
	 */
	    var CheapRuler = function CheapRuler(lat, units) {
	        if (lat === undefined) {
	            throw new Error('No latitude given.');
	        }
	        if (units && !factors[units]) {
	            throw new Error('Unknown unit ' + units + '. Use one of: ' + Object.keys(factors).join(', '));
	        }
	        // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional
	        var m = RAD * RE * (units ? factors[units] : 1);
	        var coslat = Math.cos(lat * RAD);
	        var w2 = 1 / (1 - E2 * (1 - coslat * coslat));
	        var w = Math.sqrt(w2);
	        // multipliers for converting longitude and latitude degrees into distance
	        this.kx = m * w * coslat;
	        // based on normal radius of curvature
	        this.ky = m * w * w2 * (1 - E2);    // based on meridonal radius of curvature
	    };
	    var staticAccessors = { units: { configurable: true } };
	    /**
	 * Given two points of the form [longitude, latitude], returns the distance.
	 *
	 * @param {Array<number>} a point [longitude, latitude]
	 * @param {Array<number>} b point [longitude, latitude]
	 * @returns {number} distance
	 * @example
	 * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);
	 * //=distance
	 */
	    CheapRuler.fromTile = function fromTile(y, z, units) {
	        var n = Math.PI * (1 - 2 * (y + 0.5) / Math.pow(2, z));
	        var lat = Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))) / RAD;
	        return new CheapRuler(lat, units);
	    };
	    /**
	 * Multipliers for converting between units.
	 *
	 * @example
	 * // convert 50 meters to yards
	 * 50 * CheapRuler.units.yards / CheapRuler.units.meters;
	 */
	    staticAccessors.units.get = function () {
	        return factors;
	    };
	    CheapRuler.prototype.distance = function distance(a, b) {
	        var dx = wrap(a[0] - b[0]) * this.kx;
	        var dy = (a[1] - b[1]) * this.ky;
	        return Math.sqrt(dx * dx + dy * dy);
	    };
	    /**
	 * Returns the bearing between two points in angles.
	 *
	 * @param {Array<number>} a point [longitude, latitude]
	 * @param {Array<number>} b point [longitude, latitude]
	 * @returns {number} bearing
	 * @example
	 * const bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]);
	 * //=bearing
	 */
	    CheapRuler.prototype.bearing = function bearing(a, b) {
	        var dx = wrap(b[0] - a[0]) * this.kx;
	        var dy = (b[1] - a[1]) * this.ky;
	        return Math.atan2(dx, dy) / RAD;
	    };
	    /**
	 * Returns a new point given distance and bearing from the starting point.
	 *
	 * @param {Array<number>} p point [longitude, latitude]
	 * @param {number} dist distance
	 * @param {number} bearing
	 * @returns {Array<number>} point [longitude, latitude]
	 * @example
	 * const point = ruler.destination([30.5, 50.5], 0.1, 90);
	 * //=point
	 */
	    CheapRuler.prototype.destination = function destination(p, dist, bearing) {
	        var a = bearing * RAD;
	        return this.offset(p, Math.sin(a) * dist, Math.cos(a) * dist);
	    };
	    /**
	 * Returns a new point given easting and northing offsets (in ruler units) from the starting point.
	 *
	 * @param {Array<number>} p point [longitude, latitude]
	 * @param {number} dx easting
	 * @param {number} dy northing
	 * @returns {Array<number>} point [longitude, latitude]
	 * @example
	 * const point = ruler.offset([30.5, 50.5], 10, 10);
	 * //=point
	 */
	    CheapRuler.prototype.offset = function offset(p, dx, dy) {
	        return [
	            p[0] + dx / this.kx,
	            p[1] + dy / this.ky
	        ];
	    };
	    /**
	 * Given a line (an array of points), returns the total line distance.
	 *
	 * @param {Array<Array<number>>} points [longitude, latitude]
	 * @returns {number} total line distance
	 * @example
	 * const length = ruler.lineDistance([
	 * [-67.031, 50.458], [-67.031, 50.534],
	 * [-66.929, 50.534], [-66.929, 50.458]
	 * ]);
	 * //=length
	 */
	    CheapRuler.prototype.lineDistance = function lineDistance(points) {
	        var total = 0;
	        for (var i = 0; i < points.length - 1; i++) {
	            total += this.distance(points[i], points[i + 1]);
	        }
	        return total;
	    };
	    /**
	 * Given a polygon (an array of rings, where each ring is an array of points), returns the area.
	 *
	 * @param {Array<Array<Array<number>>>} polygon
	 * @returns {number} area value in the specified units (square kilometers by default)
	 * @example
	 * const area = ruler.area([[
	 * [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534],
	 * [-66.929, 50.458], [-67.031, 50.458]
	 * ]]);
	 * //=area
	 */
	    CheapRuler.prototype.area = function area(polygon) {
	        var sum = 0;
	        for (var i = 0; i < polygon.length; i++) {
	            var ring = polygon[i];
	            for (var j = 0, len = ring.length, k = len - 1; j < len; k = j++) {
	                sum += wrap(ring[j][0] - ring[k][0]) * (ring[j][1] + ring[k][1]) * (i ? -1 : 1);
	            }
	        }
	        return Math.abs(sum) / 2 * this.kx * this.ky;
	    };
	    /**
	 * Returns the point at a specified distance along the line.
	 *
	 * @param {Array<Array<number>>} line
	 * @param {number} dist distance
	 * @returns {Array<number>} point [longitude, latitude]
	 * @example
	 * const point = ruler.along(line, 2.5);
	 * //=point
	 */
	    CheapRuler.prototype.along = function along(line, dist) {
	        var sum = 0;
	        if (dist <= 0) {
	            return line[0];
	        }
	        for (var i = 0; i < line.length - 1; i++) {
	            var p0 = line[i];
	            var p1 = line[i + 1];
	            var d = this.distance(p0, p1);
	            sum += d;
	            if (sum > dist) {
	                return interpolate(p0, p1, (dist - (sum - d)) / d);
	            }
	        }
	        return line[line.length - 1];
	    };
	    /**
	 * Returns the distance from a point `p` to a line segment `a` to `b`.
	 *
	 * @pointToSegmentDistance
	 * @param {Array<number>} p point [longitude, latitude]
	 * @param {Array<number>} p1 segment point 1 [longitude, latitude]
	 * @param {Array<number>} p2 segment point 2 [longitude, latitude]
	 * @returns {number} distance
	 * @example
	 * const distance = ruler.pointToSegmentDistance([-67.04, 50.5], [-67.05, 50.57], [-67.03, 50.54]);
	 * //=distance
	 */
	    CheapRuler.prototype.pointToSegmentDistance = function pointToSegmentDistance(p, a, b) {
	        var x = a[0];
	        var y = a[1];
	        var dx = wrap(b[0] - x) * this.kx;
	        var dy = (b[1] - y) * this.ky;
	        var t = 0;
	        if (dx !== 0 || dy !== 0) {
	            t = (wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy);
	            if (t > 1) {
	                x = b[0];
	                y = b[1];
	            } else if (t > 0) {
	                x += dx / this.kx * t;
	                y += dy / this.ky * t;
	            }
	        }
	        dx = wrap(p[0] - x) * this.kx;
	        dy = (p[1] - y) * this.ky;
	        return Math.sqrt(dx * dx + dy * dy);
	    };
	    /**
	 * Returns an object of the form {point, index, t}, where point is closest point on the line
	 * from the given point, index is the start index of the segment with the closest point,
	 * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment.
	 *
	 * @param {Array<Array<number>>} line
	 * @param {Array<number>} p point [longitude, latitude]
	 * @returns {Object} {point, index, t}
	 * @example
	 * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point;
	 * //=point
	 */
	    CheapRuler.prototype.pointOnLine = function pointOnLine(line, p) {
	        var minDist = Infinity;
	        var minX, minY, minI, minT;
	        for (var i = 0; i < line.length - 1; i++) {
	            var x = line[i][0];
	            var y = line[i][1];
	            var dx = wrap(line[i + 1][0] - x) * this.kx;
	            var dy = (line[i + 1][1] - y) * this.ky;
	            var t = 0;
	            if (dx !== 0 || dy !== 0) {
	                t = (wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy);
	                if (t > 1) {
	                    x = line[i + 1][0];
	                    y = line[i + 1][1];
	                } else if (t > 0) {
	                    x += dx / this.kx * t;
	                    y += dy / this.ky * t;
	                }
	            }
	            dx = wrap(p[0] - x) * this.kx;
	            dy = (p[1] - y) * this.ky;
	            var sqDist = dx * dx + dy * dy;
	            if (sqDist < minDist) {
	                minDist = sqDist;
	                minX = x;
	                minY = y;
	                minI = i;
	                minT = t;
	            }
	        }
	        return {
	            point: [
	                minX,
	                minY
	            ],
	            index: minI,
	            t: Math.max(0, Math.min(1, minT))
	        };
	    };
	    /**
	 * Returns a part of the given line between the start and the stop points (or their closest points on the line).
	 *
	 * @param {Array<number>} start point [longitude, latitude]
	 * @param {Array<number>} stop point [longitude, latitude]
	 * @param {Array<Array<number>>} line
	 * @returns {Array<Array<number>>} line part of a line
	 * @example
	 * const line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1);
	 * //=line2
	 */
	    CheapRuler.prototype.lineSlice = function lineSlice(start, stop, line) {
	        var p1 = this.pointOnLine(line, start);
	        var p2 = this.pointOnLine(line, stop);
	        if (p1.index > p2.index || p1.index === p2.index && p1.t > p2.t) {
	            var tmp = p1;
	            p1 = p2;
	            p2 = tmp;
	        }
	        var slice = [p1.point];
	        var l = p1.index + 1;
	        var r = p2.index;
	        if (!equals(line[l], slice[0]) && l <= r) {
	            slice.push(line[l]);
	        }
	        for (var i = l + 1; i <= r; i++) {
	            slice.push(line[i]);
	        }
	        if (!equals(line[r], p2.point)) {
	            slice.push(p2.point);
	        }
	        return slice;
	    };
	    /**
	 * Returns a part of the given line between the start and the stop points indicated by distance along the line.
	 *
	 * @param {number} start distance
	 * @param {number} stop distance
	 * @param {Array<Array<number>>} line
	 * @returns {Array<Array<number>>} line part of a line
	 * @example
	 * const line2 = ruler.lineSliceAlong(10, 20, line1);
	 * //=line2
	 */
	    CheapRuler.prototype.lineSliceAlong = function lineSliceAlong(start, stop, line) {
	        var sum = 0;
	        var slice = [];
	        for (var i = 0; i < line.length - 1; i++) {
	            var p0 = line[i];
	            var p1 = line[i + 1];
	            var d = this.distance(p0, p1);
	            sum += d;
	            if (sum > start && slice.length === 0) {
	                slice.push(interpolate(p0, p1, (start - (sum - d)) / d));
	            }
	            if (sum >= stop) {
	                slice.push(interpolate(p0, p1, (stop - (sum - d)) / d));
	                return slice;
	            }
	            if (sum > start) {
	                slice.push(p1);
	            }
	        }
	        return slice;
	    };
	    /**
	 * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance.
	 *
	 * @param {Array<number>} p point [longitude, latitude]
	 * @param {number} buffer
	 * @returns {Array<number>} box object ([w, s, e, n])
	 * @example
	 * const bbox = ruler.bufferPoint([30.5, 50.5], 0.01);
	 * //=bbox
	 */
	    CheapRuler.prototype.bufferPoint = function bufferPoint(p, buffer) {
	        var v = buffer / this.ky;
	        var h = buffer / this.kx;
	        return [
	            p[0] - h,
	            p[1] - v,
	            p[0] + h,
	            p[1] + v
	        ];
	    };
	    /**
	 * Given a bounding box, returns the box buffered by a given distance.
	 *
	 * @param {Array<number>} box object ([w, s, e, n])
	 * @param {number} buffer
	 * @returns {Array<number>} box object ([w, s, e, n])
	 * @example
	 * const bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2);
	 * //=bbox
	 */
	    CheapRuler.prototype.bufferBBox = function bufferBBox(bbox, buffer) {
	        var v = buffer / this.ky;
	        var h = buffer / this.kx;
	        return [
	            bbox[0] - h,
	            bbox[1] - v,
	            bbox[2] + h,
	            bbox[3] + v
	        ];
	    };
	    /**
	 * Returns true if the given point is inside in the given bounding box, otherwise false.
	 *
	 * @param {Array<number>} p point [longitude, latitude]
	 * @param {Array<number>} box object ([w, s, e, n])
	 * @returns {boolean}
	 * @example
	 * const inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]);
	 * //=inside
	 */
	    CheapRuler.prototype.insideBBox = function insideBBox(p, bbox) {
	        return wrap(p[0] - bbox[0]) >= 0 && wrap(p[0] - bbox[2]) <= 0 && p[1] >= bbox[1] && p[1] <= bbox[3];
	    };
	    Object.defineProperties(CheapRuler, staticAccessors);
	    function equals(a, b) {
	        return a[0] === b[0] && a[1] === b[1];
	    }
	    function interpolate(a, b, t) {
	        var dx = wrap(b[0] - a[0]);
	        var dy = b[1] - a[1];
	        return [
	            a[0] + dx * t,
	            a[1] + dy * t
	        ];
	    }
	    // normalize a degree value into [-180..180] range
	    function wrap(deg) {
	        while (deg < -180) {
	            deg += 360;
	        }
	        while (deg > 180) {
	            deg -= 360;
	        }
	        return deg;
	    }
	    return CheapRuler;
	})); 
} (cheapRuler));

var cheapRulerExports = cheapRuler.exports;
var CheapRuler = /*@__PURE__*/getDefaultExportFromCjs(cheapRulerExports);

var tinyqueue = {exports: {}};

(function (module, exports) {
	(function (global, factory) {
	    module.exports = factory() ;
	}(this, function () {
	    var TinyQueue = function TinyQueue(data, compare) {
	        if (data === void 0)
	            data = [];
	        if (compare === void 0)
	            compare = defaultCompare;
	        this.data = data;
	        this.length = this.data.length;
	        this.compare = compare;
	        if (this.length > 0) {
	            for (var i = (this.length >> 1) - 1; i >= 0; i--) {
	                this._down(i);
	            }
	        }
	    };
	    TinyQueue.prototype.push = function push(item) {
	        this.data.push(item);
	        this.length++;
	        this._up(this.length - 1);
	    };
	    TinyQueue.prototype.pop = function pop() {
	        if (this.length === 0) {
	            return undefined;
	        }
	        var top = this.data[0];
	        var bottom = this.data.pop();
	        this.length--;
	        if (this.length > 0) {
	            this.data[0] = bottom;
	            this._down(0);
	        }
	        return top;
	    };
	    TinyQueue.prototype.peek = function peek() {
	        return this.data[0];
	    };
	    TinyQueue.prototype._up = function _up(pos) {
	        var ref = this;
	        var data = ref.data;
	        var compare = ref.compare;
	        var item = data[pos];
	        while (pos > 0) {
	            var parent = pos - 1 >> 1;
	            var current = data[parent];
	            if (compare(item, current) >= 0) {
	                break;
	            }
	            data[pos] = current;
	            pos = parent;
	        }
	        data[pos] = item;
	    };
	    TinyQueue.prototype._down = function _down(pos) {
	        var ref = this;
	        var data = ref.data;
	        var compare = ref.compare;
	        var halfLength = this.length >> 1;
	        var item = data[pos];
	        while (pos < halfLength) {
	            var left = (pos << 1) + 1;
	            var best = data[left];
	            var right = left + 1;
	            if (right < this.length && compare(data[right], best) < 0) {
	                left = right;
	                best = data[right];
	            }
	            if (compare(best, item) >= 0) {
	                break;
	            }
	            data[pos] = best;
	            pos = left;
	        }
	        data[pos] = item;
	    };
	    function defaultCompare(a, b) {
	        return a < b ? -1 : a > b ? 1 : 0;
	    }
	    return TinyQueue;
	})); 
} (tinyqueue));

var tinyqueueExports = tinyqueue.exports;
var Queue = /*@__PURE__*/getDefaultExportFromCjs(tinyqueueExports);

//      
/**
 * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of
 * all source features normalized to this extent upon load.
 *
 * The value is a consequence of the following:
 *
 * * Vertex buffer store positions as signed 16 bit integers.
 * * One bit is lost for signedness to support tile buffers.
 * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int.
 * * One bit is lost to support features extending past the extent on the right edge of the tile.
 * * This leaves us with 2^13 = 8192
 *
 * @private
 * @readonly
 */
var EXTENT = 8192;

//      
// Inclusive index range for multipoint or linestring container
function compareMax$1(a, b) {
    return b.dist - a.dist;
}
const MIN_POINT_SIZE = 100;
const MIN_LINE_POINT_SIZE = 50;
function isDefaultBBOX(bbox) {
    const defualtBBox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    if (defualtBBox.length !== bbox.length) {
        return false;
    }
    for (let i = 0; i < defualtBBox.length; i++) {
        if (defualtBBox[i] !== bbox[i]) {
            return false;
        }
    }
    return true;
}
function getRangeSize(range) {
    return range[1] - range[0] + 1;
}
function isRangeSafe(range, threshold) {
    const ret = range[1] >= range[0] && range[1] < threshold;
    if (!ret) {
        console.warn('Distance Expression: Index is out of range');
    }
    return ret;
}
// Split the point set(points or linestring) into two halves, using IndexRange to do in-place splitting.
// If geometry is a line, the last point(here is the second index) of range1 needs to be included as the first point(here is the first index) of range2.
// If geometry are points, just split the points equally(if possible) into two new point sets(here are two index ranges).
function splitRange(range, isLine) {
    if (range[0] > range[1])
        return [
            null,
            null
        ];
    const size = getRangeSize(range);
    if (isLine) {
        if (size === 2) {
            return [
                range,
                null
            ];
        }
        const size1 = Math.floor(size / 2);
        const range1 = [
            range[0],
            range[0] + size1
        ];
        const range2 = [
            range[0] + size1,
            range[1]
        ];
        return [
            range1,
            range2
        ];
    } else {
        if (size === 1) {
            return [
                range,
                null
            ];
        }
        const size1 = Math.floor(size / 2) - 1;
        const range1 = [
            range[0],
            range[0] + size1
        ];
        const range2 = [
            range[0] + size1 + 1,
            range[1]
        ];
        return [
            range1,
            range2
        ];
    }
}
function getBBox(pointSets, range) {
    const bbox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    if (!isRangeSafe(range, pointSets.length))
        return bbox;
    for (let i = range[0]; i <= range[1]; ++i) {
        updateBBox(bbox, pointSets[i]);
    }
    return bbox;
}
function getPolygonBBox(polygon) {
    const bbox = [
        Infinity,
        Infinity,
        -Infinity,
        -Infinity
    ];
    for (let i = 0; i < polygon.length; ++i) {
        for (let j = 0; j < polygon[i].length; ++j) {
            updateBBox(bbox, polygon[i][j]);
        }
    }
    return bbox;
}
// Calculate the distance between two bounding boxes.
// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} and {dx, dy} to calculate the distance.
// Distance will be 0.0 if bounding box are overlapping.
function bboxToBBoxDistance(bbox1, bbox2, ruler) {
    if (isDefaultBBOX(bbox1) || isDefaultBBOX(bbox2)) {
        return NaN;
    }
    let dx = 0;
    let dy = 0;
    // bbox1 in left side
    if (bbox1[2] < bbox2[0]) {
        dx = bbox2[0] - bbox1[2];
    }
    // bbox1 in right side
    if (bbox1[0] > bbox2[2]) {
        dx = bbox1[0] - bbox2[2];
    }
    // bbox1 in above side
    if (bbox1[1] > bbox2[3]) {
        dy = bbox1[1] - bbox2[3];
    }
    // bbox1 in down side
    if (bbox1[3] < bbox2[1]) {
        dy = bbox2[1] - bbox1[3];
    }
    return ruler.distance([
        0,
        0
    ], [
        dx,
        dy
    ]);
}
function lngFromMercatorX$1(x) {
    return x * 360 - 180;
}
function latFromMercatorY$1(y) {
    const y2 = 180 - y * 360;
    return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;
}
function getLngLatPoint(coord, canonical) {
    const tilesAtZoom = Math.pow(2, canonical.z);
    const x = (coord.x / EXTENT + canonical.x) / tilesAtZoom;
    const y = (coord.y / EXTENT + canonical.y) / tilesAtZoom;
    return [
        lngFromMercatorX$1(x),
        latFromMercatorY$1(y)
    ];
}
function getLngLatPoints(coordinates, canonical) {
    const coords = [];
    for (let i = 0; i < coordinates.length; ++i) {
        coords.push(getLngLatPoint(coordinates[i], canonical));
    }
    return coords;
}
function pointToLineDistance(point, line, ruler) {
    const nearestPoint = ruler.pointOnLine(line, point).point;
    return ruler.distance(point, nearestPoint);
}
function pointsToLineDistance(points, rangeA, line, rangeB, ruler) {
    const subLine = line.slice(rangeB[0], rangeB[1] + 1);
    let dist = Infinity;
    for (let i = rangeA[0]; i <= rangeA[1]; ++i) {
        if ((dist = Math.min(dist, pointToLineDistance(points[i], subLine, ruler))) === 0)
            return 0;
    }
    return dist;
}
// precondition is two segments are not intersecting with each other
function segmentToSegmentDistance(p1, p2, q1, q2, ruler) {
    const dist1 = Math.min(ruler.pointToSegmentDistance(p1, q1, q2), ruler.pointToSegmentDistance(p2, q1, q2));
    const dist2 = Math.min(ruler.pointToSegmentDistance(q1, p1, p2), ruler.pointToSegmentDistance(q2, p1, p2));
    return Math.min(dist1, dist2);
}
function lineToLineDistance(line1, range1, line2, range2, ruler) {
    if (!isRangeSafe(range1, line1.length) || !isRangeSafe(range2, line2.length)) {
        return NaN;
    }
    let dist = Infinity;
    for (let i = range1[0]; i < range1[1]; ++i) {
        for (let j = range2[0]; j < range2[1]; ++j) {
            if (segmentIntersectSegment(line1[i], line1[i + 1], line2[j], line2[j + 1]))
                return 0;
            dist = Math.min(dist, segmentToSegmentDistance(line1[i], line1[i + 1], line2[j], line2[j + 1], ruler));
        }
    }
    return dist;
}
function pointsToPointsDistance(pointSet1, range1, pointSet2, range2, ruler) {
    if (!isRangeSafe(range1, pointSet1.length) || !isRangeSafe(range2, pointSet2.length)) {
        return NaN;
    }
    let dist = Infinity;
    for (let i = range1[0]; i <= range1[1]; ++i) {
        for (let j = range2[0]; j <= range2[1]; ++j) {
            if ((dist = Math.min(dist, ruler.distance(pointSet1[i], pointSet2[j]))) === 0)
                return dist;
        }
    }
    return dist;
}
function pointToPolygonDistance(point, polygon, ruler) {
    if (pointWithinPolygon(point, polygon, true    /*trueOnBoundary*/))
        return 0;
    let dist = Infinity;
    for (const ring of polygon) {
        const ringLen = ring.length;
        if (ringLen < 2) {
            console.warn('Distance Expression: Invalid polygon!');
            return NaN;
        }
        if (ring[0] !== ring[ringLen - 1]) {
            if ((dist = Math.min(dist, ruler.pointToSegmentDistance(point, ring[ringLen - 1], ring[0]))) === 0)
                return dist;
        }
        if ((dist = Math.min(dist, pointToLineDistance(point, ring, ruler))) === 0)
            return dist;
    }
    return dist;
}
function lineToPolygonDistance(line, range, polygon, ruler) {
    if (!isRangeSafe(range, line.length)) {
        return NaN;
    }
    for (let i = range[0]; i <= range[1]; ++i) {
        if (pointWithinPolygon(line[i], polygon, true    /*trueOnBoundary*/))
            return 0;
    }
    let dist = Infinity;
    for (let i = range[0]; i < range[1]; ++i) {
        for (const ring of polygon) {
            for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) {
                if (segmentIntersectSegment(line[i], line[i + 1], ring[k], ring[j]))
                    return 0;
                dist = Math.min(dist, segmentToSegmentDistance(line[i], line[i + 1], ring[k], ring[j], ruler));
            }
        }
    }
    return dist;
}
function polygonIntersect(polygon1, polygon2) {
    for (const ring of polygon1) {
        for (let i = 0; i <= ring.length - 1; ++i) {
            if (pointWithinPolygon(ring[i], polygon2, true    /*trueOnBoundary*/))
                return true;
        }
    }
    return false;
}
function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) {
    const bbox1 = getPolygonBBox(polygon1);
    const bbox2 = getPolygonBBox(polygon2);
    if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) {
        return currentMiniDist;
    }
    if (boxWithinBox(bbox1, bbox2)) {
        if (polygonIntersect(polygon1, polygon2))
            return 0;
    } else if (polygonIntersect(polygon2, polygon1)) {
        return 0;
    }
    let dist = currentMiniDist;
    for (const ring1 of polygon1) {
        for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) {
            for (const ring2 of polygon2) {
                for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) {
                    if (segmentIntersectSegment(ring1[l], ring1[i], ring2[k], ring2[j]))
                        return 0;
                    dist = Math.min(dist, segmentToSegmentDistance(ring1[l], ring1[i], ring2[k], ring2[j], ruler));
                }
            }
        }
    }
    return dist;
}
function updateQueue(distQueue, miniDist, ruler, pointSet1, pointSet2, r1, r2) {
    if (r1 === null || r2 === null)
        return;
    const tempDist = bboxToBBoxDistance(getBBox(pointSet1, r1), getBBox(pointSet2, r2), ruler);
    // Insert new pair to the queue if the bbox distance is less than miniDist, the pair with biggest distance will be at the top
    if (tempDist < miniDist)
        distQueue.push({
            dist: tempDist,
            range1: r1,
            range2: r2
        });
}
// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force O(n*n)
// Most of the time, use index for in-place processing.
function pointSetToPolygonDistance(pointSets, isLine, polygon, ruler, currentMiniDist = Infinity) {
    let miniDist = Math.min(ruler.distance(pointSets[0], polygon[0][0]), currentMiniDist);
    if (miniDist === 0)
        return miniDist;
    const initialDistPair = {
        dist: 0,
        range1: [
            0,
            pointSets.length - 1
        ],
        range2: [
            0,
            0
        ]
    };
    const distQueue = new Queue([initialDistPair], compareMax$1);
    const setThreshold = isLine ? MIN_LINE_POINT_SIZE : MIN_POINT_SIZE;
    const polyBBox = getPolygonBBox(polygon);
    while (distQueue.length) {
        const distPair = distQueue.pop();
        if (distPair.dist >= miniDist)
            continue;
        const range = distPair.range1;
        // In case the set size are relatively small, we could use brute-force directly
        if (getRangeSize(range) <= setThreshold) {
            if (!isRangeSafe(range, pointSets.length))
                return NaN;
            if (isLine) {
                const tempDist = lineToPolygonDistance(pointSets, range, polygon, ruler);
                if ((miniDist = Math.min(miniDist, tempDist)) === 0)
                    return miniDist;
            } else {
                for (let i = range[0]; i <= range[1]; ++i) {
                    const tempDist = pointToPolygonDistance(pointSets[i], polygon, ruler);
                    if ((miniDist = Math.min(miniDist, tempDist)) === 0)
                        return miniDist;
                }
            }
        } else {
            const newRanges = splitRange(range, isLine);
            if (newRanges[0] !== null) {
                const tempDist = bboxToBBoxDistance(getBBox(pointSets, newRanges[0]), polyBBox, ruler);
                if (tempDist < miniDist)
                    distQueue.push({
                        dist: tempDist,
                        range1: newRanges[0],
                        range2: [
                            0,
                            0
                        ]
                    });
            }
            if (newRanges[1] !== null) {
                const tempDist = bboxToBBoxDistance(getBBox(pointSets, newRanges[1]), polyBBox, ruler);
                if (tempDist < miniDist)
                    distQueue.push({
                        dist: tempDist,
                        range1: newRanges[1],
                        range2: [
                            0,
                            0
                        ]
                    });
            }
        }
    }
    return miniDist;
}
function pointSetsDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) {
    let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0]));
    if (miniDist === 0)
        return miniDist;
    const initialDistPair = {
        dist: 0,
        range1: [
            0,
            pointSet1.length - 1
        ],
        range2: [
            0,
            pointSet2.length - 1
        ]
    };
    const distQueue = new Queue([initialDistPair], compareMax$1);
    const set1Threshold = isLine1 ? MIN_LINE_POINT_SIZE : MIN_POINT_SIZE;
    const set2Threshold = isLine2 ? MIN_LINE_POINT_SIZE : MIN_POINT_SIZE;
    while (distQueue.length) {
        const distPair = distQueue.pop();
        if (distPair.dist >= miniDist)
            continue;
        const rangeA = distPair.range1;
        const rangeB = distPair.range2;
        // In case the set size are relatively small, we could use brute-force directly
        if (getRangeSize(rangeA) <= set1Threshold && getRangeSize(rangeB) <= set2Threshold) {
            if (!isRangeSafe(rangeA, pointSet1.length) || !isRangeSafe(rangeB, pointSet2.length)) {
                return NaN;
            }
            if (isLine1 && isLine2) {
                miniDist = Math.min(miniDist, lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler));
            } else if (!isLine1 && !isLine2) {
                miniDist = Math.min(miniDist, pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler));
            } else if (isLine1 && !isLine2) {
                miniDist = Math.min(miniDist, pointsToLineDistance(pointSet2, rangeB, pointSet1, rangeA, ruler));
            } else if (!isLine1 && isLine2) {
                miniDist = Math.min(miniDist, pointsToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler));
            }
            if (miniDist === 0)
                return miniDist;
        } else {
            const newRangesA = splitRange(rangeA, isLine1);
            const newRangesB = splitRange(rangeB, isLine2);
            updateQueue(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]);
            updateQueue(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]);
            updateQueue(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]);
            updateQueue(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]);
        }
    }
    return miniDist;
}
function pointSetToLinesDistance(pointSet, isLine, lines, ruler, currentMiniDist = Infinity) {
    let dist = currentMiniDist;
    const bbox1 = getBBox(pointSet, [
        0,
        pointSet.length - 1
    ]);
    for (const line of lines) {
        if (dist !== Infinity && bboxToBBoxDistance(bbox1, getBBox(line, [
                0,
                line.length - 1
            ]), ruler) >= dist)
            continue;
        dist = Math.min(dist, pointSetsDistance(pointSet, isLine, line, true    /*isLine*/, ruler, dist));
        if (dist === 0)
            return dist;
    }
    return dist;
}
function pointSetToPolygonsDistance(points, isLine, polygons, ruler, currentMiniDist = Infinity) {
    let dist = currentMiniDist;
    const bbox1 = getBBox(points, [
        0,
        points.length - 1
    ]);
    for (const polygon of polygons) {
        if (dist !== Infinity && bboxToBBoxDistance(bbox1, getPolygonBBox(polygon), ruler) >= dist)
            continue;
        const tempDist = pointSetToPolygonDistance(points, isLine, polygon, ruler, dist);
        if (isNaN(tempDist))
            return tempDist;
        if ((dist = Math.min(dist, tempDist)) === 0)
            return dist;
    }
    return dist;
}
function polygonsToPolygonsDistance(polygons1, polygons2, ruler) {
    let dist = Infinity;
    for (const polygon1 of polygons1) {
        for (const polygon2 of polygons2) {
            const tempDist = polygonToPolygonDistance(polygon1, polygon2, ruler, dist);
            if (isNaN(tempDist))
                return tempDist;
            if ((dist = Math.min(dist, tempDist)) === 0)
                return dist;
        }
    }
    return dist;
}
function pointsToGeometryDistance(originGeometry, canonical, geometry) {
    const lngLatPoints = [];
    for (const points of originGeometry) {
        for (const point of points) {
            lngLatPoints.push(getLngLatPoint(point, canonical));
        }
    }
    const ruler = new CheapRuler(lngLatPoints[0][1], 'meters');
    if (geometry.type === 'Point' || geometry.type === 'MultiPoint' || geometry.type === 'LineString') {
        return pointSetsDistance(lngLatPoints, false    /*isLine*/, geometry.type === 'Point' ? [geometry.coordinates] : geometry.coordinates, geometry.type === 'LineString'    /*isLine*/, ruler);
    }
    if (geometry.type === 'MultiLineString') {
        return pointSetToLinesDistance(lngLatPoints, false    /*isLine*/, geometry.coordinates, ruler);
    }
    if (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon') {
        return pointSetToPolygonsDistance(lngLatPoints, false    /*isLine*/, geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.coordinates, ruler);
    }
    return null;
}
function linesToGeometryDistance(originGeometry, canonical, geometry) {
    const lngLatLines = [];
    for (const line of originGeometry) {
        const lngLatLine = [];
        for (const point of line) {
            lngLatLine.push(getLngLatPoint(point, canonical));
        }
        lngLatLines.push(lngLatLine);
    }
    const ruler = new CheapRuler(lngLatLines[0][0][1], 'meters');
    if (geometry.type === 'Point' || geometry.type === 'MultiPoint' || geometry.type === 'LineString') {
        return pointSetToLinesDistance(geometry.type === 'Point' ? [geometry.coordinates] : geometry.coordinates, geometry.type === 'LineString'    /*isLine*/, lngLatLines, ruler);
    }
    if (geometry.type === 'MultiLineString') {
        let dist = Infinity;
        for (let i = 0; i < geometry.coordinates.length; i++) {
            const tempDist = pointSetToLinesDistance(geometry.coordinates[i], true    /*isLine*/, lngLatLines, ruler, dist);
            if (isNaN(tempDist))
                return tempDist;
            if ((dist = Math.min(dist, tempDist)) === 0)
                return dist;
        }
        return dist;
    }
    if (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon') {
        let dist = Infinity;
        for (let i = 0; i < lngLatLines.length; i++) {
            const tempDist = pointSetToPolygonsDistance(lngLatLines[i], true    /*isLine*/, geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.coordinates, ruler, dist);
            if (isNaN(tempDist))
                return tempDist;
            if ((dist = Math.min(dist, tempDist)) === 0)
                return dist;
        }
        return dist;
    }
    return null;
}
function polygonsToGeometryDistance(originGeometry, canonical, geometry) {
    const lngLatPolygons = [];
    for (const polygon of classifyRings$2(originGeometry, 0)) {
        const lngLatPolygon = [];
        for (let i = 0; i < polygon.length; ++i) {
            lngLatPolygon.push(getLngLatPoints(polygon[i], canonical));
        }
        lngLatPolygons.push(lngLatPolygon);
    }
    const ruler = new CheapRuler(lngLatPolygons[0][0][0][1], 'meters');
    if (geometry.type === 'Point' || geometry.type === 'MultiPoint' || geometry.type === 'LineString') {
        return pointSetToPolygonsDistance(geometry.type === 'Point' ? [geometry.coordinates] : geometry.coordinates, geometry.type === 'LineString'    /*isLine*/, lngLatPolygons, ruler);
    }
    if (geometry.type === 'MultiLineString') {
        let dist = Infinity;
        for (let i = 0; i < geometry.coordinates.length; i++) {
            const tempDist = pointSetToPolygonsDistance(geometry.coordinates[i], true    /*isLine*/, lngLatPolygons, ruler, dist);
            if (isNaN(tempDist))
                return tempDist;
            if ((dist = Math.min(dist, tempDist)) === 0)
                return dist;
        }
        return dist;
    }
    if (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon') {
        return polygonsToPolygonsDistance(geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.coordinates, lngLatPolygons, ruler);
    }
    return null;
}
function isTypeValid(type) {
    return type === 'Point' || type === 'MultiPoint' || type === 'LineString' || type === 'MultiLineString' || type === 'Polygon' || type === 'MultiPolygon';
}
class Distance {
    constructor(geojson, geometries) {
        this.type = NumberType;
        this.geojson = geojson;
        this.geometries = geometries;
    }
    static parse(args, context) {
        if (args.length !== 2) {
            return context.error(`'distance' expression requires either one argument, but found ' ${ args.length - 1 } instead.`);
        }
        if (isValue(args[1])) {
            const geojson = args[1];
            if (geojson.type === 'FeatureCollection') {
                for (let i = 0; i < geojson.features.length; ++i) {
                    if (isTypeValid(geojson.features[i].geometry.type)) {
                        return new Distance(geojson, geojson.features[i].geometry);
                    }
                }
            } else if (geojson.type === 'Feature') {
                if (isTypeValid(geojson.geometry.type)) {
                    return new Distance(geojson, geojson.geometry);
                }
            } else if (isTypeValid(geojson.type)) {
                return new Distance(geojson, geojson);
            }
        }
        return context.error('\'distance\' expression needs to be an array with format [\'Distance\', GeoJSONObj].');
    }
    evaluate(ctx) {
        const geometry = ctx.geometry();
        const canonical = ctx.canonicalID();
        if (geometry != null && canonical != null) {
            if (ctx.geometryType() === 'Point') {
                return pointsToGeometryDistance(geometry, canonical, this.geometries);
            }
            if (ctx.geometryType() === 'LineString') {
                return linesToGeometryDistance(geometry, canonical, this.geometries);
            }
            if (ctx.geometryType() === 'Polygon') {
                return polygonsToGeometryDistance(geometry, canonical, this.geometries);
            }
            console.warn('Distance Expression: currently only evaluates valid Point/LineString/Polygon geometries.');
        } else {
            console.warn('Distance Expression: requirs valid feature and canonical information.');
        }
        return null;
    }
    eachChild() {
    }
    outputDefined() {
        return true;
    }
    serialize() {
        return [
            'distance',
            this.geojson
        ];
    }
}
var Distance$1 = Distance;

//      
function isFeatureConstant(e) {
    if (e instanceof CompoundExpression$1) {
        if (e.name === 'get' && e.args.length === 1) {
            return false;
        } else if (e.name === 'feature-state') {
            return false;
        } else if (e.name === 'has' && e.args.length === 1) {
            return false;
        } else if (e.name === 'properties' || e.name === 'geometry-type' || e.name === 'id') {
            return false;
        } else if (/^filter-/.test(e.name)) {
            return false;
        }
    }
    if (e instanceof Within$1) {
        return false;
    }
    if (e instanceof Distance$1) {
        return false;
    }
    let result = true;
    e.eachChild(arg => {
        if (result && !isFeatureConstant(arg)) {
            result = false;
        }
    });
    return result;
}
function isStateConstant(e) {
    if (e instanceof CompoundExpression$1) {
        if (e.name === 'feature-state') {
            return false;
        }
    }
    let result = true;
    e.eachChild(arg => {
        if (result && !isStateConstant(arg)) {
            result = false;
        }
    });
    return result;
}
function isConfigConstant(e) {
    if (e instanceof CompoundExpression$1) {
        if (e.name === 'config') {
            return false;
        }
    }
    let result = true;
    e.eachChild(arg => {
        if (result && !isConfigConstant(arg)) {
            result = false;
        }
    });
    return result;
}
function isGlobalPropertyConstant(e, properties) {
    if (e instanceof CompoundExpression$1 && properties.indexOf(e.name) >= 0) {
        return false;
    }
    let result = true;
    e.eachChild(arg => {
        if (result && !isGlobalPropertyConstant(arg, properties)) {
            result = false;
        }
    });
    return result;
}

//      
class Var {
    constructor(name, boundExpression) {
        this.type = boundExpression.type;
        this.name = name;
        this.boundExpression = boundExpression;
    }
    static parse(args, context) {
        if (args.length !== 2 || typeof args[1] !== 'string')
            return context.error(`'var' expression requires exactly one string literal argument.`);
        const name = args[1];
        if (!context.scope.has(name)) {
            return context.error(`Unknown variable "${ name }". Make sure "${ name }" has been bound in an enclosing "let" expression before using it.`, 1);
        }
        return new Var(name, context.scope.get(name));
    }
    evaluate(ctx) {
        return this.boundExpression.evaluate(ctx);
    }
    eachChild() {
    }
    outputDefined() {
        return false;
    }
    serialize() {
        return [
            'var',
            this.name
        ];
    }
}
var Var$1 = Var;

//      
/**
 * State associated parsing at a given point in an expression tree.
 * @private
 */
class ParsingContext {
    // The expected type of this expression. Provided only to allow Expression
    // implementations to infer argument types: Expression#parse() need not
    // check that the output type of the parsed expression matches
    // `expectedType`.
    constructor(registry, path = [], expectedType, scope = new Scope$1(), errors = [], options) {
        this.registry = registry;
        this.path = path;
        this.key = path.map(part => `[${ part }]`).join('');
        this.scope = scope;
        this.errors = errors;
        this.expectedType = expectedType;
        this.options = options;
    }
    /**
     * @param expr the JSON expression to parse
     * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed
     * @param options
     * @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.
     * @private
     */
    parse(expr, index, expectedType, bindings, options = {}) {
        if (index || expectedType) {
            return this.concat(index, expectedType, bindings)._parse(expr, options);
        }
        return this._parse(expr, options);
    }
    _parse(expr, options) {
        if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {
            expr = [
                'literal',
                expr
            ];
        }
        function annotate(parsed, type, typeAnnotation) {
            if (typeAnnotation === 'assert') {
                return new Assertion$1(type, [parsed]);
            } else if (typeAnnotation === 'coerce') {
                return new Coercion$1(type, [parsed]);
            } else {
                return parsed;
            }
        }
        if (Array.isArray(expr)) {
            if (expr.length === 0) {
                return this.error(`Expected an array with at least one element. If you wanted a literal array, use ["literal", []].`);
            }
            const Expr = typeof expr[0] === 'string' ? this.registry[expr[0]] : undefined;
            if (Expr) {
                let parsed = Expr.parse(expr, this);
                if (!parsed)
                    return null;
                if (this.expectedType) {
                    const expected = this.expectedType;
                    const actual = parsed.type;
                    // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.
                    // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.
                    // Otherwise, we do static type-checking.
                    //
                    // These behaviors are overridable for:
                    //   * The "coalesce" operator, which needs to omit type annotations.
                    //   * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.
                    //
                    if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') {
                        parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');
                    } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) {
                        parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');
                    } else if (this.checkSubtype(expected, actual)) {
                        return null;
                    }
                }
                // If an expression's arguments are all literals, we can evaluate
                // it immediately and replace it with a literal value in the
                // parsed/compiled result. Expressions that expect an image should
                // not be resolved here so we can later get the available images.
                if (!(parsed instanceof Literal$1) && parsed.type.kind !== 'resolvedImage' && isConstant(parsed)) {
                    const ec = new EvaluationContext$1(this.options);
                    try {
                        parsed = new Literal$1(parsed.type, parsed.evaluate(ec));
                    } catch (e) {
                        this.error(e.message);
                        return null;
                    }
                }
                return parsed;
            }
            // Try to parse as array
            return Coercion$1.parse([
                'to-array',
                expr
            ], this);
        } else if (typeof expr === 'undefined') {
            return this.error(`'undefined' value invalid. Use null instead.`);
        } else if (typeof expr === 'object') {
            return this.error(`Bare objects invalid. Use ["literal", {...}] instead.`);
        } else {
            return this.error(`Expected an array, but found ${ typeof expr } instead.`);
        }
    }
    /**
     * Returns a copy of this context suitable for parsing the subexpression at
     * index `index`, optionally appending to 'let' binding map.
     *
     * Note that `errors` property, intended for collecting errors while
     * parsing, is copied by reference rather than cloned.
     * @private
     */
    concat(index, expectedType, bindings) {
        const path = typeof index === 'number' ? this.path.concat(index) : this.path;
        const scope = bindings ? this.scope.concat(bindings) : this.scope;
        return new ParsingContext(this.registry, path, expectedType || null, scope, this.errors, this.options);
    }
    /**
     * Push a parsing (or type checking) error into the `this.errors`
     * @param error The message
     * @param keys Optionally specify the source of the error at a child
     * of the current expression at `this.key`.
     * @private
     */
    error(error, ...keys) {
        const key = `${ this.key }${ keys.map(k => `[${ k }]`).join('') }`;
        this.errors.push(new ParsingError$1(key, error));
    }
    /**
     * Returns null if `t` is a subtype of `expected`; otherwise returns an
     * error message and also pushes it to `this.errors`.
     */
    checkSubtype(expected, t) {
        const error = checkSubtype(expected, t);
        if (error)
            this.error(error);
        return error;
    }
}
var ParsingContext$1 = ParsingContext;
function isConstant(expression) {
    if (expression instanceof Var$1) {
        return isConstant(expression.boundExpression);
    } else if (expression instanceof CompoundExpression$1 && expression.name === 'error') {
        return false;
    } else if (expression instanceof CompoundExpression$1 && expression.name === 'config') {
        return false;
    } else if (expression instanceof CollatorExpression) {
        // Although the results of a Collator expression with fixed arguments
        // generally shouldn't change between executions, we can't serialize them
        // as constant expressions because results change based on environment.
        return false;
    } else if (expression instanceof Within$1) {
        return false;
    } else if (expression instanceof Distance$1) {
        return false;
    }
    const isTypeAnnotation = expression instanceof Coercion$1 || expression instanceof Assertion$1;
    let childrenConstant = true;
    expression.eachChild(child => {
        // We can _almost_ assume that if `expressions` children are constant,
        // they would already have been evaluated to Literal values when they
        // were parsed.  Type annotations are the exception, because they might
        // have been inferred and added after a child was parsed.
        // So we recurse into isConstant() for the children of type annotations,
        // but otherwise simply check whether they are Literals.
        if (isTypeAnnotation) {
            childrenConstant = childrenConstant && isConstant(child);
        } else {
            childrenConstant = childrenConstant && child instanceof Literal$1;
        }
    });
    if (!childrenConstant) {
        return false;
    }
    return isFeatureConstant(expression) && isGlobalPropertyConstant(expression, [
        'zoom',
        'heatmap-density',
        'line-progress',
        'raster-value',
        'sky-radial-progress',
        'accumulated',
        'is-supported-script',
        'pitch',
        'distance-from-center',
        'measure-light'
    ]);
}

//      
/**
 * Returns the index of the last stop <= input, or 0 if it doesn't exist.
 * @private
 */
function findStopLessThanOrEqualTo(stops, input) {
    const lastIndex = stops.length - 1;
    let lowerIndex = 0;
    let upperIndex = lastIndex;
    let currentIndex = 0;
    let currentValue, nextValue;
    while (lowerIndex <= upperIndex) {
        currentIndex = Math.floor((lowerIndex + upperIndex) / 2);
        currentValue = stops[currentIndex];
        nextValue = stops[currentIndex + 1];
        if (currentValue <= input) {
            if (currentIndex === lastIndex || input < nextValue) {
                // Search complete
                return currentIndex;
            }
            lowerIndex = currentIndex + 1;
        } else if (currentValue > input) {
            upperIndex = currentIndex - 1;
        } else {
            throw new RuntimeError$1('Input is not a number.');
        }
    }
    return 0;
}

//      
class Step {
    constructor(type, input, stops) {
        this.type = type;
        this.input = input;
        this.labels = [];
        this.outputs = [];
        for (const [label, expression] of stops) {
            this.labels.push(label);
            this.outputs.push(expression);
        }
    }
    static parse(args, context) {
        if (args.length - 1 < 4) {
            return context.error(`Expected at least 4 arguments, but found only ${ args.length - 1 }.`);
        }
        if ((args.length - 1) % 2 !== 0) {
            return context.error(`Expected an even number of arguments.`);
        }
        const input = context.parse(args[1], 1, NumberType);
        if (!input)
            return null;
        const stops = [];
        let outputType = null;
        if (context.expectedType && context.expectedType.kind !== 'value') {
            outputType = context.expectedType;
        }
        for (let i = 1; i < args.length; i += 2) {
            const label = i === 1 ? -Infinity : args[i];
            const value = args[i + 1];
            const labelKey = i;
            const valueKey = i + 1;
            if (typeof label !== 'number') {
                return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);
            }
            if (stops.length && stops[stops.length - 1][0] >= label) {
                return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey);
            }
            const parsed = context.parse(value, valueKey, outputType);
            if (!parsed)
                return null;
            outputType = outputType || parsed.type;
            stops.push([
                label,
                parsed
            ]);
        }
        return new Step(outputType, input, stops);
    }
    evaluate(ctx) {
        const labels = this.labels;
        const outputs = this.outputs;
        if (labels.length === 1) {
            return outputs[0].evaluate(ctx);
        }
        const value = this.input.evaluate(ctx);
        if (value <= labels[0]) {
            return outputs[0].evaluate(ctx);
        }
        const stopCount = labels.length;
        if (value >= labels[stopCount - 1]) {
            return outputs[stopCount - 1].evaluate(ctx);
        }
        const index = findStopLessThanOrEqualTo(labels, value);
        return outputs[index].evaluate(ctx);
    }
    eachChild(fn) {
        fn(this.input);
        for (const expression of this.outputs) {
            fn(expression);
        }
    }
    outputDefined() {
        return this.outputs.every(out => out.outputDefined());
    }
    serialize() {
        const serialized = [
            'step',
            this.input.serialize()
        ];
        for (let i = 0; i < this.labels.length; i++) {
            if (i > 0) {
                serialized.push(this.labels[i]);
            }
            serialized.push(this.outputs[i].serialize());
        }
        return serialized;
    }
}
var Step$1 = Step;

//      
function number(a, b, t) {
    return a * (1 - t) + b * t;
}
function color(from, to, t) {
    return new Color$1(number(from.r, to.r, t), number(from.g, to.g, t), number(from.b, to.b, t), number(from.a, to.a, t));
}
function array(from, to, t) {
    return from.map((d, i) => {
        return number(d, to[i], t);
    });
}

var interpolate = /*#__PURE__*/Object.freeze({
__proto__: null,
array: array,
color: color,
number: number
});

//      
// Constants
const Xn = 0.95047,
    // D65 standard referent
    Yn = 1, Zn = 1.08883, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI;
// Utilities
function xyz2lab(t) {
    return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
    return t > t1 ? t * t * t : t2 * (t - t0);
}
function xyz2rgb(x) {
    return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
function rgb2xyz(x) {
    x /= 255;
    return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
// LAB
function rgbToLab(rgbColor) {
    const b = rgb2xyz(rgbColor.r), a = rgb2xyz(rgbColor.g), l = rgb2xyz(rgbColor.b), x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.072175 * l) / Yn), z = xyz2lab((0.0193339 * b + 0.119192 * a + 0.9503041 * l) / Zn);
    return {
        l: 116 * y - 16,
        a: 500 * (x - y),
        b: 200 * (y - z),
        alpha: rgbColor.a
    };
}
function labToRgb(labColor) {
    let y = (labColor.l + 16) / 116, x = isNaN(labColor.a) ? y : y + labColor.a / 500, z = isNaN(labColor.b) ? y : y - labColor.b / 200;
    y = Yn * lab2xyz(y);
    x = Xn * lab2xyz(x);
    z = Zn * lab2xyz(z);
    return new Color$1(xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB
    xyz2rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z), labColor.alpha);
}
function interpolateLab(from, to, t) {
    return {
        l: number(from.l, to.l, t),
        a: number(from.a, to.a, t),
        b: number(from.b, to.b, t),
        alpha: number(from.alpha, to.alpha, t)
    };
}
// HCL
function rgbToHcl(rgbColor) {
    const {l, a, b} = rgbToLab(rgbColor);
    const h = Math.atan2(b, a) * rad2deg;
    return {
        h: h < 0 ? h + 360 : h,
        c: Math.sqrt(a * a + b * b),
        l,
        alpha: rgbColor.a
    };
}
function hclToRgb(hclColor) {
    const h = hclColor.h * deg2rad, c = hclColor.c, l = hclColor.l;
    return labToRgb({
        l,
        a: Math.cos(h) * c,
        b: Math.sin(h) * c,
        alpha: hclColor.alpha
    });
}
function interpolateHue(a, b, t) {
    const d = b - a;
    return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d);
}
function interpolateHcl(from, to, t) {
    return {
        h: interpolateHue(from.h, to.h, t),
        c: number(from.c, to.c, t),
        l: number(from.l, to.l, t),
        alpha: number(from.alpha, to.alpha, t)
    };
}
const lab = {
    forward: rgbToLab,
    reverse: labToRgb,
    interpolate: interpolateLab
};
const hcl = {
    forward: rgbToHcl,
    reverse: hclToRgb,
    interpolate: interpolateHcl
};

var colorSpaces = /*#__PURE__*/Object.freeze({
__proto__: null,
hcl: hcl,
lab: lab
});

//      
class Interpolate {
    constructor(type, operator, interpolation, input, stops) {
        this.type = type;
        this.operator = operator;
        this.interpolation = interpolation;
        this.input = input;
        this.labels = [];
        this.outputs = [];
        for (const [label, expression] of stops) {
            this.labels.push(label);
            this.outputs.push(expression);
        }
    }
    static interpolationFactor(interpolation, input, lower, upper) {
        let t = 0;
        if (interpolation.name === 'exponential') {
            t = exponentialInterpolation(input, interpolation.base, lower, upper);
        } else if (interpolation.name === 'linear') {
            t = exponentialInterpolation(input, 1, lower, upper);
        } else if (interpolation.name === 'cubic-bezier') {
            const c = interpolation.controlPoints;
            const ub = new UnitBezier$1(c[0], c[1], c[2], c[3]);
            t = ub.solve(exponentialInterpolation(input, 1, lower, upper));
        }
        return t;
    }
    static parse(args, context) {
        let [operator, interpolation, input, ...rest] = args;
        if (!Array.isArray(interpolation) || interpolation.length === 0) {
            return context.error(`Expected an interpolation type expression.`, 1);
        }
        if (interpolation[0] === 'linear') {
            interpolation = { name: 'linear' };
        } else if (interpolation[0] === 'exponential') {
            const base = interpolation[1];
            if (typeof base !== 'number')
                return context.error(`Exponential interpolation requires a numeric base.`, 1, 1);
            interpolation = {
                name: 'exponential',
                base
            };
        } else if (interpolation[0] === 'cubic-bezier') {
            const controlPoints = interpolation.slice(1);
            if (controlPoints.length !== 4 || controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) {
                return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);
            }
            interpolation = {
                name: 'cubic-bezier',
                controlPoints: controlPoints
            };
        } else {
            return context.error(`Unknown interpolation type ${ String(interpolation[0]) }`, 1, 0);
        }
        if (args.length - 1 < 4) {
            return context.error(`Expected at least 4 arguments, but found only ${ args.length - 1 }.`);
        }
        if ((args.length - 1) % 2 !== 0) {
            return context.error(`Expected an even number of arguments.`);
        }
        input = context.parse(input, 2, NumberType);
        if (!input)
            return null;
        const stops = [];
        let outputType = null;
        if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') {
            outputType = ColorType;
        } else if (context.expectedType && context.expectedType.kind !== 'value') {
            outputType = context.expectedType;
        }
        for (let i = 0; i < rest.length; i += 2) {
            const label = rest[i];
            const value = rest[i + 1];
            const labelKey = i + 3;
            const valueKey = i + 4;
            if (typeof label !== 'number') {
                return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);
            }
            if (stops.length && stops[stops.length - 1][0] >= label) {
                return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey);
            }
            const parsed = context.parse(value, valueKey, outputType);
            if (!parsed)
                return null;
            outputType = outputType || parsed.type;
            stops.push([
                label,
                parsed
            ]);
        }
        if (outputType.kind !== 'number' && outputType.kind !== 'color' && !(outputType.kind === 'array' && outputType.itemType.kind === 'number' && typeof outputType.N === 'number')) {
            return context.error(`Type ${ toString$1(outputType) } is not interpolatable.`);
        }
        return new Interpolate(outputType, operator, interpolation, input, stops);
    }
    evaluate(ctx) {
        const labels = this.labels;
        const outputs = this.outputs;
        if (labels.length === 1) {
            return outputs[0].evaluate(ctx);
        }
        const value = this.input.evaluate(ctx);
        if (value <= labels[0]) {
            return outputs[0].evaluate(ctx);
        }
        const stopCount = labels.length;
        if (value >= labels[stopCount - 1]) {
            return outputs[stopCount - 1].evaluate(ctx);
        }
        const index = findStopLessThanOrEqualTo(labels, value);
        const lower = labels[index];
        const upper = labels[index + 1];
        const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);
        const outputLower = outputs[index].evaluate(ctx);
        const outputUpper = outputs[index + 1].evaluate(ctx);
        if (this.operator === 'interpolate') {
            return interpolate[this.type.kind.toLowerCase()](outputLower, outputUpper, t);    // eslint-disable-line import/namespace
        } else if (this.operator === 'interpolate-hcl') {
            return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t));
        } else {
            return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t));
        }
    }
    eachChild(fn) {
        fn(this.input);
        for (const expression of this.outputs) {
            fn(expression);
        }
    }
    outputDefined() {
        return this.outputs.every(out => out.outputDefined());
    }
    serialize() {
        let interpolation;
        if (this.interpolation.name === 'linear') {
            interpolation = ['linear'];
        } else if (this.interpolation.name === 'exponential') {
            if (this.interpolation.base === 1) {
                interpolation = ['linear'];
            } else {
                interpolation = [
                    'exponential',
                    this.interpolation.base
                ];
            }
        } else {
            interpolation = ['cubic-bezier'].concat(this.interpolation.controlPoints);
        }
        const serialized = [
            this.operator,
            interpolation,
            this.input.serialize()
        ];
        for (let i = 0; i < this.labels.length; i++) {
            serialized.push(this.labels[i], this.outputs[i].serialize());
        }
        return serialized;
    }
}
/**
 * Returns a ratio that can be used to interpolate between exponential function
 * stops.
 * 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,
 * and `a` and `b` are constants affording sufficient degrees of freedom to fit
 * the function to the given stops.
 *
 * Here's a bit of algebra that lets us compute `f(x)` directly from the stop
 * values without explicitly solving for `a` and `b`:
 *
 * First stop value: `f(x0) = y0 = a * base^x0 + b`
 * Second stop value: `f(x1) = y1 = a * base^x1 + b`
 * => `y1 - y0 = a(base^x1 - base^x0)`
 * => `a = (y1 - y0)/(base^x1 - base^x0)`
 *
 * Desired value: `f(x) = y = a * base^x + b`
 * => `f(x) = y0 + a * (base^x - base^x0)`
 *
 * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a
 * little algebra:
 * ```
 * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)
 *                     = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)
 * ```
 *
 * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have
 * `f(x) = y0 + (y1 - y0) * ratio`.  In other words, `ratio` may be treated as
 * an interpolation factor between the two stops' output values.
 *
 * (Note: a slightly different form for `ratio`,
 * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer
 * expensive `Math.pow()` operations.)
 *
 * @private
*/
function exponentialInterpolation(input, base, lowerValue, upperValue) {
    const difference = upperValue - lowerValue;
    const progress = input - lowerValue;
    if (difference === 0) {
        return 0;
    } else if (base === 1) {
        return progress / difference;
    } else {
        return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);
    }
}
var Interpolate$1 = Interpolate;

class Coalesce {
    constructor(type, args) {
        this.type = type;
        this.args = args;
    }
    static parse(args, context) {
        if (args.length < 2) {
            return context.error('Expectected at least one argument.');
        }
        let outputType = null;
        const expectedType = context.expectedType;
        if (expectedType && expectedType.kind !== 'value') {
            outputType = expectedType;
        }
        const parsedArgs = [];
        for (const arg of args.slice(1)) {
            const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' });
            if (!parsed)
                return null;
            outputType = outputType || parsed.type;
            parsedArgs.push(parsed);
        }
        // Above, we parse arguments without inferred type annotation so that
        // they don't produce a runtime error for `null` input, which would
        // preempt the desired null-coalescing behavior.
        // Thus, if any of our arguments would have needed an annotation, we
        // need to wrap the enclosing coalesce expression with it instead.
        const needsAnnotation = expectedType && parsedArgs.some(arg => checkSubtype(expectedType, arg.type));
        return needsAnnotation ? new Coalesce(ValueType, parsedArgs) : new Coalesce(outputType, parsedArgs);
    }
    evaluate(ctx) {
        let result = null;
        let argCount = 0;
        let firstImage;
        for (const arg of this.args) {
            argCount++;
            result = arg.evaluate(ctx);
            // we need to keep track of the first requested image in a coalesce statement
            // if coalesce can't find a valid image, we return the first image so styleimagemissing can fire
            if (result && result instanceof ResolvedImage && !result.available) {
                // set to first image
                if (!firstImage) {
                    firstImage = result;
                }
                result = null;
                // if we reach the end, return the first image
                if (argCount === this.args.length) {
                    return firstImage;
                }
            }
            if (result !== null)
                break;
        }
        return result;
    }
    eachChild(fn) {
        this.args.forEach(fn);
    }
    outputDefined() {
        return this.args.every(arg => arg.outputDefined());
    }
    serialize() {
        const serialized = ['coalesce'];
        this.eachChild(child => {
            serialized.push(child.serialize());
        });
        return serialized;
    }
}
var Coalesce$1 = Coalesce;

//      
class Let {
    constructor(bindings, result) {
        this.type = result.type;
        this.bindings = [].concat(bindings);
        this.result = result;
    }
    evaluate(ctx) {
        return this.result.evaluate(ctx);
    }
    eachChild(fn) {
        for (const binding of this.bindings) {
            fn(binding[1]);
        }
        fn(this.result);
    }
    static parse(args, context) {
        if (args.length < 4)
            return context.error(`Expected at least 3 arguments, but found ${ args.length - 1 } instead.`);
        const bindings = [];
        for (let i = 1; i < args.length - 1; i += 2) {
            const name = args[i];
            if (typeof name !== 'string') {
                return context.error(`Expected string, but found ${ typeof name } instead.`, i);
            }
            if (/[^a-zA-Z0-9_]/.test(name)) {
                return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i);
            }
            const value = context.parse(args[i + 1], i + 1);
            if (!value)
                return null;
            bindings.push([
                name,
                value
            ]);
        }
        const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);
        if (!result)
            return null;
        return new Let(bindings, result);
    }
    outputDefined() {
        return this.result.outputDefined();
    }
    serialize() {
        const serialized = ['let'];
        for (const [name, expr] of this.bindings) {
            serialized.push(name, expr.serialize());
        }
        serialized.push(this.result.serialize());
        return serialized;
    }
}
var Let$1 = Let;

//      
class At {
    constructor(type, index, input) {
        this.type = type;
        this.index = index;
        this.input = input;
    }
    static parse(args, context) {
        if (args.length !== 3)
            return context.error(`Expected 2 arguments, but found ${ args.length - 1 } instead.`);
        const index = context.parse(args[1], 1, NumberType);
        const input = context.parse(args[2], 2, array$1(context.expectedType || ValueType));
        if (!index || !input)
            return null;
        const t = input.type;
        return new At(t.itemType, index, input);
    }
    evaluate(ctx) {
        const index = this.index.evaluate(ctx);
        const array = this.input.evaluate(ctx);
        if (index < 0) {
            throw new RuntimeError$1(`Array index out of bounds: ${ index } < 0.`);
        }
        if (index >= array.length) {
            throw new RuntimeError$1(`Array index out of bounds: ${ index } > ${ array.length - 1 }.`);
        }
        if (index !== Math.floor(index)) {
            throw new RuntimeError$1(`Array index must be an integer, but found ${ index } instead.`);
        }
        return array[index];
    }
    eachChild(fn) {
        fn(this.index);
        fn(this.input);
    }
    outputDefined() {
        return false;
    }
    serialize() {
        return [
            'at',
            this.index.serialize(),
            this.input.serialize()
        ];
    }
}
var At$1 = At;

//      
class In {
    constructor(needle, haystack) {
        this.type = BooleanType;
        this.needle = needle;
        this.haystack = haystack;
    }
    static parse(args, context) {
        if (args.length !== 3) {
            return context.error(`Expected 2 arguments, but found ${ args.length - 1 } instead.`);
        }
        const needle = context.parse(args[1], 1, ValueType);
        const haystack = context.parse(args[2], 2, ValueType);
        if (!needle || !haystack)
            return null;
        if (!isValidType(needle.type, [
                BooleanType,
                StringType,
                NumberType,
                NullType,
                ValueType
            ])) {
            return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${ toString$1(needle.type) } instead`);
        }
        return new In(needle, haystack);
    }
    evaluate(ctx) {
        const needle = this.needle.evaluate(ctx);
        const haystack = this.haystack.evaluate(ctx);
        if (haystack == null)
            return false;
        if (!isValidNativeType(needle, [
                'boolean',
                'string',
                'number',
                'null'
            ])) {
            throw new RuntimeError$1(`Expected first argument to be of type boolean, string, number or null, but found ${ toString$1(typeOf(needle)) } instead.`);
        }
        if (!isValidNativeType(haystack, [
                'string',
                'array'
            ])) {
            throw new RuntimeError$1(`Expected second argument to be of type array or string, but found ${ toString$1(typeOf(haystack)) } instead.`);
        }
        return haystack.indexOf(needle) >= 0;
    }
    eachChild(fn) {
        fn(this.needle);
        fn(this.haystack);
    }
    outputDefined() {
        return true;
    }
    serialize() {
        return [
            'in',
            this.needle.serialize(),
            this.haystack.serialize()
        ];
    }
}
var In$1 = In;

//      
class IndexOf {
    constructor(needle, haystack, fromIndex) {
        this.type = NumberType;
        this.needle = needle;
        this.haystack = haystack;
        this.fromIndex = fromIndex;
    }
    static parse(args, context) {
        if (args.length <= 2 || args.length >= 5) {
            return context.error(`Expected 3 or 4 arguments, but found ${ args.length - 1 } instead.`);
        }
        const needle = context.parse(args[1], 1, ValueType);
        const haystack = context.parse(args[2], 2, ValueType);
        if (!needle || !haystack)
            return null;
        if (!isValidType(needle.type, [
                BooleanType,
                StringType,
                NumberType,
                NullType,
                ValueType
            ])) {
            return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${ toString$1(needle.type) } instead`);
        }
        if (args.length === 4) {
            const fromIndex = context.parse(args[3], 3, NumberType);
            if (!fromIndex)
                return null;
            return new IndexOf(needle, haystack, fromIndex);
        } else {
            return new IndexOf(needle, haystack);
        }
    }
    evaluate(ctx) {
        const needle = this.needle.evaluate(ctx);
        const haystack = this.haystack.evaluate(ctx);
        if (!isValidNativeType(needle, [
                'boolean',
                'string',
                'number',
                'null'
            ])) {
            throw new RuntimeError$1(`Expected first argument to be of type boolean, string, number or null, but found ${ toString$1(typeOf(needle)) } instead.`);
        }
        if (!isValidNativeType(haystack, [
                'string',
                'array'
            ])) {
            throw new RuntimeError$1(`Expected second argument to be of type array or string, but found ${ toString$1(typeOf(haystack)) } instead.`);
        }
        if (this.fromIndex) {
            const fromIndex = this.fromIndex.evaluate(ctx);
            return haystack.indexOf(needle, fromIndex);
        }
        return haystack.indexOf(needle);
    }
    eachChild(fn) {
        fn(this.needle);
        fn(this.haystack);
        if (this.fromIndex) {
            fn(this.fromIndex);
        }
    }
    outputDefined() {
        return false;
    }
    serialize() {
        if (this.fromIndex != null && this.fromIndex !== undefined) {
            const fromIndex = this.fromIndex.serialize();
            return [
                'index-of',
                this.needle.serialize(),
                this.haystack.serialize(),
                fromIndex
            ];
        }
        return [
            'index-of',
            this.needle.serialize(),
            this.haystack.serialize()
        ];
    }
}
var IndexOf$1 = IndexOf;

// Map input label values to output expression index
class Match {
    constructor(inputType, outputType, input, cases, outputs, otherwise) {
        this.inputType = inputType;
        this.type = outputType;
        this.input = input;
        this.cases = cases;
        this.outputs = outputs;
        this.otherwise = otherwise;
    }
    static parse(args, context) {
        if (args.length < 5)
            return context.error(`Expected at least 4 arguments, but found only ${ args.length - 1 }.`);
        if (args.length % 2 !== 1)
            return context.error(`Expected an even number of arguments.`);
        let inputType;
        let outputType;
        if (context.expectedType && context.expectedType.kind !== 'value') {
            outputType = context.expectedType;
        }
        const cases = {};
        const outputs = [];
        for (let i = 2; i < args.length - 1; i += 2) {
            let labels = args[i];
            const value = args[i + 1];
            if (!Array.isArray(labels)) {
                labels = [labels];
            }
            const labelContext = context.concat(i);
            if (labels.length === 0) {
                return labelContext.error('Expected at least one branch label.');
            }
            for (const label of labels) {
                if (typeof label !== 'number' && typeof label !== 'string') {
                    return labelContext.error(`Branch labels must be numbers or strings.`);
                } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) {
                    return labelContext.error(`Branch labels must be integers no larger than ${ Number.MAX_SAFE_INTEGER }.`);
                } else if (typeof label === 'number' && Math.floor(label) !== label) {
                    return labelContext.error(`Numeric branch labels must be integer values.`);
                } else if (!inputType) {
                    inputType = typeOf(label);
                } else if (labelContext.checkSubtype(inputType, typeOf(label))) {
                    return null;
                }
                if (typeof cases[String(label)] !== 'undefined') {
                    return labelContext.error('Branch labels must be unique.');
                }
                cases[String(label)] = outputs.length;
            }
            const result = context.parse(value, i, outputType);
            if (!result)
                return null;
            outputType = outputType || result.type;
            outputs.push(result);
        }
        const input = context.parse(args[1], 1, ValueType);
        if (!input)
            return null;
        const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
        if (!otherwise)
            return null;
        if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) {
            return null;
        }
        return new Match(inputType, outputType, input, cases, outputs, otherwise);
    }
    evaluate(ctx) {
        const input = this.input.evaluate(ctx);
        const output = typeOf(input) === this.inputType && this.outputs[this.cases[input]] || this.otherwise;
        return output.evaluate(ctx);
    }
    eachChild(fn) {
        fn(this.input);
        this.outputs.forEach(fn);
        fn(this.otherwise);
    }
    outputDefined() {
        return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined();
    }
    serialize() {
        const serialized = [
            'match',
            this.input.serialize()
        ];
        // Sort so serialization has an arbitrary defined order, even though
        // branch order doesn't affect evaluation
        const sortedLabels = Object.keys(this.cases).sort();
        // Group branches by unique match expression to support condensed
        // serializations of the form [case1, case2, ...] -> matchExpression
        const groupedByOutput = [];
        const outputLookup = {};
        // lookup index into groupedByOutput for a given output expression
        for (const label of sortedLabels) {
            const outputIndex = outputLookup[this.cases[label]];
            if (outputIndex === undefined) {
                // First time seeing this output, add it to the end of the grouped list
                outputLookup[this.cases[label]] = groupedByOutput.length;
                groupedByOutput.push([
                    this.cases[label],
                    [label]
                ]);
            } else {
                // We've seen this expression before, add the label to that output's group
                groupedByOutput[outputIndex][1].push(label);
            }
        }
        const coerceLabel = label => this.inputType.kind === 'number' ? Number(label) : label;
        for (const [outputIndex, labels] of groupedByOutput) {
            if (labels.length === 1) {
                // Only a single label matches this output expression
                serialized.push(coerceLabel(labels[0]));
            } else {
                // Array of literal labels pointing to this output expression
                serialized.push(labels.map(coerceLabel));
            }
            serialized.push(this.outputs[outputIndex].serialize());
        }
        serialized.push(this.otherwise.serialize());
        return serialized;
    }
}
var Match$1 = Match;

class Case {
    constructor(type, branches, otherwise) {
        this.type = type;
        this.branches = branches;
        this.otherwise = otherwise;
    }
    static parse(args, context) {
        if (args.length < 4)
            return context.error(`Expected at least 3 arguments, but found only ${ args.length - 1 }.`);
        if (args.length % 2 !== 0)
            return context.error(`Expected an odd number of arguments.`);
        let outputType;
        if (context.expectedType && context.expectedType.kind !== 'value') {
            outputType = context.expectedType;
        }
        const branches = [];
        for (let i = 1; i < args.length - 1; i += 2) {
            const test = context.parse(args[i], i, BooleanType);
            if (!test)
                return null;
            const result = context.parse(args[i + 1], i + 1, outputType);
            if (!result)
                return null;
            branches.push([
                test,
                result
            ]);
            outputType = outputType || result.type;
        }
        const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
        if (!otherwise)
            return null;
        return new Case(outputType, branches, otherwise);
    }
    evaluate(ctx) {
        for (const [test, expression] of this.branches) {
            if (test.evaluate(ctx)) {
                return expression.evaluate(ctx);
            }
        }
        return this.otherwise.evaluate(ctx);
    }
    eachChild(fn) {
        for (const [test, expression] of this.branches) {
            fn(test);
            fn(expression);
        }
        fn(this.otherwise);
    }
    outputDefined() {
        return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();
    }
    serialize() {
        const serialized = ['case'];
        this.eachChild(child => {
            serialized.push(child.serialize());
        });
        return serialized;
    }
}
var Case$1 = Case;

//      
class Slice {
    constructor(type, input, beginIndex, endIndex) {
        this.type = type;
        this.input = input;
        this.beginIndex = beginIndex;
        this.endIndex = endIndex;
    }
    static parse(args, context) {
        if (args.length <= 2 || args.length >= 5) {
            return context.error(`Expected 3 or 4 arguments, but found ${ args.length - 1 } instead.`);
        }
        const input = context.parse(args[1], 1, ValueType);
        const beginIndex = context.parse(args[2], 2, NumberType);
        if (!input || !beginIndex)
            return null;
        if (!isValidType(input.type, [
                array$1(ValueType),
                StringType,
                ValueType
            ])) {
            return context.error(`Expected first argument to be of type array or string, but found ${ toString$1(input.type) } instead`);
        }
        if (args.length === 4) {
            const endIndex = context.parse(args[3], 3, NumberType);
            if (!endIndex)
                return null;
            return new Slice(input.type, input, beginIndex, endIndex);
        } else {
            return new Slice(input.type, input, beginIndex);
        }
    }
    evaluate(ctx) {
        const input = this.input.evaluate(ctx);
        const beginIndex = this.beginIndex.evaluate(ctx);
        if (!isValidNativeType(input, [
                'string',
                'array'
            ])) {
            throw new RuntimeError$1(`Expected first argument to be of type array or string, but found ${ toString$1(typeOf(input)) } instead.`);
        }
        if (this.endIndex) {
            const endIndex = this.endIndex.evaluate(ctx);
            return input.slice(beginIndex, endIndex);
        }
        return input.slice(beginIndex);
    }
    eachChild(fn) {
        fn(this.input);
        fn(this.beginIndex);
        if (this.endIndex) {
            fn(this.endIndex);
        }
    }
    outputDefined() {
        return false;
    }
    serialize() {
        if (this.endIndex != null && this.endIndex !== undefined) {
            const endIndex = this.endIndex.serialize();
            return [
                'slice',
                this.input.serialize(),
                this.beginIndex.serialize(),
                endIndex
            ];
        }
        return [
            'slice',
            this.input.serialize(),
            this.beginIndex.serialize()
        ];
    }
}
var Slice$1 = Slice;

//      
function isComparableType(op, type) {
    if (op === '==' || op === '!=') {
        // equality operator
        return type.kind === 'boolean' || type.kind === 'string' || type.kind === 'number' || type.kind === 'null' || type.kind === 'value';
    } else {
        // ordering operator
        return type.kind === 'string' || type.kind === 'number' || type.kind === 'value';
    }
}
function eq(ctx, a, b) {
    return a === b;
}
function neq(ctx, a, b) {
    return a !== b;
}
function lt(ctx, a, b) {
    return a < b;
}
function gt(ctx, a, b) {
    return a > b;
}
function lteq(ctx, a, b) {
    return a <= b;
}
function gteq(ctx, a, b) {
    return a >= b;
}
function eqCollate(ctx, a, b, c) {
    return c.compare(a, b) === 0;
}
function neqCollate(ctx, a, b, c) {
    return !eqCollate(ctx, a, b, c);
}
function ltCollate(ctx, a, b, c) {
    return c.compare(a, b) < 0;
}
function gtCollate(ctx, a, b, c) {
    return c.compare(a, b) > 0;
}
function lteqCollate(ctx, a, b, c) {
    return c.compare(a, b) <= 0;
}
function gteqCollate(ctx, a, b, c) {
    return c.compare(a, b) >= 0;
}
/**
 * Special form for comparison operators, implementing the signatures:
 * - (T, T, ?Collator) => boolean
 * - (T, value, ?Collator) => boolean
 * - (value, T, ?Collator) => boolean
 *
 * For inequalities, T must be either value, string, or number. For ==/!=, it
 * can also be boolean or null.
 *
 * Equality semantics are equivalent to Javascript's strict equality (===/!==)
 * -- i.e., when the arguments' types don't match, == evaluates to false, != to
 * true.
 *
 * When types don't match in an ordering comparison, a runtime error is thrown.
 *
 * @private
 */
function makeComparison(op, compareBasic, compareWithCollator) {
    const isOrderComparison = op !== '==' && op !== '!=';
    // $FlowFixMe[method-unbinding]
    return class Comparison {
        constructor(lhs, rhs, collator) {
            this.type = BooleanType;
            this.lhs = lhs;
            this.rhs = rhs;
            this.collator = collator;
            this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value';
        }
        // $FlowFixMe[method-unbinding]
        static parse(args, context) {
            if (args.length !== 3 && args.length !== 4)
                return context.error(`Expected two or three arguments.`);
            const op = args[0];
            let lhs = context.parse(args[1], 1, ValueType);
            if (!lhs)
                return null;
            if (!isComparableType(op, lhs.type)) {
                return context.concat(1).error(`"${ op }" comparisons are not supported for type '${ toString$1(lhs.type) }'.`);
            }
            let rhs = context.parse(args[2], 2, ValueType);
            if (!rhs)
                return null;
            if (!isComparableType(op, rhs.type)) {
                return context.concat(2).error(`"${ op }" comparisons are not supported for type '${ toString$1(rhs.type) }'.`);
            }
            if (lhs.type.kind !== rhs.type.kind && lhs.type.kind !== 'value' && rhs.type.kind !== 'value') {
                return context.error(`Cannot compare types '${ toString$1(lhs.type) }' and '${ toString$1(rhs.type) }'.`);
            }
            if (isOrderComparison) {
                // typing rules specific to less/greater than operators
                if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {
                    // (value, T)
                    lhs = new Assertion$1(rhs.type, [lhs]);
                } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {
                    // (T, value)
                    rhs = new Assertion$1(lhs.type, [rhs]);
                }
            }
            let collator = null;
            if (args.length === 4) {
                if (lhs.type.kind !== 'string' && rhs.type.kind !== 'string' && lhs.type.kind !== 'value' && rhs.type.kind !== 'value') {
                    return context.error(`Cannot use collator to compare non-string types.`);
                }
                collator = context.parse(args[3], 3, CollatorType);
                if (!collator)
                    return null;
            }
            return new Comparison(lhs, rhs, collator);
        }
        evaluate(ctx) {
            const lhs = this.lhs.evaluate(ctx);
            const rhs = this.rhs.evaluate(ctx);
            if (isOrderComparison && this.hasUntypedArgument) {
                const lt = typeOf(lhs);
                const rt = typeOf(rhs);
                // check that type is string or number, and equal
                if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) {
                    throw new RuntimeError$1(`Expected arguments for "${ op }" to be (string, string) or (number, number), but found (${ lt.kind }, ${ rt.kind }) instead.`);
                }
            }
            if (this.collator && !isOrderComparison && this.hasUntypedArgument) {
                const lt = typeOf(lhs);
                const rt = typeOf(rhs);
                if (lt.kind !== 'string' || rt.kind !== 'string') {
                    return compareBasic(ctx, lhs, rhs);
                }
            }
            return this.collator ? compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : compareBasic(ctx, lhs, rhs);
        }
        eachChild(fn) {
            fn(this.lhs);
            fn(this.rhs);
            if (this.collator) {
                fn(this.collator);
            }
        }
        outputDefined() {
            return true;
        }
        serialize() {
            const serialized = [op];
            this.eachChild(child => {
                serialized.push(child.serialize());
            });
            return serialized;
        }
    };
}
const Equals = makeComparison('==', eq, eqCollate);
const NotEquals = makeComparison('!=', neq, neqCollate);
const LessThan = makeComparison('<', lt, ltCollate);
const GreaterThan = makeComparison('>', gt, gtCollate);
const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);
const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);

//      
class NumberFormat {
    // BCP 47 language tag
    // ISO 4217 currency code, required if style=currency
    // Simple units sanctioned for use in ECMAScript, required if style=unit. https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier
    // Default 0
    // Default 3
    constructor(number, locale, currency, unit, minFractionDigits, maxFractionDigits) {
        this.type = StringType;
        this.number = number;
        this.locale = locale;
        this.currency = currency;
        this.unit = unit;
        this.minFractionDigits = minFractionDigits;
        this.maxFractionDigits = maxFractionDigits;
    }
    static parse(args, context) {
        if (args.length !== 3)
            return context.error(`Expected two arguments.`);
        const number = context.parse(args[1], 1, NumberType);
        if (!number)
            return null;
        const options = args[2];
        if (typeof options !== 'object' || Array.isArray(options))
            return context.error(`NumberFormat options argument must be an object.`);
        let locale = null;
        if (options['locale']) {
            locale = context.parse(options['locale'], 1, StringType);
            if (!locale)
                return null;
        }
        let currency = null;
        if (options['currency']) {
            currency = context.parse(options['currency'], 1, StringType);
            if (!currency)
                return null;
        }
        let unit = null;
        if (options['unit']) {
            unit = context.parse(options['unit'], 1, StringType);
            if (!unit)
                return null;
        }
        let minFractionDigits = null;
        if (options['min-fraction-digits']) {
            minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);
            if (!minFractionDigits)
                return null;
        }
        let maxFractionDigits = null;
        if (options['max-fraction-digits']) {
            maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);
            if (!maxFractionDigits)
                return null;
        }
        return new NumberFormat(number, locale, currency, unit, minFractionDigits, maxFractionDigits);
    }
    evaluate(ctx) {
        return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], {
            style: this.currency && 'currency' || this.unit && 'unit' || 'decimal',
            currency: this.currency ? this.currency.evaluate(ctx) : undefined,
            unit: this.unit ? this.unit.evaluate(ctx) : undefined,
            minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined,
            maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined
        }).format(this.number.evaluate(ctx));
    }
    eachChild(fn) {
        fn(this.number);
        if (this.locale) {
            fn(this.locale);
        }
        if (this.currency) {
            fn(this.currency);
        }
        if (this.unit) {
            fn(this.unit);
        }
        if (this.minFractionDigits) {
            fn(this.minFractionDigits);
        }
        if (this.maxFractionDigits) {
            fn(this.maxFractionDigits);
        }
    }
    outputDefined() {
        return false;
    }
    serialize() {
        const options = {};
        if (this.locale) {
            options['locale'] = this.locale.serialize();
        }
        if (this.currency) {
            options['currency'] = this.currency.serialize();
        }
        if (this.unit) {
            options['unit'] = this.unit.serialize();
        }
        if (this.minFractionDigits) {
            options['min-fraction-digits'] = this.minFractionDigits.serialize();
        }
        if (this.maxFractionDigits) {
            options['max-fraction-digits'] = this.maxFractionDigits.serialize();
        }
        return [
            'number-format',
            this.number.serialize(),
            options
        ];
    }
}

//      
class Length {
    constructor(input) {
        this.type = NumberType;
        this.input = input;
    }
    static parse(args, context) {
        if (args.length !== 2)
            return context.error(`Expected 1 argument, but found ${ args.length - 1 } instead.`);
        const input = context.parse(args[1], 1);
        if (!input)
            return null;
        if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value')
            return context.error(`Expected argument of type string or array, but found ${ toString$1(input.type) } instead.`);
        return new Length(input);
    }
    evaluate(ctx) {
        const input = this.input.evaluate(ctx);
        if (typeof input === 'string') {
            return input.length;
        } else if (Array.isArray(input)) {
            return input.length;
        } else {
            throw new RuntimeError$1(`Expected value to be of type string or array, but found ${ toString$1(typeOf(input)) } instead.`);
        }
    }
    eachChild(fn) {
        fn(this.input);
    }
    outputDefined() {
        return false;
    }
    serialize() {
        const serialized = ['length'];
        this.eachChild(child => {
            serialized.push(child.serialize());
        });
        return serialized;
    }
}
var Length$1 = Length;

//      
// Seeded pseudo random generator function
function mulberry32(a) {
    return function () {
        a |= 0;
        a = a + 1831565813 | 0;
        let t = Math.imul(a ^ a >>> 15, 1 | a);
        t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
        return ((t ^ t >>> 14) >>> 0) / 4294967296;
    };
}

//      
const expressions = {
    // special forms
    '==': Equals,
    '!=': NotEquals,
    '>': GreaterThan,
    '<': LessThan,
    '>=': GreaterThanOrEqual,
    '<=': LessThanOrEqual,
    // $FlowFixMe[method-unbinding]
    'array': Assertion$1,
    // $FlowFixMe[method-unbinding]
    'at': At$1,
    'boolean': Assertion$1,
    // $FlowFixMe[method-unbinding]
    'case': Case$1,
    // $FlowFixMe[method-unbinding]
    'coalesce': Coalesce$1,
    // $FlowFixMe[method-unbinding]
    'collator': CollatorExpression,
    // $FlowFixMe[method-unbinding]
    'format': FormatExpression,
    // $FlowFixMe[method-unbinding]
    'image': ImageExpression,
    // $FlowFixMe[method-unbinding]
    'in': In$1,
    // $FlowFixMe[method-unbinding]
    'index-of': IndexOf$1,
    // $FlowFixMe[method-unbinding]
    'interpolate': Interpolate$1,
    'interpolate-hcl': Interpolate$1,
    'interpolate-lab': Interpolate$1,
    // $FlowFixMe[method-unbinding]
    'length': Length$1,
    // $FlowFixMe[method-unbinding]
    'let': Let$1,
    // $FlowFixMe[method-unbinding]
    'literal': Literal$1,
    // $FlowFixMe[method-unbinding]
    'match': Match$1,
    'number': Assertion$1,
    // $FlowFixMe[method-unbinding]
    'number-format': NumberFormat,
    'object': Assertion$1,
    // $FlowFixMe[method-unbinding]
    'slice': Slice$1,
    // $FlowFixMe[method-unbinding]
    'step': Step$1,
    'string': Assertion$1,
    // $FlowFixMe[method-unbinding]
    'to-boolean': Coercion$1,
    'to-color': Coercion$1,
    'to-number': Coercion$1,
    'to-string': Coercion$1,
    // $FlowFixMe[method-unbinding]
    'var': Var$1,
    // $FlowFixMe[method-unbinding]
    'within': Within$1,
    // $FlowFixMe[method-unbinding]
    'distance': Distance$1
};
function rgba(ctx, [r, g, b, a]) {
    r = r.evaluate(ctx);
    g = g.evaluate(ctx);
    b = b.evaluate(ctx);
    const alpha = a ? a.evaluate(ctx) : 1;
    const error = validateRGBA(r, g, b, alpha);
    if (error)
        throw new RuntimeError$1(error);
    return new Color$1(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);
}
function hsla(ctx, [h, s, l, a]) {
    h = h.evaluate(ctx);
    s = s.evaluate(ctx);
    l = l.evaluate(ctx);
    const alpha = a ? a.evaluate(ctx) : 1;
    const error = validateHSLA(h, s, l, alpha);
    if (error)
        throw new RuntimeError$1(error);
    const colorFunction = `hsla(${ h }, ${ s }%, ${ l }%, ${ alpha })`;
    const color = Color$1.parse(colorFunction);
    if (!color)
        throw new RuntimeError$1(`Failed to parse HSLA color: ${ colorFunction }`);
    return color;
}
function has(key, obj) {
    return key in obj;
}
function get(key, obj) {
    const v = obj[key];
    return typeof v === 'undefined' ? null : v;
}
function getConfig(ctx, key, scope) {
    if (scope.length) {
        key += `\u{1f}${ scope }`;
    }
    const v = ctx.getConfig(key);
    return v ? v.evaluate(ctx) : null;
}
function binarySearch(v, a, i, j) {
    while (i <= j) {
        const m = i + j >> 1;
        if (a[m] === v)
            return true;
        if (a[m] > v)
            j = m - 1;
        else
            i = m + 1;
    }
    return false;
}
function varargs(type) {
    return { type };
}
function hashString(str) {
    let hash = 0;
    if (str.length === 0) {
        return hash;
    }
    for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash;
    }
    return hash;
}
CompoundExpression$1.register(expressions, {
    'error': [
        ErrorType,
        [StringType],
        (ctx, [v]) => {
            throw new RuntimeError$1(v.evaluate(ctx));
        }
    ],
    'typeof': [
        StringType,
        [ValueType],
        (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx)))
    ],
    'to-rgba': [
        array$1(NumberType, 4),
        [ColorType],
        (ctx, [v]) => {
            return v.evaluate(ctx).toArray();
        }
    ],
    'rgb': [
        ColorType,
        [
            NumberType,
            NumberType,
            NumberType
        ],
        rgba
    ],
    'rgba': [
        ColorType,
        [
            NumberType,
            NumberType,
            NumberType,
            NumberType
        ],
        rgba
    ],
    'hsl': [
        ColorType,
        [
            NumberType,
            NumberType,
            NumberType
        ],
        hsla
    ],
    'hsla': [
        ColorType,
        [
            NumberType,
            NumberType,
            NumberType,
            NumberType
        ],
        hsla
    ],
    'has': {
        type: BooleanType,
        overloads: [
            [
                [StringType],
                (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())
            ],
            [
                [
                    StringType,
                    ObjectType
                ],
                (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))
            ]
        ]
    },
    'get': {
        type: ValueType,
        overloads: [
            [
                [StringType],
                (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())
            ],
            [
                [
                    StringType,
                    ObjectType
                ],
                (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))
            ]
        ]
    },
    'config': {
        type: ValueType,
        overloads: [
            [
                [StringType],
                (ctx, [key]) => getConfig(ctx, key.evaluate(ctx), '')
            ],
            [
                [
                    StringType,
                    StringType
                ],
                (ctx, [key, scope]) => getConfig(ctx, key.evaluate(ctx), scope.evaluate(ctx))
            ]
        ]
    },
    'feature-state': [
        ValueType,
        [StringType],
        (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})
    ],
    'properties': [
        ObjectType,
        [],
        ctx => ctx.properties()
    ],
    'geometry-type': [
        StringType,
        [],
        ctx => ctx.geometryType()
    ],
    'id': [
        ValueType,
        [],
        ctx => ctx.id()
    ],
    'zoom': [
        NumberType,
        [],
        ctx => ctx.globals.zoom
    ],
    'pitch': [
        NumberType,
        [],
        ctx => ctx.globals.pitch || 0
    ],
    'distance-from-center': [
        NumberType,
        [],
        ctx => ctx.distanceFromCenter()
    ],
    'measure-light': [
        NumberType,
        [StringType],
        (ctx, [s]) => ctx.measureLight(s.evaluate(ctx))
    ],
    'heatmap-density': [
        NumberType,
        [],
        ctx => ctx.globals.heatmapDensity || 0
    ],
    'line-progress': [
        NumberType,
        [],
        ctx => ctx.globals.lineProgress || 0
    ],
    'raster-value': [
        NumberType,
        [],
        ctx => ctx.globals.rasterValue || 0
    ],
    'sky-radial-progress': [
        NumberType,
        [],
        ctx => ctx.globals.skyRadialProgress || 0
    ],
    'accumulated': [
        ValueType,
        [],
        ctx => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated
    ],
    '+': [
        NumberType,
        varargs(NumberType),
        (ctx, args) => {
            let result = 0;
            for (const arg of args) {
                result += arg.evaluate(ctx);
            }
            return result;
        }
    ],
    '*': [
        NumberType,
        varargs(NumberType),
        (ctx, args) => {
            let result = 1;
            for (const arg of args) {
                result *= arg.evaluate(ctx);
            }
            return result;
        }
    ],
    '-': {
        type: NumberType,
        overloads: [
            [
                [
                    NumberType,
                    NumberType
                ],
                (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)
            ],
            [
                [NumberType],
                (ctx, [a]) => -a.evaluate(ctx)
            ]
        ]
    },
    '/': [
        NumberType,
        [
            NumberType,
            NumberType
        ],
        (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)
    ],
    '%': [
        NumberType,
        [
            NumberType,
            NumberType
        ],
        (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)
    ],
    'ln2': [
        NumberType,
        [],
        () => Math.LN2
    ],
    'pi': [
        NumberType,
        [],
        () => Math.PI
    ],
    'e': [
        NumberType,
        [],
        () => Math.E
    ],
    '^': [
        NumberType,
        [
            NumberType,
            NumberType
        ],
        (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))
    ],
    'sqrt': [
        NumberType,
        [NumberType],
        (ctx, [x]) => Math.sqrt(x.evaluate(ctx))
    ],
    'log10': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10
    ],
    'ln': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.log(n.evaluate(ctx))
    ],
    'log2': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2
    ],
    'sin': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.sin(n.evaluate(ctx))
    ],
    'cos': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.cos(n.evaluate(ctx))
    ],
    'tan': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.tan(n.evaluate(ctx))
    ],
    'asin': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.asin(n.evaluate(ctx))
    ],
    'acos': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.acos(n.evaluate(ctx))
    ],
    'atan': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.atan(n.evaluate(ctx))
    ],
    'min': [
        NumberType,
        varargs(NumberType),
        (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))
    ],
    'max': [
        NumberType,
        varargs(NumberType),
        (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))
    ],
    'abs': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.abs(n.evaluate(ctx))
    ],
    'round': [
        NumberType,
        [NumberType],
        (ctx, [n]) => {
            const v = n.evaluate(ctx);
            // Javascript's Math.round() rounds towards +Infinity for halfway
            // values, even when they're negative. It's more common to round
            // away from 0 (e.g., this is what python and C++ do)
            return v < 0 ? -Math.round(-v) : Math.round(v);
        }
    ],
    'floor': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.floor(n.evaluate(ctx))
    ],
    'ceil': [
        NumberType,
        [NumberType],
        (ctx, [n]) => Math.ceil(n.evaluate(ctx))
    ],
    'filter-==': [
        BooleanType,
        [
            StringType,
            ValueType
        ],
        (ctx, [k, v]) => ctx.properties()[k.value] === v.value
    ],
    'filter-id-==': [
        BooleanType,
        [ValueType],
        (ctx, [v]) => ctx.id() === v.value
    ],
    'filter-type-==': [
        BooleanType,
        [StringType],
        (ctx, [v]) => ctx.geometryType() === v.value
    ],
    'filter-<': [
        BooleanType,
        [
            StringType,
            ValueType
        ],
        (ctx, [k, v]) => {
            const a = ctx.properties()[k.value];
            const b = v.value;
            return typeof a === typeof b && a < b;
        }
    ],
    'filter-id-<': [
        BooleanType,
        [ValueType],
        (ctx, [v]) => {
            const a = ctx.id();
            const b = v.value;
            return typeof a === typeof b && a < b;
        }
    ],
    'filter->': [
        BooleanType,
        [
            StringType,
            ValueType
        ],
        (ctx, [k, v]) => {
            const a = ctx.properties()[k.value];
            const b = v.value;
            return typeof a === typeof b && a > b;
        }
    ],
    'filter-id->': [
        BooleanType,
        [ValueType],
        (ctx, [v]) => {
            const a = ctx.id();
            const b = v.value;
            return typeof a === typeof b && a > b;
        }
    ],
    'filter-<=': [
        BooleanType,
        [
            StringType,
            ValueType
        ],
        (ctx, [k, v]) => {
            const a = ctx.properties()[k.value];
            const b = v.value;
            return typeof a === typeof b && a <= b;
        }
    ],
    'filter-id-<=': [
        BooleanType,
        [ValueType],
        (ctx, [v]) => {
            const a = ctx.id();
            const b = v.value;
            return typeof a === typeof b && a <= b;
        }
    ],
    'filter->=': [
        BooleanType,
        [
            StringType,
            ValueType
        ],
        (ctx, [k, v]) => {
            const a = ctx.properties()[k.value];
            const b = v.value;
            return typeof a === typeof b && a >= b;
        }
    ],
    'filter-id->=': [
        BooleanType,
        [ValueType],
        (ctx, [v]) => {
            const a = ctx.id();
            const b = v.value;
            return typeof a === typeof b && a >= b;
        }
    ],
    'filter-has': [
        BooleanType,
        [ValueType],
        (ctx, [k]) => k.value in ctx.properties()
    ],
    'filter-has-id': [
        BooleanType,
        [],
        ctx => ctx.id() !== null && ctx.id() !== undefined
    ],
    'filter-type-in': [
        BooleanType,
        [array$1(StringType)],
        (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0
    ],
    'filter-id-in': [
        BooleanType,
        [array$1(ValueType)],
        (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0
    ],
    'filter-in-small': [
        BooleanType,
        [
            StringType,
            array$1(ValueType)
        ],
        // assumes v is an array literal
        (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0
    ],
    'filter-in-large': [
        BooleanType,
        [
            StringType,
            array$1(ValueType)
        ],
        // assumes v is a array literal with values sorted in ascending order and of a single type
        (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1)
    ],
    'all': {
        type: BooleanType,
        overloads: [
            [
                [
                    BooleanType,
                    BooleanType
                ],
                (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)
            ],
            [
                varargs(BooleanType),
                (ctx, args) => {
                    for (const arg of args) {
                        if (!arg.evaluate(ctx))
                            return false;
                    }
                    return true;
                }
            ]
        ]
    },
    'any': {
        type: BooleanType,
        overloads: [
            [
                [
                    BooleanType,
                    BooleanType
                ],
                (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)
            ],
            [
                varargs(BooleanType),
                (ctx, args) => {
                    for (const arg of args) {
                        if (arg.evaluate(ctx))
                            return true;
                    }
                    return false;
                }
            ]
        ]
    },
    '!': [
        BooleanType,
        [BooleanType],
        (ctx, [b]) => !b.evaluate(ctx)
    ],
    'is-supported-script': [
        BooleanType,
        [StringType],
        // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant
        (ctx, [s]) => {
            const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;
            if (isSupportedScript) {
                return isSupportedScript(s.evaluate(ctx));
            }
            return true;
        }
    ],
    'upcase': [
        StringType,
        [StringType],
        (ctx, [s]) => s.evaluate(ctx).toUpperCase()
    ],
    'downcase': [
        StringType,
        [StringType],
        (ctx, [s]) => s.evaluate(ctx).toLowerCase()
    ],
    'concat': [
        StringType,
        varargs(ValueType),
        (ctx, args) => args.map(arg => toString(arg.evaluate(ctx))).join('')
    ],
    'resolved-locale': [
        StringType,
        [CollatorType],
        (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()
    ],
    'random': [
        NumberType,
        [
            NumberType,
            NumberType,
            ValueType
        ],
        (ctx, args) => {
            const [min, max, seed] = args.map(arg => arg.evaluate(ctx));
            if (min > max) {
                return min;
            }
            if (min === max) {
                return min;
            }
            let seedVal;
            if (typeof seed === 'string') {
                seedVal = hashString(seed);
            } else if (typeof seed === 'number') {
                seedVal = seed;
            } else {
                throw new RuntimeError$1(`Invalid seed input: ${ seed }`);
            }
            const random = mulberry32(seedVal)();
            return min + random * (max - min);
        }
    ]
});
var expressions$1 = expressions;

//      
/**
 * A type used for returning and propagating errors. The first element of the union
 * represents success and contains a value, and the second represents an error and
 * contains an error value.
 * @private
 */
function success(value) {
    return {
        result: 'success',
        value
    };
}
function error(value) {
    return {
        result: 'error',
        value
    };
}

//      
function expressionHasParameter(expression, parameter) {
    return !!expression && !!expression.parameters && expression.parameters.indexOf(parameter) > -1;
}
function supportsPropertyExpression(spec) {
    return spec['property-type'] === 'data-driven';
}
function supportsLightExpression(spec) {
    return expressionHasParameter(spec.expression, 'measure-light');
}
function supportsZoomExpression(spec) {
    return expressionHasParameter(spec.expression, 'zoom');
}
function supportsInterpolation(spec) {
    return !!spec.expression && spec.expression.interpolated;
}

function isFunction(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function identityFunction(x) {
    return x;
}
function createFunction(parameters, propertySpec) {
    const isColor = propertySpec.type === 'color';
    const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object';
    const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;
    const zoomDependent = zoomAndFeatureDependent || !featureDependent;
    const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval');
    if (isColor) {
        parameters = extend({}, parameters);
        if (parameters.stops) {
            parameters.stops = parameters.stops.map(stop => {
                return [
                    stop[0],
                    Color$1.parse(stop[1])
                ];
            });
        }
        if (parameters.default) {
            parameters.default = Color$1.parse(parameters.default);
        } else {
            parameters.default = Color$1.parse(propertySpec.default);
        }
    }
    if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) {
        // eslint-disable-line import/namespace
        throw new Error(`Unknown color space: ${ parameters.colorSpace }`);
    }
    let innerFun;
    let hashedStops;
    let categoricalKeyType;
    if (type === 'exponential') {
        innerFun = evaluateExponentialFunction;
    } else if (type === 'interval') {
        innerFun = evaluateIntervalFunction;
    } else if (type === 'categorical') {
        innerFun = evaluateCategoricalFunction;
        // For categorical functions, generate an Object as a hashmap of the stops for fast searching
        hashedStops = Object.create(null);
        for (const stop of parameters.stops) {
            hashedStops[stop[0]] = stop[1];
        }
        // Infer key type based on first stop key-- used to encforce strict type checking later
        categoricalKeyType = typeof parameters.stops[0][0];
    } else if (type === 'identity') {
        innerFun = evaluateIdentityFunction;
    } else {
        throw new Error(`Unknown function type "${ type }"`);
    }
    if (zoomAndFeatureDependent) {
        const featureFunctions = {};
        const zoomStops = [];
        for (let s = 0; s < parameters.stops.length; s++) {
            const stop = parameters.stops[s];
            const zoom = stop[0].zoom;
            if (featureFunctions[zoom] === undefined) {
                featureFunctions[zoom] = {
                    zoom,
                    type: parameters.type,
                    property: parameters.property,
                    default: parameters.default,
                    stops: []
                };
                zoomStops.push(zoom);
            }
            featureFunctions[zoom].stops.push([
                stop[0].value,
                stop[1]
            ]);
        }
        const featureFunctionStops = [];
        for (const z of zoomStops) {
            featureFunctionStops.push([
                featureFunctions[z].zoom,
                createFunction(featureFunctions[z], propertySpec)
            ]);
        }
        const interpolationType = { name: 'linear' };
        return {
            kind: 'composite',
            interpolationType,
            interpolationFactor: Interpolate$1.interpolationFactor.bind(undefined, interpolationType),
            zoomStops: featureFunctionStops.map(s => s[0]),
            evaluate({zoom}, properties) {
                return evaluateExponentialFunction({
                    stops: featureFunctionStops,
                    base: parameters.base
                }, propertySpec, zoom).evaluate(zoom, properties);
            }
        };
    } else if (zoomDependent) {
        const interpolationType = type === 'exponential' ? {
            name: 'exponential',
            base: parameters.base !== undefined ? parameters.base : 1
        } : null;
        return {
            kind: 'camera',
            interpolationType,
            interpolationFactor: Interpolate$1.interpolationFactor.bind(undefined, interpolationType),
            zoomStops: parameters.stops.map(s => s[0]),
            evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType)
        };
    } else {
        return {
            kind: 'source',
            evaluate(_, feature) {
                const value = feature && feature.properties ? feature.properties[parameters.property] : undefined;
                if (value === undefined) {
                    return coalesce(parameters.default, propertySpec.default);
                }
                return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);
            }
        };
    }
}
function coalesce(a, b, c) {
    if (a !== undefined)
        return a;
    if (b !== undefined)
        return b;
    if (c !== undefined)
        return c;
}
function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {
    const evaluated = typeof input === keyType ? hashedStops[input] : undefined;
    // Enforce strict typing on input
    return coalesce(evaluated, parameters.default, propertySpec.default);
}
function evaluateIntervalFunction(parameters, propertySpec, input) {
    // Edge cases
    if (getType$1(input) !== 'number')
        return coalesce(parameters.default, propertySpec.default);
    const n = parameters.stops.length;
    if (n === 1)
        return parameters.stops[0][1];
    if (input <= parameters.stops[0][0])
        return parameters.stops[0][1];
    if (input >= parameters.stops[n - 1][0])
        return parameters.stops[n - 1][1];
    const index = findStopLessThanOrEqualTo(parameters.stops.map(stop => stop[0]), input);
    return parameters.stops[index][1];
}
function evaluateExponentialFunction(parameters, propertySpec, input) {
    const base = parameters.base !== undefined ? parameters.base : 1;
    // Edge cases
    if (getType$1(input) !== 'number')
        return coalesce(parameters.default, propertySpec.default);
    const n = parameters.stops.length;
    if (n === 1)
        return parameters.stops[0][1];
    if (input <= parameters.stops[0][0])
        return parameters.stops[0][1];
    if (input >= parameters.stops[n - 1][0])
        return parameters.stops[n - 1][1];
    const index = findStopLessThanOrEqualTo(parameters.stops.map(stop => stop[0]), input);
    const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]);
    const outputLower = parameters.stops[index][1];
    const outputUpper = parameters.stops[index + 1][1];
    let interp = interpolate[propertySpec.type] || identityFunction;
    // eslint-disable-line import/namespace
    if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {
        const colorspace = colorSpaces[parameters.colorSpace];
        // eslint-disable-line import/namespace
        interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));
    }
    if (typeof outputLower.evaluate === 'function') {
        return {
            evaluate(...args) {
                const evaluatedLower = outputLower.evaluate.apply(undefined, args);
                const evaluatedUpper = outputUpper.evaluate.apply(undefined, args);
                // Special case for fill-outline-color, which has no spec default.
                if (evaluatedLower === undefined || evaluatedUpper === undefined) {
                    return undefined;
                }
                return interp(evaluatedLower, evaluatedUpper, t);
            }
        };
    }
    return interp(outputLower, outputUpper, t);
}
function evaluateIdentityFunction(parameters, propertySpec, input) {
    if (propertySpec.type === 'color') {
        input = Color$1.parse(input);
    } else if (propertySpec.type === 'formatted') {
        input = Formatted.fromString(input.toString());
    } else if (propertySpec.type === 'resolvedImage') {
        input = ResolvedImage.fromString(input.toString());
    } else if (getType$1(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {
        input = undefined;
    }
    return coalesce(input, parameters.default, propertySpec.default);
}
/**
 * Returns a ratio that can be used to interpolate between exponential function
 * stops.
 *
 * 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,
 * and `a` and `b` are constants affording sufficient degrees of freedom to fit
 * the function to the given stops.
 *
 * Here's a bit of algebra that lets us compute `f(x)` directly from the stop
 * values without explicitly solving for `a` and `b`:
 *
 * First stop value: `f(x0) = y0 = a * base^x0 + b`
 * Second stop value: `f(x1) = y1 = a * base^x1 + b`
 * => `y1 - y0 = a(base^x1 - base^x0)`
 * => `a = (y1 - y0)/(base^x1 - base^x0)`
 *
 * Desired value: `f(x) = y = a * base^x + b`
 * => `f(x) = y0 + a * (base^x - base^x0)`
 *
 * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a
 * little algebra:
 * ```
 * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)
 *                     = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)
 * ```
 *
 * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have
 * `f(x) = y0 + (y1 - y0) * ratio`.  In other words, `ratio` may be treated as
 * an interpolation factor between the two stops' output values.
 *
 * (Note: a slightly different form for `ratio`,
 * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer
 * expensive `Math.pow()` operations.)
 *
 * @private
 */
function interpolationFactor(input, base, lowerValue, upperValue) {
    const difference = upperValue - lowerValue;
    const progress = input - lowerValue;
    if (difference === 0) {
        return 0;
    } else if (base === 1) {
        return progress / difference;
    } else {
        return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);
    }
}

class StyleExpression {
    constructor(expression, propertySpec, options) {
        this.expression = expression;
        this._warningHistory = {};
        this._evaluator = new EvaluationContext$1(options);
        this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;
        this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;
    }
    evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection, featureTileCoord, featureDistanceData) {
        this._evaluator.globals = globals;
        this._evaluator.feature = feature;
        this._evaluator.featureState = featureState;
        this._evaluator.canonical = canonical || null;
        this._evaluator.availableImages = availableImages || null;
        this._evaluator.formattedSection = formattedSection;
        this._evaluator.featureTileCoord = featureTileCoord || null;
        this._evaluator.featureDistanceData = featureDistanceData || null;
        return this.expression.evaluate(this._evaluator);
    }
    evaluate(globals, feature, featureState, canonical, availableImages, formattedSection, featureTileCoord, featureDistanceData) {
        this._evaluator.globals = globals;
        this._evaluator.feature = feature || null;
        this._evaluator.featureState = featureState || null;
        this._evaluator.canonical = canonical || null;
        this._evaluator.availableImages = availableImages || null;
        this._evaluator.formattedSection = formattedSection || null;
        this._evaluator.featureTileCoord = featureTileCoord || null;
        this._evaluator.featureDistanceData = featureDistanceData || null;
        try {
            const val = this.expression.evaluate(this._evaluator);
            // eslint-disable-next-line no-self-compare
            if (val === null || val === undefined || typeof val === 'number' && val !== val) {
                return this._defaultValue;
            }
            if (this._enumValues && !(val in this._enumValues)) {
                throw new RuntimeError$1(`Expected value to be one of ${ Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ') }, but found ${ JSON.stringify(val) } instead.`);
            }
            return val;
        } catch (e) {
            if (!this._warningHistory[e.message]) {
                this._warningHistory[e.message] = true;
                if (typeof console !== 'undefined') {
                    console.warn(e.message);
                }
            }
            return this._defaultValue;
        }
    }
}
function isExpression(expression) {
    return Array.isArray(expression) && expression.length > 0 && typeof expression[0] === 'string' && expression[0] in expressions$1;
}
/**
 * Parse and typecheck the given style spec JSON expression.  If
 * options.defaultValue is provided, then the resulting StyleExpression's
 * `evaluate()` method will handle errors by logging a warning (once per
 * message) and returning the default value.  Otherwise, it will throw
 * evaluation errors.
 *
 * @private
 */
function createExpression(expression, propertySpec, options) {
    const parser = new ParsingContext$1(expressions$1, [], propertySpec ? getExpectedType(propertySpec) : undefined, undefined, undefined, options);
    // For string-valued properties, coerce to string at the top level rather than asserting.
    const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined);
    if (!parsed) {
        return error(parser.errors);
    }
    return success(new StyleExpression(parsed, propertySpec, options));
}
class ZoomConstantExpression {
    constructor(kind, expression, isLightConstant) {
        this.kind = kind;
        this._styleExpression = expression;
        this.isLightConstant = isLightConstant;
        this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression);
        this.isConfigDependent = !isConfigConstant(expression.expression);
    }
    evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
        return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
    evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
        return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
}
class ZoomDependentExpression {
    constructor(kind, expression, zoomStops, interpolationType, isLightConstant) {
        this.kind = kind;
        this.zoomStops = zoomStops;
        this._styleExpression = expression;
        this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression);
        this.isLightConstant = isLightConstant;
        this.isConfigDependent = !isConfigConstant(expression.expression);
        this.interpolationType = interpolationType;
    }
    evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
        return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
    evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
        return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
    interpolationFactor(input, lower, upper) {
        if (this.interpolationType) {
            return Interpolate$1.interpolationFactor(this.interpolationType, input, lower, upper);
        } else {
            return 0;
        }
    }
}
function createPropertyExpression(expression, propertySpec, options) {
    expression = createExpression(expression, propertySpec, options);
    if (expression.result === 'error') {
        return expression;
    }
    const parsed = expression.value.expression;
    const isFeatureConstant$1 = isFeatureConstant(parsed);
    if (!isFeatureConstant$1 && !supportsPropertyExpression(propertySpec)) {
        return error([new ParsingError$1('', 'data expressions not supported')]);
    }
    const isZoomConstant = isGlobalPropertyConstant(parsed, [
        'zoom',
        'pitch',
        'distance-from-center'
    ]);
    if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {
        return error([new ParsingError$1('', 'zoom expressions not supported')]);
    }
    const isLightConstant = isGlobalPropertyConstant(parsed, ['measure-light']);
    if (!isLightConstant && !supportsLightExpression(propertySpec)) {
        return error([new ParsingError$1('', 'measure-light expression not supported')]);
    }
    const canRelaxZoomRestriction = propertySpec.expression && propertySpec.expression.relaxZoomRestriction;
    const zoomCurve = findZoomCurve(parsed);
    if (!zoomCurve && !isZoomConstant && !canRelaxZoomRestriction) {
        return error([new ParsingError$1('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')]);
    } else if (zoomCurve instanceof ParsingError$1) {
        return error([zoomCurve]);
    } else if (zoomCurve instanceof Interpolate$1 && !supportsInterpolation(propertySpec)) {
        return error([new ParsingError$1('', '"interpolate" expressions cannot be used with this property')]);
    }
    if (!zoomCurve) {
        return success(isFeatureConstant$1 ? new ZoomConstantExpression('constant', expression.value, isLightConstant) : new ZoomConstantExpression('source', expression.value, isLightConstant));
    }
    const interpolationType = zoomCurve instanceof Interpolate$1 ? zoomCurve.interpolation : undefined;
    return success(isFeatureConstant$1 ? new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType, isLightConstant) : new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType, isLightConstant));
}
// serialization wrapper for old-style stop functions normalized to the
// expression interface
class StylePropertyFunction {
    constructor(parameters, specification) {
        this._parameters = parameters;
        this._specification = specification;
        extend(this, createFunction(this._parameters, this._specification));
    }
    static deserialize(serialized) {
        return new StylePropertyFunction(serialized._parameters, serialized._specification);
    }
    static serialize(input) {
        return {
            _parameters: input._parameters,
            _specification: input._specification
        };
    }
}
function normalizePropertyExpression(value, specification, options) {
    if (isFunction(value)) {
        return new StylePropertyFunction(value, specification);
    } else if (isExpression(value) || Array.isArray(value) && value.length > 0) {
        const expression = createPropertyExpression(value, specification, options);
        if (expression.result === 'error') {
            // this should have been caught in validation
            throw new Error(expression.value.map(err => `${ err.key }: ${ err.message }`).join(', '));
        }
        return expression.value;
    } else {
        let constant = value;
        if (typeof value === 'string' && specification.type === 'color') {
            constant = Color$1.parse(value);
        }
        return {
            kind: 'constant',
            isConfigDependent: false,
            evaluate: () => constant
        };
    }
}
// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate"
// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or
// "coalesce" expressions.
function findZoomCurve(expression) {
    let result = null;
    if (expression instanceof Let$1) {
        result = findZoomCurve(expression.result);
    } else if (expression instanceof Coalesce$1) {
        for (const arg of expression.args) {
            result = findZoomCurve(arg);
            if (result) {
                break;
            }
        }
    } else if ((expression instanceof Step$1 || expression instanceof Interpolate$1) && expression.input instanceof CompoundExpression$1 && expression.input.name === 'zoom') {
        result = expression;
    }
    if (result instanceof ParsingError$1) {
        return result;
    }
    expression.eachChild(child => {
        const childResult = findZoomCurve(child);
        if (childResult instanceof ParsingError$1) {
            result = childResult;
        } else if (result && childResult && result !== childResult) {
            result = new ParsingError$1('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.');
        }
    });
    return result;
}
function getExpectedType(spec) {
    const types = {
        color: ColorType,
        string: StringType,
        number: NumberType,
        enum: StringType,
        boolean: BooleanType,
        formatted: FormattedType,
        resolvedImage: ResolvedImageType
    };
    if (spec.type === 'array') {
        return array$1(types[spec.value] || ValueType, spec.length);
    }
    return types[spec.type];
}
function getDefaultValue(spec) {
    if (spec.type === 'color' && (isFunction(spec.default) || Array.isArray(spec.default))) {
        // Special case for heatmap-color: it uses the 'default:' to define a
        // default color ramp, but createExpression expects a simple value to fall
        // back to in case of runtime errors
        return new Color$1(0, 0, 0, 0);
    } else if (spec.type === 'color') {
        return Color$1.parse(spec.default) || null;
    } else if (spec.default === undefined) {
        return null;
    } else {
        return spec.default;
    }
}

//      
function validateObject(options) {
    const key = options.key;
    const object = options.value;
    const elementSpecs = options.valueSpec || {};
    const elementValidators = options.objectElementValidators || {};
    const style = options.style;
    const styleSpec = options.styleSpec;
    let errors = [];
    const type = getType$1(object);
    if (type !== 'object') {
        return [new ValidationError(key, object, `object expected, ${ type } found`)];
    }
    for (const objectKey in object) {
        const elementSpecKey = objectKey.split('.')[0];
        // treat 'paint.*' as 'paint'
        const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*'];
        let validateElement;
        if (elementValidators[elementSpecKey]) {
            validateElement = elementValidators[elementSpecKey];
        } else if (elementSpecs[elementSpecKey]) {
            validateElement = validate;
        } else if (elementValidators['*']) {
            validateElement = elementValidators['*'];
        } else if (elementSpecs['*']) {
            validateElement = validate;
        }
        if (!validateElement) {
            errors.push(new ValidationWarning(key, object[objectKey], `unknown property "${ objectKey }"`));
            continue;
        }
        errors = errors.concat(validateElement({
            key: (key ? `${ key }.` : key) + objectKey,
            value: object[objectKey],
            valueSpec: elementSpec,
            style,
            styleSpec,
            object,
            objectKey    // $FlowFixMe[extra-arg]
        }, object));
    }
    for (const elementSpecKey in elementSpecs) {
        // Don't check `required` when there's a custom validator for that property.
        if (elementValidators[elementSpecKey]) {
            continue;
        }
        if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) {
            errors.push(new ValidationError(key, object, `missing required property "${ elementSpecKey }"`));
        }
    }
    return errors;
}

//      
function validateImport(options) {
    const {value, styleSpec} = options;
    const {data, ...importSpec} = value;
    // Preserve __line__ from the value
    Object.defineProperty(importSpec, '__line__', {
        value: value.__line__,
        enumerable: false
    });
    let errors = validateObject(extend({}, options, {
        value: importSpec,
        valueSpec: styleSpec.import
    }));
    // Empty string is reserved for the root style id
    if (unbundle(importSpec.id) === '') {
        const key = `${ options.key }.id`;
        errors.push(new ValidationError(key, importSpec, `import id can't be an empty string`));
    }
    if (data) {
        const key = `${ options.key }.data`;
        errors = errors.concat(validateStyle$1(data, styleSpec, { key }));
    }
    return errors;
}

//      
function validateArray(options) {
    const array = options.value;
    const arraySpec = options.valueSpec;
    const style = options.style;
    const styleSpec = options.styleSpec;
    const key = options.key;
    const validateArrayElement = options.arrayElementValidator || validate;
    if (getType$1(array) !== 'array') {
        return [new ValidationError(key, array, `array expected, ${ getType$1(array) } found`)];
    }
    if (arraySpec.length && array.length !== arraySpec.length) {
        return [new ValidationError(key, array, `array length ${ arraySpec.length } expected, length ${ array.length } found`)];
    }
    if (arraySpec['min-length'] && array.length < arraySpec['min-length']) {
        return [new ValidationError(key, array, `array length at least ${ arraySpec['min-length'] } expected, length ${ array.length } found`)];
    }
    let arrayElementSpec = {
        'type': arraySpec.value,
        'values': arraySpec.values,
        'minimum': arraySpec.minimum,
        'maximum': arraySpec.maximum,
        function: undefined
    };
    if (styleSpec.$version < 7) {
        arrayElementSpec.function = arraySpec.function;
    }
    if (getType$1(arraySpec.value) === 'object') {
        arrayElementSpec = arraySpec.value;
    }
    let errors = [];
    for (let i = 0; i < array.length; i++) {
        errors = errors.concat(validateArrayElement({
            array,
            arrayIndex: i,
            value: array[i],
            valueSpec: arrayElementSpec,
            style,
            styleSpec,
            key: `${ key }[${ i }]`
        }, true));
    }
    return errors;
}

//      
function validateNumber(options) {
    const key = options.key;
    const value = options.value;
    const valueSpec = options.valueSpec;
    let type = getType$1(value);
    // eslint-disable-next-line no-self-compare
    if (type === 'number' && value !== value) {
        type = 'NaN';
    }
    if (type !== 'number') {
        return [new ValidationError(key, value, `number expected, ${ type } found`)];
    }
    if ('minimum' in valueSpec) {
        let specMin = valueSpec.minimum;
        if (getType$1(valueSpec.minimum) === 'array') {
            const i = options.arrayIndex;
            specMin = valueSpec.minimum[i];
        }
        if (value < specMin) {
            return [new ValidationError(key, value, `${ value } is less than the minimum value ${ specMin }`)];
        }
    }
    if ('maximum' in valueSpec) {
        let specMax = valueSpec.maximum;
        if (getType$1(valueSpec.maximum) === 'array') {
            const i = options.arrayIndex;
            specMax = valueSpec.maximum[i];
        }
        if (value > specMax) {
            return [new ValidationError(key, value, `${ value } is greater than the maximum value ${ specMax }`)];
        }
    }
    return [];
}

//      
function validateFunction(options) {
    const functionValueSpec = options.valueSpec;
    const functionType = unbundle(options.value.type);
    let stopKeyType;
    let stopDomainValues = {};
    let previousStopDomainValue;
    let previousStopDomainZoom;
    const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined;
    const isPropertyFunction = !isZoomFunction;
    const isZoomAndPropertyFunction = getType$1(options.value.stops) === 'array' && getType$1(options.value.stops[0]) === 'array' && getType$1(options.value.stops[0][0]) === 'object';
    const errors = validateObject({
        key: options.key,
        value: options.value,
        valueSpec: options.styleSpec.function,
        style: options.style,
        styleSpec: options.styleSpec,
        objectElementValidators: {
            stops: validateFunctionStops,
            default: validateFunctionDefault
        }
    });
    if (functionType === 'identity' && isZoomFunction) {
        errors.push(new ValidationError(options.key, options.value, 'missing required property "property"'));
    }
    if (functionType !== 'identity' && !options.value.stops) {
        errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"'));
    }
    if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) {
        errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported'));
    }
    if (options.styleSpec.$version >= 8) {
        if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) {
            errors.push(new ValidationError(options.key, options.value, 'property functions not supported'));
        } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {
            errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported'));
        }
    }
    if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) {
        errors.push(new ValidationError(options.key, options.value, '"property" property is required'));
    }
    return errors;
    function validateFunctionStops(options) {
        if (functionType === 'identity') {
            return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')];
        }
        let errors = [];
        const value = options.value;
        errors = errors.concat(validateArray({
            key: options.key,
            value,
            valueSpec: options.valueSpec,
            style: options.style,
            styleSpec: options.styleSpec,
            arrayElementValidator: validateFunctionStop
        }));
        if (getType$1(value) === 'array' && value.length === 0) {
            errors.push(new ValidationError(options.key, value, 'array must have at least one stop'));
        }
        return errors;
    }
    function validateFunctionStop(options) {
        let errors = [];
        const value = options.value;
        const key = options.key;
        if (getType$1(value) !== 'array') {
            return [new ValidationError(key, value, `array expected, ${ getType$1(value) } found`)];
        }
        if (value.length !== 2) {
            return [new ValidationError(key, value, `array length 2 expected, length ${ value.length } found`)];
        }
        if (isZoomAndPropertyFunction) {
            if (getType$1(value[0]) !== 'object') {
                return [new ValidationError(key, value, `object expected, ${ getType$1(value[0]) } found`)];
            }
            if (value[0].zoom === undefined) {
                return [new ValidationError(key, value, 'object stop key must have zoom')];
            }
            if (value[0].value === undefined) {
                return [new ValidationError(key, value, 'object stop key must have value')];
            }
            const nextStopDomainZoom = unbundle(value[0].zoom);
            if (typeof nextStopDomainZoom !== 'number') {
                return [new ValidationError(key, value[0].zoom, 'stop zoom values must be numbers')];
            }
            if (previousStopDomainZoom && previousStopDomainZoom > nextStopDomainZoom) {
                return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')];
            }
            if (nextStopDomainZoom !== previousStopDomainZoom) {
                previousStopDomainZoom = nextStopDomainZoom;
                previousStopDomainValue = undefined;
                stopDomainValues = {};
            }
            errors = errors.concat(validateObject({
                key: `${ key }[0]`,
                value: value[0],
                valueSpec: { zoom: {} },
                style: options.style,
                styleSpec: options.styleSpec,
                objectElementValidators: {
                    zoom: validateNumber,
                    value: validateStopDomainValue
                }
            }));
        } else {
            errors = errors.concat(validateStopDomainValue({
                key: `${ key }[0]`,
                value: value[0],
                valueSpec: {},
                style: options.style,
                styleSpec: options.styleSpec
            }, value));
        }
        if (isExpression(deepUnbundle(value[1]))) {
            return errors.concat([new ValidationError(`${ key }[1]`, value[1], 'expressions are not allowed in function stops.')]);
        }
        return errors.concat(validate({
            key: `${ key }[1]`,
            value: value[1],
            valueSpec: functionValueSpec,
            style: options.style,
            styleSpec: options.styleSpec
        }));
    }
    function validateStopDomainValue(options, stop) {
        const type = getType$1(options.value);
        const value = unbundle(options.value);
        const reportValue = options.value !== null ? options.value : stop;
        if (!stopKeyType) {
            stopKeyType = type;
        } else if (type !== stopKeyType) {
            return [new ValidationError(options.key, reportValue, `${ type } stop domain type must match previous stop domain type ${ stopKeyType }`)];
        }
        if (type !== 'number' && type !== 'string' && type !== 'boolean' && typeof value !== 'number' && typeof value !== 'string' && typeof value !== 'boolean') {
            return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')];
        }
        if (type !== 'number' && functionType !== 'categorical') {
            let message = `number expected, ${ type } found`;
            if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) {
                message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.';
            }
            return [new ValidationError(options.key, reportValue, message)];
        }
        if (functionType === 'categorical' && type === 'number' && (typeof value !== 'number' || !isFinite(value) || Math.floor(value) !== value)) {
            return [new ValidationError(options.key, reportValue, `integer expected, found ${ String(value) }`)];
        }
        if (functionType !== 'categorical' && type === 'number' && typeof value === 'number' && typeof previousStopDomainValue === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) {
            return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')];
        } else {
            previousStopDomainValue = value;
        }
        if (functionType === 'categorical' && value in stopDomainValues) {
            return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];
        } else {
            stopDomainValues[value] = true;
        }
        return [];
    }
    function validateFunctionDefault(options) {
        return validate({
            key: options.key,
            value: options.value,
            valueSpec: functionValueSpec,
            style: options.style,
            styleSpec: options.styleSpec
        });
    }
}

//      
function validateExpression(options) {
    const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);
    if (expression.result === 'error') {
        return expression.value.map(error => {
            return new ValidationError(`${ options.key }${ error.key }`, options.value, error.message);
        });
    }
    const expressionObj = expression.value.expression || expression.value._styleExpression.expression;
    if (options.expressionContext === 'property' && options.propertyKey === 'text-font' && !expressionObj.outputDefined()) {
        return [new ValidationError(options.key, options.value, `Invalid data expression for "${ options.propertyKey }". Output values must be contained as literals within the expression.`)];
    }
    if (options.expressionContext === 'property' && options.propertyType === 'layout' && !isStateConstant(expressionObj)) {
        return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')];
    }
    if (options.expressionContext === 'filter') {
        return disallowedFilterParameters(expressionObj, options);
    }
    if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) {
        if (!isGlobalPropertyConstant(expressionObj, [
                'zoom',
                'feature-state'
            ])) {
            return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')];
        }
        if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) {
            return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')];
        }
    }
    return [];
}
function disallowedFilterParameters(e, options) {
    const disallowedParameters = new Set([
        'zoom',
        'feature-state',
        'pitch',
        'distance-from-center'
    ]);
    if (options.valueSpec && options.valueSpec.expression) {
        for (const param of options.valueSpec.expression.parameters) {
            disallowedParameters.delete(param);
        }
    }
    if (disallowedParameters.size === 0) {
        return [];
    }
    const errors = [];
    if (e instanceof CompoundExpression$1) {
        if (disallowedParameters.has(e.name)) {
            return [new ValidationError(options.key, options.value, `["${ e.name }"] expression is not supported in a filter for a ${ options.object.type } layer with id: ${ options.object.id }`)];
        }
    }
    e.eachChild(arg => {
        errors.push(...disallowedFilterParameters(arg, options));
    });
    return errors;
}

//      
function validateBoolean(options) {
    const value = options.value;
    const key = options.key;
    const type = getType$1(value);
    if (type !== 'boolean') {
        return [new ValidationError(key, value, `boolean expected, ${ type } found`)];
    }
    return [];
}

//      
function validateColor(options) {
    const key = options.key;
    const value = options.value;
    const type = getType$1(value);
    if (type !== 'string') {
        return [new ValidationError(key, value, `color expected, ${ type } found`)];
    }
    if (parseCSSColor_1(value) === null) {
        return [new ValidationError(key, value, `color expected, "${ value }" found`)];
    }
    return [];
}

//      
function validateEnum(options) {
    const key = options.key;
    const value = options.value;
    const valueSpec = options.valueSpec;
    const errors = [];
    if (Array.isArray(valueSpec.values)) {
        // <=v7
        if (valueSpec.values.indexOf(unbundle(value)) === -1) {
            errors.push(new ValidationError(key, value, `expected one of [${ valueSpec.values.join(', ') }], ${ JSON.stringify(value) } found`));
        }
    } else {
        // >=v8
        if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) {
            errors.push(new ValidationError(key, value, `expected one of [${ Object.keys(valueSpec.values).join(', ') }], ${ JSON.stringify(value) } found`));
        }
    }
    return errors;
}

//      
function isExpressionFilter(filter) {
    if (filter === true || filter === false) {
        return true;
    }
    if (!Array.isArray(filter) || filter.length === 0) {
        return false;
    }
    switch (filter[0]) {
    case 'has':
        return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';
    case 'in':
        return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2]));
    case '!in':
    case '!has':
    case 'none':
        return false;
    case '==':
    case '!=':
    case '>':
    case '>=':
    case '<':
    case '<=':
        return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2]));
    case 'any':
    case 'all':
        for (const f of filter.slice(1)) {
            if (!isExpressionFilter(f) && typeof f !== 'boolean') {
                return false;
            }
        }
        return true;
    default:
        return true;
    }
}
/**
 * Given a filter expressed as nested arrays, return a new function
 * that evaluates whether a given feature (with a .properties or .tags property)
 * passes its test.
 *
 * @private
 * @param {Array} filter mapbox gl filter
 * @param {string} layerType the type of the layer this filter will be applied to.
 * @returns {Function} filter-evaluating function
 */
function createFilter(filter, layerType = 'fill') {
    if (filter === null || filter === undefined) {
        return {
            filter: () => true,
            needGeometry: false,
            needFeature: false
        };
    }
    if (!isExpressionFilter(filter)) {
        // $FlowFixMe[incompatible-call]
        filter = convertFilter(filter);
    }
    const filterExp = filter;
    let staticFilter = true;
    try {
        staticFilter = extractStaticFilter(filterExp);
    } catch (e) {
        console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate.
This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md
and paste the contents of this message in the report.
Thank you!
Filter Expression:
${ JSON.stringify(filterExp, null, 2) }
        `);
    }
    // Compile the static component of the filter
    const filterSpec = spec[`filter_${ layerType }`];
    const compiledStaticFilter = createExpression(staticFilter, filterSpec);
    let filterFunc = null;
    if (compiledStaticFilter.result === 'error') {
        throw new Error(compiledStaticFilter.value.map(err => `${ err.key }: ${ err.message }`).join(', '));
    } else {
        filterFunc = (globalProperties, feature, canonical) => compiledStaticFilter.value.evaluate(globalProperties, feature, {}, canonical);
    }
    // If the static component is not equal to the entire filter then we have a dynamic component
    // Compile the dynamic component separately
    let dynamicFilterFunc = null;
    let needFeature = null;
    if (staticFilter !== filterExp) {
        const compiledDynamicFilter = createExpression(filterExp, filterSpec);
        if (compiledDynamicFilter.result === 'error') {
            throw new Error(compiledDynamicFilter.value.map(err => `${ err.key }: ${ err.message }`).join(', '));
        } else {
            dynamicFilterFunc = (globalProperties, feature, canonical, featureTileCoord, featureDistanceData) => compiledDynamicFilter.value.evaluate(globalProperties, feature, {}, canonical, undefined, undefined, featureTileCoord, featureDistanceData);
            needFeature = !isFeatureConstant(compiledDynamicFilter.value.expression);
        }
    }
    filterFunc = filterFunc;
    const needGeometry = geometryNeeded(staticFilter);
    return {
        filter: filterFunc,
        dynamicFilter: dynamicFilterFunc ? dynamicFilterFunc : undefined,
        needGeometry,
        needFeature: !!needFeature
    };
}
function extractStaticFilter(filter) {
    if (!isDynamicFilter(filter)) {
        return filter;
    }
    // Shallow copy so we can replace expressions in-place
    let result = deepUnbundle(filter);
    // 1. Union branches
    unionDynamicBranches(result);
    // 2. Collapse dynamic conditions to  `true`
    result = collapseDynamicBooleanExpressions(result);
    return result;
}
function collapseDynamicBooleanExpressions(expression) {
    if (!Array.isArray(expression)) {
        return expression;
    }
    const collapsed = collapsedExpression(expression);
    if (collapsed === true) {
        return collapsed;
    } else {
        return collapsed.map(subExpression => collapseDynamicBooleanExpressions(subExpression));
    }
}
/**
 * Traverses the expression and replaces all instances of branching on a
 * `dynamic` conditional (such as `['pitch']` or `['distance-from-center']`)
 * into an `any` expression.
 * This ensures that all possible outcomes of a `dynamic` branch are considered
 * when evaluating the expression upfront during filtering.
 *
 * @param {Array<any>} filter the filter expression mutated in-place.
 */
function unionDynamicBranches(filter) {
    let isBranchingDynamically = false;
    const branches = [];
    if (filter[0] === 'case') {
        for (let i = 1; i < filter.length - 1; i += 2) {
            isBranchingDynamically = isBranchingDynamically || isDynamicFilter(filter[i]);
            branches.push(filter[i + 1]);
        }
        branches.push(filter[filter.length - 1]);
    } else if (filter[0] === 'match') {
        isBranchingDynamically = isBranchingDynamically || isDynamicFilter(filter[1]);
        for (let i = 2; i < filter.length - 1; i += 2) {
            branches.push(filter[i + 1]);
        }
        branches.push(filter[filter.length - 1]);
    } else if (filter[0] === 'step') {
        isBranchingDynamically = isBranchingDynamically || isDynamicFilter(filter[1]);
        for (let i = 1; i < filter.length - 1; i += 2) {
            branches.push(filter[i + 1]);
        }
    }
    if (isBranchingDynamically) {
        filter.length = 0;
        filter.push('any', ...branches);
    }
    // traverse and recurse into children
    for (let i = 1; i < filter.length; i++) {
        unionDynamicBranches(filter[i]);
    }
}
function isDynamicFilter(filter) {
    // Base Cases
    if (!Array.isArray(filter)) {
        return false;
    }
    if (isRootExpressionDynamic(filter[0])) {
        return true;
    }
    for (let i = 1; i < filter.length; i++) {
        const child = filter[i];
        if (isDynamicFilter(child)) {
            return true;
        }
    }
    return false;
}
function isRootExpressionDynamic(expression) {
    return expression === 'pitch' || expression === 'distance-from-center';
}
const dynamicConditionExpressions = new Set([
    'in',
    '==',
    '!=',
    '>',
    '>=',
    '<',
    '<=',
    'to-boolean'
]);
function collapsedExpression(expression) {
    if (dynamicConditionExpressions.has(expression[0])) {
        for (let i = 1; i < expression.length; i++) {
            const param = expression[i];
            if (isDynamicFilter(param)) {
                return true;
            }
        }
    }
    return expression;
}
// Comparison function to sort numbers and strings
function compare(a, b) {
    return a < b ? -1 : a > b ? 1 : 0;
}
function geometryNeeded(filter) {
    if (!Array.isArray(filter))
        return false;
    if (filter[0] === 'within' || filter[0] === 'distance')
        return true;
    for (let index = 1; index < filter.length; index++) {
        if (geometryNeeded(filter[index]))
            return true;
    }
    return false;
}
function convertFilter(filter) {
    if (!filter)
        return true;
    const op = filter[0];
    if (filter.length <= 1)
        return op !== 'any';
    const converted = op === '==' ? convertComparisonOp(filter[1], filter[2], '==') : op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) : op === '<' || op === '>' || op === '<=' || op === '>=' ? convertComparisonOp(filter[1], filter[2], op) : op === 'any' ? convertDisjunctionOp(filter.slice(1)) : op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) : op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) : op === 'in' ? convertInOp(filter[1], filter.slice(2)) : op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) : op === 'has' ? convertHasOp(filter[1]) : op === '!has' ? convertNegation(convertHasOp(filter[1])) : true;
    return converted;
}
function convertComparisonOp(property, value, op) {
    switch (property) {
    case '$type':
        return [
            `filter-type-${ op }`,
            value
        ];
    case '$id':
        return [
            `filter-id-${ op }`,
            value
        ];
    default:
        return [
            `filter-${ op }`,
            property,
            value
        ];
    }
}
function convertDisjunctionOp(filters) {
    return ['any'].concat(filters.map(convertFilter));
}
function convertInOp(property, values) {
    if (values.length === 0) {
        return false;
    }
    switch (property) {
    case '$type':
        return [
            `filter-type-in`,
            [
                'literal',
                values
            ]
        ];
    case '$id':
        return [
            `filter-id-in`,
            [
                'literal',
                values
            ]
        ];
    default:
        if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {
            return [
                'filter-in-large',
                property,
                [
                    'literal',
                    values.sort(compare)
                ]
            ];
        } else {
            return [
                'filter-in-small',
                property,
                [
                    'literal',
                    values
                ]
            ];
        }
    }
}
function convertHasOp(property) {
    switch (property) {
    case '$type':
        return true;
    case '$id':
        return [`filter-has-id`];
    default:
        return [
            `filter-has`,
            property
        ];
    }
}
function convertNegation(filter) {
    return [
        '!',
        filter
    ];
}

//      
function validateFilter$1(options) {
    if (isExpressionFilter(deepUnbundle(options.value))) {
        // We default to a layerType of `fill` because that points to a non-dynamic filter definition within the style-spec.
        const layerType = options.layerType || 'fill';
        return validateExpression(extend({}, options, {
            expressionContext: 'filter',
            valueSpec: options.styleSpec[`filter_${ layerType }`]
        }));
    } else {
        return validateNonExpressionFilter(options);
    }
}
function validateNonExpressionFilter(options) {
    const value = options.value;
    const key = options.key;
    if (getType$1(value) !== 'array') {
        return [new ValidationError(key, value, `array expected, ${ getType$1(value) } found`)];
    }
    const styleSpec = options.styleSpec;
    let type;
    let errors = [];
    if (value.length < 1) {
        return [new ValidationError(key, value, 'filter array must have at least 1 element')];
    }
    errors = errors.concat(validateEnum({
        key: `${ key }[0]`,
        value: value[0],
        valueSpec: styleSpec.filter_operator,
        style: options.style,
        styleSpec: options.styleSpec
    }));
    switch (unbundle(value[0])) {
    case '<':
    case '<=':
    case '>':
    case '>=':
        if (value.length >= 2 && unbundle(value[1]) === '$type') {
            errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${ value[0] }"`));
        }
    /* falls through */
    case '==':
    case '!=':
        if (value.length !== 3) {
            errors.push(new ValidationError(key, value, `filter array for operator "${ value[0] }" must have 3 elements`));
        }
    /* falls through */
    case 'in':
    case '!in':
        if (value.length >= 2) {
            type = getType$1(value[1]);
            if (type !== 'string') {
                errors.push(new ValidationError(`${ key }[1]`, value[1], `string expected, ${ type } found`));
            }
        }
        for (let i = 2; i < value.length; i++) {
            type = getType$1(value[i]);
            if (unbundle(value[1]) === '$type') {
                errors = errors.concat(validateEnum({
                    key: `${ key }[${ i }]`,
                    value: value[i],
                    valueSpec: styleSpec.geometry_type,
                    style: options.style,
                    styleSpec: options.styleSpec
                }));
            } else if (type !== 'string' && type !== 'number' && type !== 'boolean') {
                errors.push(new ValidationError(`${ key }[${ i }]`, value[i], `string, number, or boolean expected, ${ type } found`));
            }
        }
        break;
    case 'any':
    case 'all':
    case 'none':
        for (let i = 1; i < value.length; i++) {
            errors = errors.concat(validateNonExpressionFilter({
                key: `${ key }[${ i }]`,
                value: value[i],
                style: options.style,
                styleSpec: options.styleSpec
            }));
        }
        break;
    case 'has':
    case '!has':
        type = getType$1(value[1]);
        if (value.length !== 2) {
            errors.push(new ValidationError(key, value, `filter array for "${ value[0] }" operator must have 2 elements`));
        } else if (type !== 'string') {
            errors.push(new ValidationError(`${ key }[1]`, value[1], `string expected, ${ type } found`));
        }
        break;
    }
    return errors;
}

//      
function validateProperty(options, propertyType) {
    const key = options.key;
    const style = options.style;
    const layer = options.layer;
    const styleSpec = options.styleSpec;
    const value = options.value;
    const propertyKey = options.objectKey;
    const layerSpec = styleSpec[`${ propertyType }_${ options.layerType }`];
    if (!layerSpec)
        return [];
    const transitionMatch = propertyKey.match(/^(.*)-transition$/);
    if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {
        return validate({
            key,
            value,
            valueSpec: styleSpec.transition,
            style,
            styleSpec
        });
    }
    const valueSpec = options.valueSpec || layerSpec[propertyKey];
    if (!valueSpec) {
        return [new ValidationWarning(key, value, `unknown property "${ propertyKey }"`)];
    }
    let tokenMatch;
    if (getType$1(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {
        const example = `\`{ "type": "identity", "property": ${ tokenMatch ? JSON.stringify(tokenMatch[1]) : '"_"' } }\``;
        return [new ValidationError(key, value, `"${ propertyKey }" does not support interpolation syntax\n` + `Use an identity property function instead: ${ example }.`)];
    }
    const errors = [];
    if (options.layerType === 'symbol') {
        if (propertyKey === 'text-field' && style && !style.glyphs && !style.imports) {
            errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property'));
        }
        if (propertyKey === 'text-font' && isFunction(deepUnbundle(value)) && unbundle(value.type) === 'identity') {
            errors.push(new ValidationError(key, value, '"text-font" does not support identity functions'));
        }
    } else if (options.layerType === 'model' && propertyType === 'paint' && layer && layer.layout && layer.layout.hasOwnProperty('model-id')) {
        if (supportsPropertyExpression(valueSpec) && (supportsLightExpression(valueSpec) || supportsZoomExpression(valueSpec))) {
            // Performance related style spec limitation: zoom and light expressions are not allowed for e.g. trees.
            const expression = createPropertyExpression(deepUnbundle(value), valueSpec);
            const expressionObj = expression.value.expression || expression.value._styleExpression.expression;
            if (expressionObj && !isGlobalPropertyConstant(expressionObj, ['measure-light'])) {
                errors.push(new ValidationError(key, value, `${ propertyKey } does not support measure-light expressions when the model layer source is vector tile or GeoJSON.`));
            }
        }
    }
    return errors.concat(validate({
        key: options.key,
        value,
        valueSpec,
        style,
        styleSpec,
        expressionContext: 'property',
        propertyType,
        propertyKey
    }));
}

//      
function validatePaintProperty$1(options) {
    return validateProperty(options, 'paint');
}

//      
function validateLayoutProperty$1(options) {
    return validateProperty(options, 'layout');
}

//      
function validateLayer$1(options) {
    let errors = [];
    const layer = options.value;
    const key = options.key;
    const style = options.style;
    const styleSpec = options.styleSpec;
    if (!layer.type && !layer.ref) {
        errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required'));
    }
    let type = unbundle(layer.type);
    const ref = unbundle(layer.ref);
    if (layer.id) {
        const layerId = unbundle(layer.id);
        for (let i = 0; i < options.arrayIndex; i++) {
            const otherLayer = style.layers[i];
            if (unbundle(otherLayer.id) === layerId) {
                // $FlowFixMe[prop-missing] - id.__line__ is added dynamically during the readStyle step
                errors.push(new ValidationError(key, layer.id, `duplicate layer id "${ layer.id }", previously used at line ${ otherLayer.id.__line__ }`));
            }
        }
    }
    if ('ref' in layer) {
        [
            'type',
            'source',
            'source-layer',
            'filter',
            'layout'
        ].forEach(p => {
            if (p in layer) {
                errors.push(new ValidationError(key, layer[p], `"${ p }" is prohibited for ref layers`));
            }
        });
        let parent;
        style.layers.forEach(layer => {
            if (unbundle(layer.id) === ref)
                parent = layer;
        });
        if (!parent) {
            if (typeof ref === 'string')
                errors.push(new ValidationError(key, layer.ref, `ref layer "${ ref }" not found`));    // $FlowFixMe[prop-missing] - ref is not defined on the LayerSpecification subtypes
        } else if (parent.ref) {
            errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer'));
        } else {
            type = unbundle(parent.type);
        }
    } else if (!(type === 'background' || type === 'sky' || type === 'slot')) {
        if (!layer.source) {
            errors.push(new ValidationError(key, layer, 'missing required property "source"'));
        } else {
            const source = style.sources && style.sources[layer.source];
            const sourceType = source && unbundle(source.type);
            if (!source) {
                errors.push(new ValidationError(key, layer.source, `source "${ layer.source }" not found`));
            } else if (sourceType === 'vector' && type === 'raster') {
                errors.push(new ValidationError(key, layer.source, `layer "${ layer.id }" requires a raster source`));
            } else if (sourceType === 'raster' && type !== 'raster') {
                errors.push(new ValidationError(key, layer.source, `layer "${ layer.id }" requires a vector source`));
            } else if (sourceType === 'vector' && !layer['source-layer']) {
                errors.push(new ValidationError(key, layer, `layer "${ layer.id }" must specify a "source-layer"`));
            } else if (sourceType === 'raster-dem' && type !== 'hillshade') {
                errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.'));
            } else if (type === 'line' && layer.paint && (layer.paint['line-gradient'] || layer.paint['line-trim-offset']) && (sourceType !== 'geojson' || !source.lineMetrics)) {
                errors.push(new ValidationError(key, layer, `layer "${ layer.id }" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`));
            }
        }
    }
    errors = errors.concat(validateObject({
        key,
        value: layer,
        valueSpec: styleSpec.layer,
        style: options.style,
        styleSpec: options.styleSpec,
        objectElementValidators: {
            '*'() {
                return [];
            },
            // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs;
            // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772.
            type() {
                return validate({
                    key: `${ key }.type`,
                    value: layer.type,
                    valueSpec: styleSpec.layer.type,
                    style: options.style,
                    styleSpec: options.styleSpec,
                    object: layer,
                    objectKey: 'type'
                });
            },
            filter(options) {
                return validateFilter$1(extend({ layerType: type }, options));
            },
            layout(options) {
                return validateObject({
                    layer,
                    key: options.key,
                    value: options.value,
                    valueSpec: {},
                    style: options.style,
                    styleSpec: options.styleSpec,
                    objectElementValidators: {
                        '*'(options) {
                            return validateLayoutProperty$1(extend({ layerType: type }, options));
                        }
                    }
                });
            },
            paint(options) {
                return validateObject({
                    layer,
                    key: options.key,
                    value: options.value,
                    valueSpec: {},
                    style: options.style,
                    styleSpec: options.styleSpec,
                    objectElementValidators: {
                        '*'(options) {
                            return validatePaintProperty$1(extend({
                                layerType: type,
                                layer
                            }, options));
                        }
                    }
                });
            }
        }
    }));
    return errors;
}

//      
function validateString(options) {
    const value = options.value;
    const key = options.key;
    const type = getType$1(value);
    if (type !== 'string') {
        return [new ValidationError(key, value, `string expected, ${ type } found`)];
    }
    return [];
}

//      
const objectElementValidators = { promoteId: validatePromoteId };
function validateSource$1(options) {
    const value = options.value;
    const key = options.key;
    const styleSpec = options.styleSpec;
    const style = options.style;
    if (!value.type) {
        return [new ValidationError(key, value, '"type" is required')];
    }
    const type = unbundle(value.type);
    let errors;
    switch (type) {
    case 'vector':
    case 'raster':
    case 'raster-dem':
        errors = validateObject({
            key,
            value,
            valueSpec: styleSpec[`source_${ type.replace('-', '_') }`],
            style: options.style,
            styleSpec,
            objectElementValidators
        });
        return errors;
    case 'geojson':
        errors = validateObject({
            key,
            value,
            valueSpec: styleSpec.source_geojson,
            style,
            styleSpec,
            objectElementValidators
        });
        if (value.cluster) {
            for (const prop in value.clusterProperties) {
                const [operator, mapExpr] = value.clusterProperties[prop];
                const reduceExpr = typeof operator === 'string' ? [
                    operator,
                    ['accumulated'],
                    [
                        'get',
                        prop
                    ]
                ] : operator;
                errors.push(...validateExpression({
                    key: `${ key }.${ prop }.map`,
                    value: mapExpr,
                    expressionContext: 'cluster-map'
                }));
                errors.push(...validateExpression({
                    key: `${ key }.${ prop }.reduce`,
                    value: reduceExpr,
                    expressionContext: 'cluster-reduce'
                }));
            }
        }
        return errors;
    case 'video':
        return validateObject({
            key,
            value,
            valueSpec: styleSpec.source_video,
            style,
            styleSpec
        });
    case 'image':
        return validateObject({
            key,
            value,
            valueSpec: styleSpec.source_image,
            style,
            styleSpec
        });
    case 'canvas':
        return [new ValidationError(key, null, `Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`, 'source.canvas')];
    default:
        return validateEnum({
            key: `${ key }.type`,
            value: value.type,
            valueSpec: { values: getSourceTypeValues(styleSpec) },
            style,
            styleSpec
        });
    }
}
function getSourceTypeValues(styleSpec) {
    return styleSpec.source.reduce((memo, source) => {
        const sourceType = styleSpec[source];
        if (sourceType.type.type === 'enum') {
            memo = memo.concat(Object.keys(sourceType.type.values));
        }
        return memo;
    }, []);
}
function validatePromoteId({key, value}) {
    if (getType$1(value) === 'string') {
        return validateString({
            key,
            value
        });
    } else {
        const errors = [];
        for (const prop in value) {
            errors.push(...validateString({
                key: `${ key }.${ prop }`,
                value: value[prop]
            }));
        }
        return errors;
    }
}

//      
// Allow any URL, use dummy base, if it's a relative URL
function isValidUrl(str) {
    const isRelative = str.indexOf('://') === -1;
    try {
        new URL(str, isRelative ? 'http://example.com' : undefined);
        return true;
    } catch (_) {
        return false;
    }
}
function validateModel$1(options) {
    const url = options.value;
    let errors = [];
    if (!url) {
        return errors;
    }
    const type = getType$1(url);
    if (type !== 'string') {
        errors = errors.concat([new ValidationError(options.key, url, `string expected, "${ type }" found`)]);
        return errors;
    }
    if (!isValidUrl(url)) {
        errors = errors.concat([new ValidationError(options.key, url, `invalid url "${ url }"`)]);
    }
    return errors;
}

//      
function validateLight$1(options) {
    const light = options.value;
    const styleSpec = options.styleSpec;
    const lightSpec = styleSpec.light;
    const style = options.style;
    let errors = [];
    const rootType = getType$1(light);
    if (light === undefined) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new ValidationError('light', light, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in light) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {
            errors = errors.concat(validate({
                key,
                value: light[key],
                valueSpec: styleSpec.transition,
                style,
                styleSpec
            }));
        } else if (lightSpec[key]) {
            errors = errors.concat(validate({
                key,
                value: light[key],
                valueSpec: lightSpec[key],
                style,
                styleSpec
            }));
        } else {
            errors = errors.concat([new ValidationError(key, light[key], `unknown property "${ key }"`)]);
        }
    }
    return errors;
}

//      
function validateLights$1(options) {
    const light = options.value;
    let errors = [];
    if (!light) {
        return errors;
    }
    const type = getType$1(light);
    if (type !== 'object') {
        errors = errors.concat([new ValidationError('light-3d', light, `object expected, ${ type } found`)]);
        return errors;
    }
    const styleSpec = options.styleSpec;
    const lightSpec = styleSpec['light-3d'];
    const key = options.key;
    const style = options.style;
    const lights = options.style.lights;
    for (const key of [
            'type',
            'id'
        ]) {
        if (!(key in light)) {
            errors = errors.concat([new ValidationError('light-3d', light, `missing property ${ key } on light`)]);
            return errors;
        }
    }
    if (light.type && lights) {
        for (let i = 0; i < options.arrayIndex; i++) {
            const lightType = unbundle(light.type);
            const otherLight = lights[i];
            if (unbundle(otherLight.type) === lightType) {
                // $FlowFixMe[prop-missing] - id.__line__ is added dynamically during the readStyle step
                errors.push(new ValidationError(key, light.id, `duplicate light type "${ light.type }", previously defined at line ${ otherLight.id.__line__ }`));
            }
        }
    }
    const lightType = `properties_light_${ light['type'] }`;
    if (!(lightType in styleSpec)) {
        errors = errors.concat([new ValidationError('light-3d', light, `Invalid light type ${ light['type'] }`)]);
        return errors;
    }
    const lightPropertySpec = styleSpec[lightType];
    for (const key in light) {
        if (key === 'properties') {
            const properties = light[key];
            const propertiesType = getType$1(properties);
            if (propertiesType !== 'object') {
                errors = errors.concat([new ValidationError('properties', properties, `object expected, ${ propertiesType } found`)]);
                return errors;
            }
            for (const propertyKey in properties) {
                if (!lightPropertySpec[propertyKey]) {
                    errors = errors.concat([new ValidationWarning(options.key, properties[propertyKey], `unknown property "${ propertyKey }"`)]);
                } else {
                    errors = errors.concat(validate({
                        key: propertyKey,
                        value: properties[propertyKey],
                        valueSpec: lightPropertySpec[propertyKey],
                        style,
                        styleSpec
                    }));
                }
            }
        } else {
            const transitionMatch = key.match(/^(.*)-transition$/);
            if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {
                errors = errors.concat(validate({
                    key,
                    value: light[key],
                    valueSpec: styleSpec.transition,
                    style,
                    styleSpec
                }));
            } else if (lightSpec[key]) {
                errors = errors.concat(validate({
                    key,
                    value: light[key],
                    valueSpec: lightSpec[key],
                    style,
                    styleSpec
                }));
            } else {
                errors = errors.concat([new ValidationWarning(key, light[key], `unknown property "${ key }"`)]);
            }
        }
    }
    return errors;
}

//      
function validateTerrain$1(options) {
    const terrain = options.value;
    const key = options.key;
    const style = options.style;
    const styleSpec = options.styleSpec;
    const terrainSpec = styleSpec.terrain;
    let errors = [];
    const rootType = getType$1(terrain);
    if (terrain === undefined) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in terrain) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        if (transitionMatch && terrainSpec[transitionMatch[1]] && terrainSpec[transitionMatch[1]].transition) {
            errors = errors.concat(validate({
                key,
                value: terrain[key],
                valueSpec: styleSpec.transition,
                style,
                styleSpec
            }));
        } else if (terrainSpec[key]) {
            errors = errors.concat(validate({
                key,
                value: terrain[key],
                valueSpec: terrainSpec[key],
                style,
                styleSpec
            }));
        } else {
            errors = errors.concat([new ValidationWarning(key, terrain[key], `unknown property "${ key }"`)]);
        }
    }
    if (!terrain.source) {
        errors.push(new ValidationError(key, terrain, `terrain is missing required property "source"`));
    } else {
        const source = style.sources && style.sources[terrain.source];
        const sourceType = source && unbundle(source.type);
        if (!source) {
            errors.push(new ValidationError(key, terrain.source, `source "${ terrain.source }" not found`));
        } else if (sourceType !== 'raster-dem') {
            errors.push(new ValidationError(key, terrain.source, `terrain cannot be used with a source of type ${ String(sourceType) }, it only be used with a "raster-dem" source type`));
        }
    }
    return errors;
}

//      
function validateFog$1(options) {
    const fog = options.value;
    const style = options.style;
    const styleSpec = options.styleSpec;
    const fogSpec = styleSpec.fog;
    let errors = [];
    const rootType = getType$1(fog);
    if (fog === undefined) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new ValidationError('fog', fog, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in fog) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        if (transitionMatch && fogSpec[transitionMatch[1]] && fogSpec[transitionMatch[1]].transition) {
            errors = errors.concat(validate({
                key,
                value: fog[key],
                valueSpec: styleSpec.transition,
                style,
                styleSpec
            }));
        } else if (fogSpec[key]) {
            errors = errors.concat(validate({
                key,
                value: fog[key],
                valueSpec: fogSpec[key],
                style,
                styleSpec
            }));
        } else {
            errors = errors.concat([new ValidationWarning(key, fog[key], `unknown property "${ key }"`)]);
        }
    }
    return errors;
}

//      
function validateFormatted(options) {
    if (validateString(options).length === 0) {
        return [];
    }
    return validateExpression(options);
}

//      
function validateImage(options) {
    if (validateString(options).length === 0) {
        return [];
    }
    return validateExpression(options);
}

//      
function validateProjection(options) {
    const projection = options.value;
    const styleSpec = options.styleSpec;
    const projectionSpec = styleSpec.projection;
    const style = options.style;
    let errors = [];
    const rootType = getType$1(projection);
    if (rootType === 'object') {
        for (const key in projection) {
            errors = errors.concat(validate({
                key,
                value: projection[key],
                valueSpec: projectionSpec[key],
                style,
                styleSpec
            }));
        }
    } else if (rootType !== 'string') {
        errors = errors.concat([new ValidationError('projection', projection, `object or string expected, ${ rootType } found`)]);
    }
    return errors;
}

//      
const VALIDATORS = {
    '*'() {
        return [];
    },
    'array': validateArray,
    'boolean': validateBoolean,
    'number': validateNumber,
    'color': validateColor,
    'enum': validateEnum,
    'filter': validateFilter$1,
    'function': validateFunction,
    'layer': validateLayer$1,
    'object': validateObject,
    'source': validateSource$1,
    'model': validateModel$1,
    'light': validateLight$1,
    'light-3d': validateLights$1,
    'terrain': validateTerrain$1,
    'fog': validateFog$1,
    'string': validateString,
    'formatted': validateFormatted,
    'resolvedImage': validateImage,
    'projection': validateProjection,
    'import': validateImport
};
// Main recursive validation function. Tracks:
//
// - key: string representing location of validation in style tree. Used only
//   for more informative error reporting.
// - value: current value from style being evaluated. May be anything from a
//   high level object that needs to be descended into deeper or a simple
//   scalar value.
// - valueSpec: current spec being evaluated. Tracks value.
// - styleSpec: current full spec being evaluated.
function validate(options, arrayAsExpression = false) {
    const value = options.value;
    const valueSpec = options.valueSpec;
    const styleSpec = options.styleSpec;
    if (valueSpec.expression && isFunction(unbundle(value))) {
        return validateFunction(options);
    } else if (valueSpec.expression && isExpression(deepUnbundle(value))) {
        return validateExpression(options);
    } else if (valueSpec.type && VALIDATORS[valueSpec.type]) {
        const valid = VALIDATORS[valueSpec.type](options);
        if (arrayAsExpression === true && valid.length > 0 && getType$1(options.value) === 'array') {
            // Try to validate as an expression
            return validateExpression(options);
        } else {
            return valid;
        }
    } else {
        const valid = validateObject(extend({}, options, { valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec }));
        return valid;
    }
}

//      
function validateGlyphsURL (options) {
    const value = options.value;
    const key = options.key;
    const errors = validateString(options);
    if (errors.length)
        return errors;
    if (value.indexOf('{fontstack}') === -1) {
        errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token'));
    }
    if (value.indexOf('{range}') === -1) {
        errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token'));
    }
    return errors;
}

//      
function validateStyle$1(style, styleSpec = spec, options = {}) {
    const errors = validate({
        key: options.key || '',
        value: style,
        valueSpec: styleSpec.$root,
        styleSpec,
        style,
        objectElementValidators: {
            glyphs: validateGlyphsURL,
            '*': () => []
        }
    });
    return errors;
}

//      
/**
 * Validate a Mapbox GL style against the style specification. This entrypoint,
 * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as
 * small a browserify bundle as possible by omitting unnecessary functionality
 * and legacy style specifications.
 *
 * @private
 * @param {Object} style The style to be validated.
 * @param {Object} [styleSpec] The style specification to validate against.
 *     If omitted, the latest style spec is used.
 * @returns {Array<ValidationError>}
 * @example
 *   var validate = require('mapbox-gl-style-spec/lib/validate_style.min');
 *   var errors = validate(style);
 */
function validateStyle(style, styleSpec = spec) {
    const errors = validateStyle$1(style, styleSpec);
    return sortErrors(errors);
}
const validateSource = opts => sortErrors(validateSource$1(opts));
const validateLight = opts => sortErrors(validateLight$1(opts));
const validateLights = opts => sortErrors(validateLights$1(opts));
const validateTerrain = opts => sortErrors(validateTerrain$1(opts));
const validateFog = opts => sortErrors(validateFog$1(opts));
const validateLayer = opts => sortErrors(validateLayer$1(opts));
const validateFilter = opts => sortErrors(validateFilter$1(opts));
const validatePaintProperty = opts => sortErrors(validatePaintProperty$1(opts));
const validateLayoutProperty = opts => sortErrors(validateLayoutProperty$1(opts));
const validateModel = opts => sortErrors(validateModel$1(opts));
function sortErrors(errors) {
    return errors.slice().sort((a, b) => a.line && b.line ? a.line - b.line : 0);
}

//      
function emitValidationErrors$1(emitter, errors) {
    let hasErrors = false;
    if (errors && errors.length) {
        for (const error of errors) {
            // do not fail rendering when seeing unknown properties, just skip them
            if (error instanceof ValidationWarning) {
                warnOnce(error.message);
            } else {
                emitter.fire(new ErrorEvent(new Error(error.message)));
                hasErrors = true;
            }
        }
    }
    return hasErrors;
}

var gridIndex = GridIndex$1;
var NUM_PARAMS = 3;
function GridIndex$1(extent, n, padding) {
    var cells = this.cells = [];
    if (extent instanceof ArrayBuffer) {
        this.arrayBuffer = extent;
        var array = new Int32Array(this.arrayBuffer);
        extent = array[0];
        n = array[1];
        padding = array[2];
        this.d = n + 2 * padding;
        for (var k = 0; k < this.d * this.d; k++) {
            var start = array[NUM_PARAMS + k];
            var end = array[NUM_PARAMS + k + 1];
            cells.push(start === end ? null : array.subarray(start, end));
        }
        var keysOffset = array[NUM_PARAMS + cells.length];
        var bboxesOffset = array[NUM_PARAMS + cells.length + 1];
        this.keys = array.subarray(keysOffset, bboxesOffset);
        this.bboxes = array.subarray(bboxesOffset);
        this.insert = this._insertReadonly;
    } else {
        this.d = n + 2 * padding;
        for (var i = 0; i < this.d * this.d; i++) {
            cells.push([]);
        }
        this.keys = [];
        this.bboxes = [];
    }
    this.n = n;
    this.extent = extent;
    this.padding = padding;
    this.scale = n / extent;
    this.uid = 0;
    var p = padding / n * extent;
    this.min = -p;
    this.max = extent + p;
}
GridIndex$1.prototype.insert = function (key, x1, y1, x2, y2) {
    this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++);
    this.keys.push(key);
    this.bboxes.push(x1);
    this.bboxes.push(y1);
    this.bboxes.push(x2);
    this.bboxes.push(y2);
};
GridIndex$1.prototype._insertReadonly = function () {
    throw 'Cannot insert into a GridIndex created from an ArrayBuffer.';
};
GridIndex$1.prototype._insertCell = function (x1, y1, x2, y2, cellIndex, uid) {
    this.cells[cellIndex].push(uid);
};
GridIndex$1.prototype.query = function (x1, y1, x2, y2, intersectionTest) {
    var min = this.min;
    var max = this.max;
    if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) {
        // We use `Array#slice` because `this.keys` may be a `Int32Array` and
        // some browsers (Safari and IE) do not support `TypedArray#slice`
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility
        return Array.prototype.slice.call(this.keys);
    } else {
        var result = [];
        var seenUids = {};
        this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest);
        return result;
    }
};
GridIndex$1.prototype._queryCell = function (x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) {
    var cell = this.cells[cellIndex];
    if (cell !== null) {
        var keys = this.keys;
        var bboxes = this.bboxes;
        for (var u = 0; u < cell.length; u++) {
            var uid = cell[u];
            if (seenUids[uid] === undefined) {
                var offset = uid * 4;
                if (intersectionTest ? intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : x1 <= bboxes[offset + 2] && y1 <= bboxes[offset + 3] && x2 >= bboxes[offset + 0] && y2 >= bboxes[offset + 1]) {
                    seenUids[uid] = true;
                    result.push(keys[uid]);
                } else {
                    seenUids[uid] = false;
                }
            }
        }
    }
};
GridIndex$1.prototype._forEachCell = function (x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) {
    var cx1 = this._convertToCellCoord(x1);
    var cy1 = this._convertToCellCoord(y1);
    var cx2 = this._convertToCellCoord(x2);
    var cy2 = this._convertToCellCoord(y2);
    for (var x = cx1; x <= cx2; x++) {
        for (var y = cy1; y <= cy2; y++) {
            var cellIndex = this.d * y + x;
            if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1)))
                continue;
            if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest))
                return;
        }
    }
};
GridIndex$1.prototype._convertFromCellCoord = function (x) {
    return (x - this.padding) / this.scale;
};
GridIndex$1.prototype._convertToCellCoord = function (x) {
    return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));
};
GridIndex$1.prototype.toArrayBuffer = function () {
    if (this.arrayBuffer)
        return this.arrayBuffer;
    var cells = this.cells;
    var metadataLength = NUM_PARAMS + this.cells.length + 1 + 1;
    var totalCellLength = 0;
    for (var i = 0; i < this.cells.length; i++) {
        totalCellLength += this.cells[i].length;
    }
    var array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length);
    array[0] = this.extent;
    array[1] = this.n;
    array[2] = this.padding;
    var offset = metadataLength;
    for (var k = 0; k < cells.length; k++) {
        var cell = cells[k];
        array[NUM_PARAMS + k] = offset;
        array.set(cell, offset);
        offset += cell.length;
    }
    array[NUM_PARAMS + cells.length] = offset;
    array.set(this.keys, offset);
    offset += this.keys.length;
    array[NUM_PARAMS + cells.length + 1] = offset;
    array.set(this.bboxes, offset);
    offset += this.bboxes.length;
    return array.buffer;
};

var Grid = /*@__PURE__*/getDefaultExportFromCjs(gridIndex);

const registry = {};
/**
 * Register the given class as serializable.
 *
 * @param options
 * @param options.omit List of properties to omit from serialization (e.g., cached/computed properties)
 *
 * @private
 */
function register(klass, name, options = {}) {
    Object.defineProperty(klass, '_classRegistryKey', {
        value: name,
        writeable: false
    });
    registry[name] = {
        klass,
        omit: options.omit || []
    };
}
register(Object, 'Object');
Grid.serialize = function serialize(grid, transferables) {
    const buffer = grid.toArrayBuffer();
    if (transferables) {
        transferables.add(buffer);
    }
    return { buffer };
};
Grid.deserialize = function deserialize(serialized) {
    return new Grid(serialized.buffer);
};
Object.defineProperty(Grid, 'name', { value: 'Grid' });
register(Grid, 'Grid');
register(Color$1, 'Color');
register(Error, 'Error');
register(AJAXError, 'AJAXError');
register(ResolvedImage, 'ResolvedImage');
register(StylePropertyFunction, 'StylePropertyFunction');
register(StyleExpression, 'StyleExpression', { omit: ['_evaluator'] });
register(ZoomDependentExpression, 'ZoomDependentExpression');
register(ZoomConstantExpression, 'ZoomConstantExpression');
register(CompoundExpression$1, 'CompoundExpression', { omit: ['_evaluate'] });
for (const name in expressions$1) {
    if (!registry[expressions$1[name]._classRegistryKey])
        register(expressions$1[name], `Expression${ name }`);
}
function isArrayBuffer(val) {
    return val && typeof ArrayBuffer !== 'undefined' && (val instanceof ArrayBuffer || val.constructor && val.constructor.name === 'ArrayBuffer');
}
function isImageBitmap(val) {
    return window$1.ImageBitmap && val instanceof window$1.ImageBitmap;
}
/**
 * Serialize the given object for transfer to or from a web worker.
 *
 * For non-builtin types, recursively serialize each property (possibly
 * omitting certain properties - see register()), and package the result along
 * with the constructor's `name` so that the appropriate constructor can be
 * looked up in `deserialize()`.
 *
 * If a `transferables` set is provided, add any transferable objects (i.e.,
 * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed,
 * this should happen in the client code, before using serialize().)
 *
 * @private
 */
function serialize(input, transferables) {
    if (input === null || input === undefined || typeof input === 'boolean' || typeof input === 'number' || typeof input === 'string' || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp) {
        return input;
    }
    if (isArrayBuffer(input) || isImageBitmap(input)) {
        if (transferables) {
            transferables.add(input);
        }
        return input;
    }
    if (ArrayBuffer.isView(input)) {
        const view = input;
        if (transferables) {
            transferables.add(view.buffer);
        }
        return view;
    }
    if (input instanceof window$1.ImageData) {
        if (transferables) {
            transferables.add(input.data.buffer);
        }
        return input;
    }
    if (Array.isArray(input)) {
        const serialized = [];
        for (const item of input) {
            serialized.push(serialize(item, transferables));
        }
        return serialized;
    }
    if (input instanceof Map) {
        const properties = { '$name': 'Map' };
        for (const [key, value] of input.entries()) {
            properties[key] = serialize(value);
        }
        return properties;
    }
    if (typeof input === 'object') {
        const klass = input.constructor;
        const name = klass._classRegistryKey;
        if (!name) {
            throw new Error(`can't serialize object of unregistered class ${ name }`);
        }
        const properties = klass.serialize ? klass.serialize(input, transferables) : {};
        if (!klass.serialize) {
            for (const key in input) {
                // any cast due to https://github.com/facebook/flow/issues/5393
                if (!input.hasOwnProperty(key))
                    continue;
                if (registry[name].omit.indexOf(key) >= 0)
                    continue;
                const property = input[key];
                properties[key] = serialize(property, transferables);
            }
            if (input instanceof Error) {
                properties['message'] = input.message;
            }
        }
        if (properties['$name']) {
            throw new Error('$name property is reserved for worker serialization logic.');
        }
        if (name !== 'Object') {
            properties['$name'] = name;
        }
        return properties;
    }
    throw new Error(`can't serialize object of type ${ typeof input }`);
}
function deserialize$1(input) {
    if (input === null || input === undefined || typeof input === 'boolean' || typeof input === 'number' || typeof input === 'string' || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp || isArrayBuffer(input) || isImageBitmap(input) || ArrayBuffer.isView(input) || input instanceof window$1.ImageData) {
        return input;
    }
    if (Array.isArray(input)) {
        return input.map(deserialize$1);
    }
    if (typeof input === 'object') {
        const name = input.$name || 'Object';
        if (name === 'Map') {
            const map = new Map();
            for (const key of Object.keys(input)) {
                // $FlowFixMe[incompatible-type]
                if (key === '$name')
                    continue;
                const value = input[key];
                map.set(key, deserialize$1(value));
            }
            return map;
        }
        const {klass} = registry[name];
        if (!klass) {
            throw new Error(`can't deserialize unregistered class ${ name }`);
        }
        if (klass.deserialize) {
            return klass.deserialize(input);
        }
        const result = Object.create(klass.prototype);
        for (const key of Object.keys(input)) {
            // $FlowFixMe[incompatible-type]
            if (key === '$name')
                continue;
            const value = input[key];
            result[key] = deserialize$1(value);
        }
        return result;
    }
    throw new Error(`can't deserialize object of type ${ typeof input }`);
}

//      
// The following table comes from <http://www.unicode.org/Public/12.0.0/ucd/Blocks.txt>.
// Keep it synchronized with <http://www.unicode.org/Public/UCD/latest/ucd/Blocks.txt>.
const unicodeBlockLookup = {
    // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F,
    'Latin-1 Supplement': char => char >= 128 && char <= 255,
    // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F,
    // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F,
    // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF,
    // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF,
    // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F,
    // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF,
    // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF,
    // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F,
    // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F,
    //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF,
    'Arabic': char => char >= 1536 && char <= 1791,
    //'Syriac': (char) => char >= 0x0700 && char <= 0x074F,
    'Arabic Supplement': char => char >= 1872 && char <= 1919,
    // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF,
    // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF,
    // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F,
    // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F,
    // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F,
    'Arabic Extended-A': char => char >= 2208 && char <= 2303,
    // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F,
    // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF,
    // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F,
    // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF,
    // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F,
    // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF,
    // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F,
    // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF,
    // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F,
    // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF,
    // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F,
    // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF,
    // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF,
    // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F,
    // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF,
    'Hangul Jamo': char => char >= 4352 && char <= 4607,
    // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F,
    // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F,
    // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF,
    'Unified Canadian Aboriginal Syllabics': char => char >= 5120 && char <= 5759,
    // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F,
    // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF,
    // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F,
    // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F,
    // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F,
    // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F,
    'Khmer': char => char >= 6016 && char <= 6143,
    // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF,
    'Unified Canadian Aboriginal Syllabics Extended': char => char >= 6320 && char <= 6399,
    // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F,
    // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F,
    // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF,
    // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF,
    // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F,
    // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF,
    // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF,
    // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F,
    // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF,
    // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF,
    // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F,
    // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F,
    // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F,
    // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF,
    // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF,
    // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF,
    // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F,
    // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF,
    // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF,
    // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF,
    // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF,
    'General Punctuation': char => char >= 8192 && char <= 8303,
    // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F,
    // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF,
    // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF,
    'Letterlike Symbols': char => char >= 8448 && char <= 8527,
    'Number Forms': char => char >= 8528 && char <= 8591,
    // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF,
    // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF,
    'Miscellaneous Technical': char => char >= 8960 && char <= 9215,
    'Control Pictures': char => char >= 9216 && char <= 9279,
    'Optical Character Recognition': char => char >= 9280 && char <= 9311,
    'Enclosed Alphanumerics': char => char >= 9312 && char <= 9471,
    // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F,
    // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F,
    'Geometric Shapes': char => char >= 9632 && char <= 9727,
    'Miscellaneous Symbols': char => char >= 9728 && char <= 9983,
    // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF,
    // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF,
    // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF,
    // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF,
    // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F,
    // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF,
    // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF,
    'Miscellaneous Symbols and Arrows': char => char >= 11008 && char <= 11263,
    // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F,
    // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F,
    // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF,
    // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F,
    // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F,
    // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF,
    // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF,
    // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F,
    'CJK Radicals Supplement': char => char >= 11904 && char <= 12031,
    'Kangxi Radicals': char => char >= 12032 && char <= 12255,
    'Ideographic Description Characters': char => char >= 12272 && char <= 12287,
    'CJK Symbols and Punctuation': char => char >= 12288 && char <= 12351,
    'Hiragana': char => char >= 12352 && char <= 12447,
    'Katakana': char => char >= 12448 && char <= 12543,
    'Bopomofo': char => char >= 12544 && char <= 12591,
    'Hangul Compatibility Jamo': char => char >= 12592 && char <= 12687,
    'Kanbun': char => char >= 12688 && char <= 12703,
    'Bopomofo Extended': char => char >= 12704 && char <= 12735,
    'CJK Strokes': char => char >= 12736 && char <= 12783,
    'Katakana Phonetic Extensions': char => char >= 12784 && char <= 12799,
    'Enclosed CJK Letters and Months': char => char >= 12800 && char <= 13055,
    'CJK Compatibility': char => char >= 13056 && char <= 13311,
    'CJK Unified Ideographs Extension A': char => char >= 13312 && char <= 19903,
    'Yijing Hexagram Symbols': char => char >= 19904 && char <= 19967,
    'CJK Unified Ideographs': char => char >= 19968 && char <= 40959,
    'Yi Syllables': char => char >= 40960 && char <= 42127,
    'Yi Radicals': char => char >= 42128 && char <= 42191,
    // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF,
    // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F,
    // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F,
    // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF,
    // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F,
    // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF,
    // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F,
    // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F,
    // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F,
    // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF,
    // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF,
    // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F,
    // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F,
    'Hangul Jamo Extended-A': char => char >= 43360 && char <= 43391,
    // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF,
    // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF,
    // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F,
    // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F,
    // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF,
    // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF,
    // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F,
    // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F,
    // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF,
    // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF,
    'Hangul Syllables': char => char >= 44032 && char <= 55215,
    'Hangul Jamo Extended-B': char => char >= 55216 && char <= 55295,
    // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F,
    // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF,
    // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF,
    'Private Use Area': char => char >= 57344 && char <= 63743,
    'CJK Compatibility Ideographs': char => char >= 63744 && char <= 64255,
    // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F,
    'Arabic Presentation Forms-A': char => char >= 64336 && char <= 65023,
    // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F,
    'Vertical Forms': char => char >= 65040 && char <= 65055,
    // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F,
    'CJK Compatibility Forms': char => char >= 65072 && char <= 65103,
    'Small Form Variants': char => char >= 65104 && char <= 65135,
    'Arabic Presentation Forms-B': char => char >= 65136 && char <= 65279,
    'Halfwidth and Fullwidth Forms': char => char >= 65280 && char <= 65519,
    // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF,
    // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F,
    // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF,
    // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F,
    // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F,
    // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF,
    // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF,
    // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F,
    // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF,
    // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF,
    // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F,
    // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F,
    // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F,
    // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F,
    // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF,
    // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F,
    // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F,
    // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF,
    // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF,
    // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F,
    // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F,
    // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F,
    // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F,
    // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F,
    // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F,
    // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF,
    // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF,
    // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F,
    // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F,
    // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F,
    // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF,
    // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F,
    // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F,
    // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F,
    // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF,
    // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F,
    // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F,
    // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F,
    // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF,
    // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F,
    // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF,
    // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F,
    // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F,
    // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F,
    // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F,
    // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF,
    // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F,
    // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF,
    // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF,
    // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F,
    // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F,
    // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF,
    // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF,
    // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F,
    // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF,
    // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF,
    // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F,
    // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F,
    // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF,
    // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF,
    // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F,
    // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F,
    // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF,
    // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F,
    // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F,
    // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF,
    // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF,
    // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F,
    // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF,
    // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF,
    // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F,
    // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF,
    // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F,
    // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF,
    // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF,
    // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF,
    // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF,
    // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F,
    // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F,
    // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F,
    // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F,
    // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F,
    // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F,
    // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F,
    // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF,
    // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F,
    // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F,
    // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F,
    // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF,
    // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF,
    // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF,
    // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF,
    // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F,
    // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F,
    // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF,
    // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F,
    // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF,
    // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF,
    // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF,
    // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F,
    // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF,
    // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F,
    // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F,
    // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF,
    // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF,
    // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F,
    // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F,
    // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF,
    // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF,
    // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F,
    // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF,
    // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F,
    // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF,
    // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F,
    // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F,
    // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF,
    // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF,
    // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF,
    // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF,
    // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F,
    // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F,
    // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF,
    // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F,
    // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF,
    // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF,
    // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF,
    // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F,
    // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF,
    'CJK Unified Ideographs Extension B': char => char >= 131072 && char <= 173791
};

//      
/* eslint-disable new-cap */
function allowsVerticalWritingMode(chars) {
    for (const char of chars) {
        if (charHasUprightVerticalOrientation(char.charCodeAt(0)))
            return true;
    }
    return false;
}
function allowsLetterSpacing(chars) {
    for (const char of chars) {
        if (!charAllowsLetterSpacing(char.charCodeAt(0)))
            return false;
    }
    return true;
}
function charAllowsLetterSpacing(char) {
    if (unicodeBlockLookup['Arabic'](char))
        return false;
    if (unicodeBlockLookup['Arabic Supplement'](char))
        return false;
    if (unicodeBlockLookup['Arabic Extended-A'](char))
        return false;
    if (unicodeBlockLookup['Arabic Presentation Forms-A'](char))
        return false;
    if (unicodeBlockLookup['Arabic Presentation Forms-B'](char))
        return false;
    return true;
}
function charAllowsIdeographicBreaking(char) {
    // Return early for characters outside all ideographic ranges.
    if (char < 11904)
        return false;
    if (unicodeBlockLookup['Bopomofo Extended'](char))
        return true;
    if (unicodeBlockLookup['Bopomofo'](char))
        return true;
    if (unicodeBlockLookup['CJK Compatibility Forms'](char))
        return true;
    if (unicodeBlockLookup['CJK Compatibility Ideographs'](char))
        return true;
    if (unicodeBlockLookup['CJK Compatibility'](char))
        return true;
    if (unicodeBlockLookup['CJK Radicals Supplement'](char))
        return true;
    if (unicodeBlockLookup['CJK Strokes'](char))
        return true;
    if (unicodeBlockLookup['CJK Symbols and Punctuation'](char))
        return true;
    if (unicodeBlockLookup['CJK Unified Ideographs Extension A'](char))
        return true;
    if (unicodeBlockLookup['CJK Unified Ideographs'](char))
        return true;
    if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char))
        return true;
    if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char))
        return true;
    if (unicodeBlockLookup['Hiragana'](char))
        return true;
    if (unicodeBlockLookup['Ideographic Description Characters'](char))
        return true;
    if (unicodeBlockLookup['Kangxi Radicals'](char))
        return true;
    if (unicodeBlockLookup['Katakana Phonetic Extensions'](char))
        return true;
    if (unicodeBlockLookup['Katakana'](char))
        return true;
    if (unicodeBlockLookup['Vertical Forms'](char))
        return true;
    if (unicodeBlockLookup['Yi Radicals'](char))
        return true;
    if (unicodeBlockLookup['Yi Syllables'](char))
        return true;
    return false;
}
// The following logic comes from
// <http://www.unicode.org/Public/12.0.0/ucd/VerticalOrientation.txt>.
// Keep it synchronized with
// <http://www.unicode.org/Public/UCD/latest/ucd/VerticalOrientation.txt>.
// The data file denotes with “U” or “Tu” any codepoint that may be drawn
// upright in vertical text but does not distinguish between upright and
// “neutral” characters.
// Blocks in the Unicode supplementary planes are excluded from this module due
// to <https://github.com/mapbox/mapbox-gl/issues/29>.
/**
 * Returns true if the given Unicode codepoint identifies a character with
 * upright orientation.
 *
 * A character has upright orientation if it is drawn upright (unrotated)
 * whether the line is oriented horizontally or vertically, even if both
 * adjacent characters can be rotated. For example, a Chinese character is
 * always drawn upright. An uprightly oriented character causes an adjacent
 * “neutral” character to be drawn upright as well.
 * @private
 */
function charHasUprightVerticalOrientation(char) {
    if (char === 746    /* modifier letter yin departing tone mark */ || char === 747    /* modifier letter yang departing tone mark */) {
        return true;
    }
    // Return early for characters outside all ranges whose characters remain
    // upright in vertical writing mode.
    if (char < 4352)
        return false;
    if (unicodeBlockLookup['Bopomofo Extended'](char))
        return true;
    if (unicodeBlockLookup['Bopomofo'](char))
        return true;
    if (unicodeBlockLookup['CJK Compatibility Forms'](char)) {
        if (!(char >= 65097    /* dashed overline */ && char <= 65103)) {
            return true;
        }
    }
    if (unicodeBlockLookup['CJK Compatibility Ideographs'](char))
        return true;
    if (unicodeBlockLookup['CJK Compatibility'](char))
        return true;
    if (unicodeBlockLookup['CJK Radicals Supplement'](char))
        return true;
    if (unicodeBlockLookup['CJK Strokes'](char))
        return true;
    if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) {
        if (!(char >= 12296    /* left angle bracket */ && char <= 12305) && !(char >= 12308    /* left tortoise shell bracket */ && char <= 12319) && char !== 12336    /* wavy dash */) {
            return true;
        }
    }
    if (unicodeBlockLookup['CJK Unified Ideographs Extension A'](char))
        return true;
    if (unicodeBlockLookup['CJK Unified Ideographs'](char))
        return true;
    if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char))
        return true;
    if (unicodeBlockLookup['Hangul Compatibility Jamo'](char))
        return true;
    if (unicodeBlockLookup['Hangul Jamo Extended-A'](char))
        return true;
    if (unicodeBlockLookup['Hangul Jamo Extended-B'](char))
        return true;
    if (unicodeBlockLookup['Hangul Jamo'](char))
        return true;
    if (unicodeBlockLookup['Hangul Syllables'](char))
        return true;
    if (unicodeBlockLookup['Hiragana'](char))
        return true;
    if (unicodeBlockLookup['Ideographic Description Characters'](char))
        return true;
    if (unicodeBlockLookup['Kanbun'](char))
        return true;
    if (unicodeBlockLookup['Kangxi Radicals'](char))
        return true;
    if (unicodeBlockLookup['Katakana Phonetic Extensions'](char))
        return true;
    if (unicodeBlockLookup['Katakana'](char)) {
        if (char !== 12540    /* katakana-hiragana prolonged sound mark */) {
            return true;
        }
    }
    if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) {
        if (char !== 65288    /* fullwidth left parenthesis */ && char !== 65289    /* fullwidth right parenthesis */ && char !== 65293    /* fullwidth hyphen-minus */ && !(char >= 65306    /* fullwidth colon */ && char <= 65310) && char !== 65339    /* fullwidth left square bracket */ && char !== 65341    /* fullwidth right square bracket */ && char !== 65343    /* fullwidth low line */ && !(char >= 65371    /* fullwidth left curly bracket */ && char <= 65503) && char !== 65507    /* fullwidth macron */ && !(char >= 65512    /* halfwidth forms light vertical */ && char <= 65519)) {
            return true;
        }
    }
    if (unicodeBlockLookup['Small Form Variants'](char)) {
        if (!(char >= 65112    /* small em dash */ && char <= 65118) && !(char >= 65123    /* small hyphen-minus */ && char <= 65126)) {
            return true;
        }
    }
    if (unicodeBlockLookup['Unified Canadian Aboriginal Syllabics'](char))
        return true;
    if (unicodeBlockLookup['Unified Canadian Aboriginal Syllabics Extended'](char))
        return true;
    if (unicodeBlockLookup['Vertical Forms'](char))
        return true;
    if (unicodeBlockLookup['Yijing Hexagram Symbols'](char))
        return true;
    if (unicodeBlockLookup['Yi Syllables'](char))
        return true;
    if (unicodeBlockLookup['Yi Radicals'](char))
        return true;
    return false;
}
/**
 * Returns true if the given Unicode codepoint identifies a character with
 * neutral orientation.
 *
 * A character has neutral orientation if it may be drawn rotated or unrotated
 * when the line is oriented vertically, depending on the orientation of the
 * adjacent characters. For example, along a verticlly oriented line, the vulgar
 * fraction ½ is drawn upright among Chinese characters but rotated among Latin
 * letters. A neutrally oriented character does not influence whether an
 * adjacent character is drawn upright or rotated.
 * @private
 */
function charHasNeutralVerticalOrientation(char) {
    if (unicodeBlockLookup['Latin-1 Supplement'](char)) {
        if (char === 167    /* section sign */ || char === 169    /* copyright sign */ || char === 174    /* registered sign */ || char === 177    /* plus-minus sign */ || char === 188    /* vulgar fraction one quarter */ || char === 189    /* vulgar fraction one half */ || char === 190    /* vulgar fraction three quarters */ || char === 215    /* multiplication sign */ || char === 247    /* division sign */) {
            return true;
        }
    }
    if (unicodeBlockLookup['General Punctuation'](char)) {
        if (char === 8214    /* double vertical line */ || char === 8224    /* dagger */ || char === 8225    /* double dagger */ || char === 8240    /* per mille sign */ || char === 8241    /* per ten thousand sign */ || char === 8251    /* reference mark */ || char === 8252    /* double exclamation mark */ || char === 8258    /* asterism */ || char === 8263    /* double question mark */ || char === 8264    /* question exclamation mark */ || char === 8265    /* exclamation question mark */ || char === 8273    /* two asterisks aligned vertically */) {
            return true;
        }
    }
    if (unicodeBlockLookup['Letterlike Symbols'](char))
        return true;
    if (unicodeBlockLookup['Number Forms'](char))
        return true;
    if (unicodeBlockLookup['Miscellaneous Technical'](char)) {
        if (char >= 8960    /* diameter sign */ && char <= 8967    /* wavy line */ || char >= 8972    /* bottom right crop */ && char <= 8991    /* bottom right corner */ || char >= 8996    /* up arrowhead between two horizontal bars */ && char <= 9000    /* keyboard */ || char === 9003    /* erase to the left */ || char >= 9085    /* shouldered open box */ && char <= 9114    /* clear screen symbol */ || char >= 9150    /* dentistry symbol light vertical and top right */ && char <= 9165    /* square foot */ || char === 9167    /* eject symbol */ || char >= 9169    /* metrical breve */ && char <= 9179    /* fuse */ || char >= 9186    /* white trapezium */ && char <= 9215) {
            return true;
        }
    }
    if (unicodeBlockLookup['Control Pictures'](char) && char !== 9251    /* open box */)
        return true;
    if (unicodeBlockLookup['Optical Character Recognition'](char))
        return true;
    if (unicodeBlockLookup['Enclosed Alphanumerics'](char))
        return true;
    if (unicodeBlockLookup['Geometric Shapes'](char))
        return true;
    if (unicodeBlockLookup['Miscellaneous Symbols'](char)) {
        if (!(char >= 9754    /* black left pointing index */ && char <= 9759)) {
            return true;
        }
    }
    if (unicodeBlockLookup['Miscellaneous Symbols and Arrows'](char)) {
        if (char >= 11026    /* square with top half black */ && char <= 11055    /* white vertical ellipse */ || char >= 11088    /* white medium star */ && char <= 11097    /* heavy circled saltire */ || char >= 11192    /* upwards white arrow from bar with horizontal bar */ && char <= 11243) {
            return true;
        }
    }
    if (unicodeBlockLookup['CJK Symbols and Punctuation'](char))
        return true;
    if (unicodeBlockLookup['Katakana'](char))
        return true;
    if (unicodeBlockLookup['Private Use Area'](char))
        return true;
    if (unicodeBlockLookup['CJK Compatibility Forms'](char))
        return true;
    if (unicodeBlockLookup['Small Form Variants'](char))
        return true;
    if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char))
        return true;
    if (char === 8734    /* infinity */ || char === 8756    /* therefore */ || char === 8757    /* because */ || char >= 9984    /* black safety scissors */ && char <= 10087    /* rotated floral heart bullet */ || char >= 10102    /* dingbat negative circled digit one */ && char <= 10131    /* dingbat negative circled sans-serif number ten */ || char === 65532    /* object replacement character */ || char === 65533    /* replacement character */) {
        return true;
    }
    return false;
}
/**
 * Returns true if the given Unicode codepoint identifies a character with
 * rotated orientation.
 *
 * A character has rotated orientation if it is drawn rotated when the line is
 * oriented vertically, even if both adjacent characters are upright. For
 * example, a Latin letter is drawn rotated along a vertical line. A rotated
 * character causes an adjacent “neutral” character to be drawn rotated as well.
 * @private
 */
function charHasRotatedVerticalOrientation(char) {
    return !(charHasUprightVerticalOrientation(char) || charHasNeutralVerticalOrientation(char));
}
function charInComplexShapingScript(char) {
    return unicodeBlockLookup['Arabic'](char) || unicodeBlockLookup['Arabic Supplement'](char) || unicodeBlockLookup['Arabic Extended-A'](char) || unicodeBlockLookup['Arabic Presentation Forms-A'](char) || unicodeBlockLookup['Arabic Presentation Forms-B'](char);
}
function charInRTLScript(char) {
    // Main blocks for Hebrew, Arabic, Thaana and other RTL scripts
    return char >= 1424 && char <= 2303 || unicodeBlockLookup['Arabic Presentation Forms-A'](char) || unicodeBlockLookup['Arabic Presentation Forms-B'](char);
}
function charInSupportedScript(char, canRenderRTL) {
    // This is a rough heuristic: whether we "can render" a script
    // actually depends on the properties of the font being used
    // and whether differences from the ideal rendering are considered
    // semantically significant.
    // Even in Latin script, we "can't render" combinations such as the fi
    // ligature, but we don't consider that semantically significant.
    if (!canRenderRTL && charInRTLScript(char)) {
        return false;
    }
    if (char >= 2304 && char <= 3583 || char >= 3840 && char <= 4255 || // Main blocks for Tibetan and Myanmar
        unicodeBlockLookup['Khmer'](char)) {
        // These blocks cover common scripts that require
        // complex text shaping, based on unicode script metadata:
        // http://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt
        // where "Web Rank <= 32" "Shaping Required = YES"
        return false;
    }
    return true;
}
function stringContainsRTLText(chars) {
    for (const char of chars) {
        if (charInRTLScript(char.charCodeAt(0))) {
            return true;
        }
    }
    return false;
}
function isStringInSupportedScript(chars, canRenderRTL) {
    for (const char of chars) {
        if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) {
            return false;
        }
    }
    return true;
}

//      
const status = {
    unavailable: 'unavailable',
    // Not loaded
    deferred: 'deferred',
    // The plugin URL has been specified, but loading has been deferred
    loading: 'loading',
    // request in-flight
    loaded: 'loaded',
    error: 'error'
};
let _completionCallback = null;
//Variables defining the current state of the plugin
let pluginStatus = status.unavailable;
let pluginURL = null;
const triggerPluginCompletionEvent = function (error) {
    // NetworkError's are not correctly reflected by the plugin status which prevents reloading plugin
    if (error && typeof error === 'string' && error.indexOf('NetworkError') > -1) {
        pluginStatus = status.error;
    }
    if (_completionCallback) {
        _completionCallback(error);
    }
};
function sendPluginStateToWorker() {
    evented.fire(new Event('pluginStateChange', {
        pluginStatus,
        pluginURL
    }));
}
const evented = new Evented();
const getRTLTextPluginStatus = function () {
    return pluginStatus;
};
const registerForPluginStateChange = function (callback) {
    // Do an initial sync of the state
    callback({
        pluginStatus,
        pluginURL
    });
    // Listen for all future state changes
    evented.on('pluginStateChange', callback);
    return callback;
};
const setRTLTextPlugin = function (url, callback, deferred = false) {
    if (pluginStatus === status.deferred || pluginStatus === status.loading || pluginStatus === status.loaded) {
        throw new Error('setRTLTextPlugin cannot be called multiple times.');
    }
    pluginURL = exported$1.resolveURL(url);
    pluginStatus = status.deferred;
    _completionCallback = callback;
    sendPluginStateToWorker();
    //Start downloading the plugin immediately if not intending to lazy-load
    if (!deferred) {
        downloadRTLTextPlugin();
    }
};
const downloadRTLTextPlugin = function () {
    if (pluginStatus !== status.deferred || !pluginURL) {
        throw new Error('rtl-text-plugin cannot be downloaded unless a pluginURL is specified');
    }
    pluginStatus = status.loading;
    sendPluginStateToWorker();
    if (pluginURL) {
        getArrayBuffer({ url: pluginURL }, error => {
            if (error) {
                triggerPluginCompletionEvent(error);
            } else {
                pluginStatus = status.loaded;
                sendPluginStateToWorker();
            }
        });
    }
};
const plugin = {
    applyArabicShaping: null,
    processBidirectionalText: null,
    processStyledBidirectionalText: null,
    isLoaded() {
        return pluginStatus === status.loaded || // Main Thread: loaded if the completion callback returned successfully
        plugin.applyArabicShaping != null;    // Web-worker: loaded if the plugin functions have been compiled
    },
    isLoading() {
        // Main Thread Only: query the loading status, this function does not return the correct value in the worker context.
        return pluginStatus === status.loading;
    },
    setState(state) {
        pluginStatus = state.pluginStatus;
        pluginURL = state.pluginURL;
    },
    isParsed() {
        return plugin.applyArabicShaping != null && plugin.processBidirectionalText != null && plugin.processStyledBidirectionalText != null;
    },
    getPluginURL() {
        return pluginURL;
    }
};
const lazyLoadRTLTextPlugin = function () {
    if (!plugin.isLoading() && !plugin.isLoaded() && getRTLTextPluginStatus() === 'deferred') {
        downloadRTLTextPlugin();
    }
};

//      
class EvaluationParameters {
    // "options" may also be another EvaluationParameters to copy
    constructor(zoom, options) {
        this.zoom = zoom;
        if (options) {
            this.now = options.now;
            this.fadeDuration = options.fadeDuration;
            this.transition = options.transition;
            this.pitch = options.pitch;
            this.brightness = options.brightness;
        } else {
            this.now = 0;
            this.fadeDuration = 0;
            this.transition = {};
            this.pitch = 0;
            this.brightness = 0;
        }
    }
    isSupportedScript(str) {
        return isStringInSupportedScript(str, plugin.isLoaded());
    }
}

/**
 * Implements a number of classes that define state and behavior for paint and layout properties, most
 * importantly their respective evaluation chains:
 *
 *       Transitionable paint property value
 *     → Transitioning paint property value
 *     → Possibly evaluated paint property value
 *     → Fully evaluated paint property value
 *
 *       Layout property value
 *     → Possibly evaluated layout property value
 *     → Fully evaluated layout property value
 *
 * @module
 * @private
 */
/**
 *  Implementations of the `Property` interface:
 *
 *  * Hold metadata about a property that's independent of any specific value: stuff like the type of the value,
 *    the default value, etc. This comes from the style specification JSON.
 *  * Define behavior that needs to be polymorphic across different properties: "possibly evaluating"
 *    an input value (see below), and interpolating between two possibly-evaluted values.
 *
 *  The type `T` is the fully-evaluated value type (e.g. `number`, `string`, `Color`).
 *  The type `R` is the intermediate "possibly evaluated" value type. See below.
 *
 *  There are two main implementations of the interface -- one for properties that allow data-driven values,
 *  and one for properties that don't. There are a few "special case" implementations as well:
 *  one for `heatmap-color` and `line-gradient`, and one for `light-position`.
 *
 * @private
 */
/**
 *  `PropertyValue` represents the value part of a property key-value unit. It's used to represent both
 *  paint and layout property values, and regardless of whether or not their property supports data-driven
 *  expressions.
 *
 *  `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the
 *  following:
 *
 *    * A constant value of the type appropriate for the property
 *    * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions)
 *    * An expression which produces a value of that type
 *    * "undefined"/"not present", in which case the property is assumed to take on its default value.
 *
 *  In addition to storing the original input value, `PropertyValue` also stores a normalized representation,
 *  effectively treating functions as if they are expressions, and constant or default values as if they are
 *  (constant) expressions.
 *
 *  @private
 */
class PropertyValue {
    constructor(property, value, options) {
        this.property = property;
        this.value = value;
        this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification, options);
    }
    isDataDriven() {
        return this.expression.kind === 'source' || this.expression.kind === 'composite';
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);
    }
}
// ------- Transitionable -------
/**
 * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between
 * old and new value. The duration of the transition, and the delay before it begins, is configurable.
 *
 * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition
 * configuration.
 *
 * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values:
 * `TransitioningPropertyValue`.
 *
 * @private
 */
class TransitionablePropertyValue {
    constructor(property, options) {
        this.property = property;
        this.value = new PropertyValue(property, undefined, options);
    }
    transitioned(parameters, prior) {
        return new TransitioningPropertyValue(this.property, this.value, prior, // eslint-disable-line no-use-before-define
        extend$1({}, parameters.transition, this.transition), parameters.now);
    }
    untransitioned() {
        return new TransitioningPropertyValue(this.property, this.value, null, {}, 0);    // eslint-disable-line no-use-before-define
    }
}
/**
 * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates
 * an object type with the same keys and values of type `TransitionablePropertyValue<T, R>`.
 *
 * @private
 */
/**
 * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a
 * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a
 * `Transitioning` instance for the same set of properties.
 *
 * @private
 */
class Transitionable {
    constructor(properties, options) {
        this._properties = properties;
        this._values = Object.create(properties.defaultTransitionablePropertyValues);
        this._options = options;
        this.isConfigDependent = false;
    }
    getValue(name) {
        return clone$9(this._values[name].value.value);
    }
    setValue(name, value) {
        if (!this._values.hasOwnProperty(name)) {
            this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._options);
        }
        // Note that we do not _remove_ an own property in the case where a value is being reset
        // to the default: the transition might still be non-default.
        this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value), this._options);
        this.isConfigDependent = this.isConfigDependent || this._values[name].value.expression.isConfigDependent;
    }
    setTransitionOrValue(properties, options) {
        if (options)
            this._options = options;
        const specProperties = this._properties.properties;
        if (properties) {
            for (const name in properties) {
                const value = properties[name];
                if (endsWith(name, '-transition')) {
                    const propName = name.slice(0, -'-transition'.length);
                    if (specProperties[propName]) {
                        this.setTransition(propName, value);
                    }
                } else if (specProperties[name]) {
                    // skip unrecognized properties
                    this.setValue(name, value);
                }
            }
        }
    }
    getTransition(name) {
        return clone$9(this._values[name].transition);
    }
    setTransition(name, value) {
        if (!this._values.hasOwnProperty(name)) {
            this._values[name] = new TransitionablePropertyValue(this._values[name].property);
        }
        this._values[name].transition = clone$9(value) || undefined;
    }
    serialize() {
        const result = {};
        for (const property of Object.keys(this._values)) {
            const value = this.getValue(property);
            if (value !== undefined) {
                result[property] = value;
            }
            const transition = this.getTransition(property);
            if (transition !== undefined) {
                result[`${ property }-transition`] = transition;
            }
        }
        return result;
    }
    transitioned(parameters, prior) {
        const result = new Transitioning(this._properties);
        // eslint-disable-line no-use-before-define
        for (const property of Object.keys(this._values)) {
            result._values[property] = this._values[property].transitioned(parameters, prior._values[property]);
        }
        return result;
    }
    untransitioned() {
        const result = new Transitioning(this._properties);
        // eslint-disable-line no-use-before-define
        for (const property of Object.keys(this._values)) {
            result._values[property] = this._values[property].untransitioned();
        }
        return result;
    }
}
// ------- Transitioning -------
/**
 * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint
 * property value. In this step, transitions between old and new values are handled: as long as the transition is in
 * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and
 * the new value based on the current time and the configured transition duration and delay. The product is the next
 * step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept.
 *
 * @private
 */
class TransitioningPropertyValue {
    constructor(property, value, prior, transition, now) {
        const delay = transition.delay || 0;
        const duration = transition.duration || 0;
        now = now || 0;
        this.property = property;
        this.value = value;
        this.begin = now + delay;
        this.end = this.begin + duration;
        if (property.specification.transition && (transition.delay || transition.duration)) {
            this.prior = prior;
        }
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        const now = parameters.now || 0;
        const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages);
        const prior = this.prior;
        if (!prior) {
            // No prior value.
            return finalValue;
        } else if (now > this.end) {
            // Transition from prior value is now complete.
            this.prior = null;
            return finalValue;
        } else if (this.value.isDataDriven()) {
            // Transitions to data-driven properties are not supported.
            // We snap immediately to the data-driven value so that, when we perform layout,
            // we see the data-driven function and can use it to populate vertex buffers.
            this.prior = null;
            return finalValue;
        } else if (now < this.begin) {
            // Transition hasn't started yet.
            return prior.possiblyEvaluate(parameters, canonical, availableImages);
        } else {
            // Interpolate between recursively-calculated prior value and final.
            const t = (now - this.begin) / (this.end - this.begin);
            return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));
        }
    }
}
/**
 * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates
 * an object type with the same keys and values of type `TransitioningPropertyValue<T, R>`.
 *
 * @private
 */
/**
 * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a
 * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a
 * `PossiblyEvaluated` instance for the same set of properties.
 *
 * @private
 */
class Transitioning {
    constructor(properties) {
        this._properties = properties;
        this._values = Object.create(properties.defaultTransitioningPropertyValues);
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        const result = new PossiblyEvaluated(this._properties);
        // eslint-disable-line no-use-before-define
        for (const property of Object.keys(this._values)) {
            result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);
        }
        return result;
    }
    hasTransition() {
        for (const property of Object.keys(this._values)) {
            if (this._values[property].prior) {
                return true;
            }
        }
        return false;
    }
}
// ------- Layout -------
/**
 * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates
 * an object type with the same keys and values of type `PropertyValue<T, R>`.
 *
 * @private
 */
/**
 * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates
 * an object type with the same keys and values of type `PropertyValueSpecification<T>`.
 *
 * @private
 */
/**
 * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than
 * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then
 * fully evaluated.
 *
 * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a
 * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a
 * `PossiblyEvaluated` instance for the same set of properties.
 *
 * @private
 */
class Layout {
    constructor(properties, options) {
        this._properties = properties;
        this._values = Object.create(properties.defaultPropertyValues);
        this._options = options;
        this.isConfigDependent = false;
    }
    getValue(name) {
        return clone$9(this._values[name].value);
    }
    setValue(name, value) {
        this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value), this._options);
        this.isConfigDependent = this.isConfigDependent || this._values[name].expression.isConfigDependent;
    }
    serialize() {
        const result = {};
        for (const property of Object.keys(this._values)) {
            const value = this.getValue(property);
            if (value !== undefined) {
                result[property] = value;
            }
        }
        return result;
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        const result = new PossiblyEvaluated(this._properties);
        // eslint-disable-line no-use-before-define
        for (const property of Object.keys(this._values)) {
            result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);
        }
        return result;
    }
}
// ------- PossiblyEvaluated -------
/**
 * "Possibly evaluated value" is an intermediate stage in the evaluation chain for both paint and layout property
 * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code
 * which uses data-driven property values must assume that the value is dependent on feature data, and request that it
 * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation
 * will not actually depend on the feature, and we can benefit from returning the prior result of having done the
 * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and "global" parameters
 * such as current zoom level.
 *
 * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or
 * camera expression, then the "possibly evaluated" result is a constant value. Otherwise, the input value was either
 * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate
 * the source and composite cases because they are handled differently when generating GL attributes, buffers, and
 * uniforms.
 *
 * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that
 * do not allow data-driven values. For such properties, we know that the "possibly evaluated" result is always a constant
 * scalar value. See below.
 *
 * @private
 */
/**
 * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a
 * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply
 * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the
 * case where the input value was a constant or camera function.
 *
 * @private
 */
class PossiblyEvaluatedPropertyValue {
    constructor(property, value, parameters) {
        this.property = property;
        this.value = value;
        this.parameters = parameters;
    }
    isConstant() {
        return this.value.kind === 'constant';
    }
    constantOr(value) {
        if (this.value.kind === 'constant') {
            return this.value.value;
        } else {
            return value;
        }
    }
    evaluate(feature, featureState, canonical, availableImages) {
        return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages);
    }
}
/**
 * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates
 * an object type with the same keys, and values of type `R`.
 *
 * For properties that don't allow data-driven values, `R` is a scalar type such as `number`, `string`, or `Color`.
 * For data-driven properties, it is `PossiblyEvaluatedPropertyValue`. Critically, the type definitions are set up
 * in a way that allows flow to know which of these two cases applies for any given property name, and if you attempt
 * to use a `PossiblyEvaluatedPropertyValue` as if it was a scalar, or vice versa, you will get a type error. (However,
 * 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
 * as `layer.paint.get('foo-opacity') === 0`, if `foo-opacity` is data-driven, than the left-hand side is of type
 * `PossiblyEvaluatedPropertyValue<number>`, but flow will not complain about comparing this to a number using `===`.
 * See https://github.com/facebook/flow/issues/2359.)
 *
 * @private
 */
/**
 * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a
 * given layer type.
 * @private
 */
class PossiblyEvaluated {
    constructor(properties) {
        this._properties = properties;
        this._values = Object.create(properties.defaultPossiblyEvaluatedValues);
    }
    get(name) {
        return this._values[name];
    }
}
/**
 * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions.
 * This restriction allows us to declare statically that the result of possibly evaluating this kind of property
 * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis.
 *
 * @private
 */
class DataConstantProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters) {
        // $FlowFixMe[method-unbinding]
        return value.expression.evaluate(parameters);
    }
    interpolate(a, b, t) {
        const interp = interpolate[this.specification.type];
        if (interp) {
            return interp(a, b, t);
        } else {
            return a;
        }
    }
}
/**
 * An implementation of `Property` for properties that permit data-driven (source or composite) expressions.
 * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue<T>`; obtaining
 * a scalar value `T` requires further evaluation on a per-feature basis.
 *
 * @private
 */
class DataDrivenProperty {
    constructor(specification, overrides) {
        this.specification = specification;
        this.overrides = overrides;
    }
    possiblyEvaluate(value, parameters, canonical, availableImages) {
        if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {
            // $FlowFixMe[method-unbinding]
            return new PossiblyEvaluatedPropertyValue(this, {
                kind: 'constant',
                value: value.expression.evaluate(parameters, null, {}, canonical, availableImages)
            }, parameters);
        } else {
            return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);
        }
    }
    interpolate(a, b, t) {
        // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values.
        if (a.value.kind !== 'constant' || b.value.kind !== 'constant') {
            return a;
        }
        // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in
        // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former
        // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the
        // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant
        // undefined value is the "default value" for fill-outline-color held in
        // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of
        // `PossiblyEvaluated#_values`.
        if (a.value.value === undefined || b.value.value === undefined) {
            return new PossiblyEvaluatedPropertyValue(this, {
                kind: 'constant',
                value: undefined
            }, a.parameters);
        }
        const interp = interpolate[this.specification.type];
        if (interp) {
            return new PossiblyEvaluatedPropertyValue(this, {
                kind: 'constant',
                value: interp(a.value.value, b.value.value, t)
            }, a.parameters);
        } else {
            return a;
        }
    }
    evaluate(value, parameters, feature, featureState, canonical, availableImages) {
        if (value.kind === 'constant') {
            return value.value;
        } else {
            // $FlowFixMe[method-unbinding]
            return value.evaluate(parameters, feature, featureState, canonical, availableImages);
        }
    }
}
/**
 * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and
 * evaluation returns a boolean value in order to indicate its presence, but the real
 * evaluation happens in StyleLayer classes.
 *
 * @private
 */
class ColorRampProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters, canonical, availableImages) {
        // $FlowFixMe[method-unbinding]
        return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages);
    }
    interpolate() {
        return false;
    }
}
class DirectionProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters) {
        // $FlowFixMe[method-unbinding]
        return sphericalDirectionToCartesian(value.expression.evaluate(parameters));
    }
    interpolate(a, b, t) {
        return {
            x: number(a.x, b.x, t),
            y: number(a.y, b.y, t),
            z: number(a.z, b.z, t)
        };
    }
}
class PositionProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters) {
        // $FlowFixMe[method-unbinding]
        return sphericalPositionToCartesian(value.expression.evaluate(parameters));
    }
    interpolate(a, b, t) {
        return {
            x: number(a.x, b.x, t),
            y: number(a.y, b.y, t),
            z: number(a.z, b.z, t),
            azimuthal: number(a.azimuthal, b.azimuthal, t),
            polar: number(a.polar, b.polar, t)
        };
    }
}
/**
 * `Properties` holds objects containing default values for the layout or paint property set of a given
 * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of
 * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid
 * doing work in the common case where a property has no explicit value set and should be considered to take
 * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over
 * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final
 * evaluations for defaults, the result of which will always be the same.
 *
 * @private
 */
class Properties {
    constructor(properties) {
        this.properties = properties;
        this.defaultPropertyValues = {};
        this.defaultTransitionablePropertyValues = {};
        this.defaultTransitioningPropertyValues = {};
        this.defaultPossiblyEvaluatedValues = {};
        this.overridableProperties = [];
        const defaultParameters = new EvaluationParameters(0, {});
        for (const property in properties) {
            const prop = properties[property];
            if (prop.specification.overridable) {
                this.overridableProperties.push(property);
            }
            const defaultPropertyValue = this.defaultPropertyValues[property] = new PropertyValue(prop, undefined);
            const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = new TransitionablePropertyValue(prop);
            this.defaultTransitioningPropertyValues[property] = defaultTransitionablePropertyValue.untransitioned();
            this.defaultPossiblyEvaluatedValues[property] = defaultPropertyValue.possiblyEvaluate(defaultParameters);
        }
    }
}
register(DataDrivenProperty, 'DataDrivenProperty');
register(DataConstantProperty, 'DataConstantProperty');
register(ColorRampProperty, 'ColorRampProperty');

//      
const FQIDSeparator = '\x1F';
function isFQID(id) {
    return id.indexOf(FQIDSeparator) >= 0;
}
function makeFQID(id, scope) {
    if (!scope)
        return id;
    return `${ id }${ FQIDSeparator }${ scope }`;
}
function getNameFromFQID(fqid) {
    const sep = fqid.indexOf(FQIDSeparator);
    return sep >= 0 ? fqid.slice(0, sep) : fqid;
}

//      
const TRANSITION_SUFFIX = '-transition';
class StyleLayer extends Evented {
    constructor(layer, properties, options) {
        super();
        this.id = layer.id;
        this.type = layer.type;
        this._featureFilter = {
            filter: () => true,
            needGeometry: false,
            needFeature: false
        };
        this._filterCompiled = false;
        this.isConfigDependent = false;
        if (layer.type === 'custom')
            return;
        layer = layer;
        this.metadata = layer.metadata;
        this.minzoom = layer.minzoom;
        this.maxzoom = layer.maxzoom;
        if (layer.type !== 'background' && layer.type !== 'sky' && layer.type !== 'slot') {
            this.source = layer.source;
            this.sourceLayer = layer['source-layer'];
            this.filter = layer.filter;
        }
        this.options = options;
        if (layer.slot)
            this.slot = layer.slot;
        if (properties.layout) {
            this._unevaluatedLayout = new Layout(properties.layout, options);
            this.isConfigDependent = this.isConfigDependent || this._unevaluatedLayout.isConfigDependent;
        }
        if (properties.paint) {
            this._transitionablePaint = new Transitionable(properties.paint, options);
            for (const property in layer.paint) {
                this.setPaintProperty(property, layer.paint[property], { validate: false });
            }
            for (const property in layer.layout) {
                this.setLayoutProperty(property, layer.layout[property], { validate: false });
            }
            this.isConfigDependent = this.isConfigDependent || this._transitionablePaint.isConfigDependent;
            this._transitioningPaint = this._transitionablePaint.untransitioned();
            //$FlowFixMe
            this.paint = new PossiblyEvaluated(properties.paint);
        }
    }
    /**
     * Sets the scope of the style layer to a particular Style.
     *
     * @private
     */
    setScope(scope) {
        this.scope = scope;
        this.fqid = makeFQID(this.id, scope);
    }
    getLayoutProperty(name) {
        if (name === 'visibility') {
            return this.visibility;
        }
        return this._unevaluatedLayout.getValue(name);
    }
    setLayoutProperty(name, value, options = {}) {
        if (value !== null && value !== undefined) {
            const key = `layers.${ this.id }.layout.${ name }`;
            if (this._validate(validateLayoutProperty, key, name, value, options)) {
                return;
            }
        }
        if (this.type === 'custom' && name === 'visibility') {
            this.visibility = value;
            return;
        }
        const layout = this._unevaluatedLayout;
        const specProps = layout._properties.properties;
        if (!specProps[name])
            return;
        // skip unrecognized properties
        layout.setValue(name, value);
        this.isConfigDependent = this.isConfigDependent || layout.isConfigDependent;
        if (name === 'visibility') {
            this.possiblyEvaluateVisibility();
        }
    }
    possiblyEvaluateVisibility() {
        this.visibility = this._unevaluatedLayout._values.visibility.possiblyEvaluate({ zoom: 0 });
    }
    getPaintProperty(name) {
        if (endsWith(name, TRANSITION_SUFFIX)) {
            return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length));
        } else {
            return this._transitionablePaint.getValue(name);
        }
    }
    setPaintProperty(name, value, options = {}) {
        if (value !== null && value !== undefined) {
            const key = `layers.${ this.id }.paint.${ name }`;
            if (this._validate(validatePaintProperty, key, name, value, options)) {
                return false;
            }
        }
        const paint = this._transitionablePaint;
        const specProps = paint._properties.properties;
        if (endsWith(name, TRANSITION_SUFFIX)) {
            const propName = name.slice(0, -TRANSITION_SUFFIX.length);
            if (specProps[propName]) {
                // skip unrecognized properties
                paint.setTransition(propName, value || undefined);
            }
            return false;
        }
        if (!specProps[name])
            return false;
        // skip unrecognized properties
        const transitionable = paint._values[name];
        const wasDataDriven = transitionable.value.isDataDriven();
        const oldValue = transitionable.value;
        paint.setValue(name, value);
        this.isConfigDependent = this.isConfigDependent || paint.isConfigDependent;
        this._handleSpecialPaintPropertyUpdate(name);
        const newValue = paint._values[name].value;
        const isDataDriven = newValue.isDataDriven();
        const isPattern = endsWith(name, 'pattern') || name === 'line-dasharray';
        // if a pattern value is changed, we need to make sure the new icons get added to each tile's iconAtlas
        // so a call to _updateLayer is necessary, and we return true from this function so it gets called in
        // Style#setPaintProperty
        return isDataDriven || wasDataDriven || isPattern || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue);
    }
    _handleSpecialPaintPropertyUpdate(_) {
    }
    getProgramIds() {
        // No-op; can be overridden by derived classes.
        return null;
    }
    // eslint-disable-next-line no-unused-vars
    getDefaultProgramParams(name, zoom) {
        // No-op; can be overridden by derived classes.
        return null;
    }
    // eslint-disable-next-line no-unused-vars
    _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) {
        // No-op; can be overridden by derived classes.
        return false;
    }
    isHidden(zoom) {
        if (this.minzoom && zoom < this.minzoom)
            return true;
        if (this.maxzoom && zoom >= this.maxzoom)
            return true;
        return this.visibility === 'none';
    }
    updateTransitions(parameters) {
        this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint);
    }
    hasTransition() {
        return this._transitioningPaint.hasTransition();
    }
    recalculate(parameters, availableImages) {
        if (this._unevaluatedLayout) {
            this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages);
        }
        this.paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages);
    }
    serialize() {
        const output = {
            'id': this.id,
            'type': this.type,
            'slot': this.slot,
            'source': this.source,
            'source-layer': this.sourceLayer,
            'metadata': this.metadata,
            'minzoom': this.minzoom,
            'maxzoom': this.maxzoom,
            'filter': this.filter,
            'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(),
            'paint': this._transitionablePaint && this._transitionablePaint.serialize()
        };
        return filterObject(output, (value, key) => {
            return value !== undefined && !(key === 'layout' && !Object.keys(value).length) && !(key === 'paint' && !Object.keys(value).length);
        });
    }
    _validate(validate, key, name, value, options = {}) {
        if (options && options.validate === false) {
            return false;
        }
        return emitValidationErrors$1(this, validate.call(validateStyle, {
            key,
            layerType: this.type,
            objectKey: name,
            value,
            styleSpec: spec,
            // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407
            style: {
                glyphs: true,
                sprite: true
            }
        }));
    }
    is3D() {
        return false;
    }
    isSky() {
        return false;
    }
    isTileClipped() {
        return false;
    }
    hasOffscreenPass() {
        return false;
    }
    hasShadowPass() {
        return false;
    }
    canCastShadows() {
        return false;
    }
    hasLightBeamPass() {
        return false;
    }
    cutoffRange() {
        return 0;
    }
    resize() {
    }
    isStateDependent() {
        for (const property in this.paint._values) {
            const value = this.paint.get(property);
            if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {
                continue;
            }
            if ((value.value.kind === 'source' || value.value.kind === 'composite') && value.value.isStateDependent) {
                return true;
            }
        }
        return false;
    }
    compileFilter() {
        if (!this._filterCompiled) {
            this._featureFilter = createFilter(this.filter);
            this._filterCompiled = true;
        }
    }
    invalidateCompiledFilter() {
        this._filterCompiled = false;
    }
    dynamicFilter() {
        return this._featureFilter.dynamicFilter;
    }
    dynamicFilterNeedsFeature() {
        return this._featureFilter.needFeature;
    }
}

//      
/**
 * Class for tracking style changes by scope, shared between all style instances.
 */
class StyleChanges {
    constructor() {
        this.changed = false;
        this._updatedLayers = {};
        this._removedLayers = {};
        this.updatedSourceCaches = {};
        this.updatedPaintProps = new Set();
        this.changedImages = new Set();
    }
    /**
     * Mark a layer as having changes and needs to be rerendered.
     * @param {StyleLayer} layer
     */
    updateLayer(layer) {
        const scope = layer.scope;
        this._updatedLayers[scope] = this._updatedLayers[scope] || new Set();
        this._updatedLayers[scope].add(layer.id);
    }
    /**
     * Mark a layer as having been removed and needing to be cleaned up.
     * @param {StyleLayer} layer
     */
    removeLayer(layer) {
        const scope = layer.scope;
        this._removedLayers[scope] = this._removedLayers[scope] || {};
        this._updatedLayers[scope] = this._updatedLayers[scope] || new Set();
        this._removedLayers[scope][layer.id] = layer;
        this._updatedLayers[scope].delete(layer.id);
        this.updatedPaintProps.delete(layer.fqid);
    }
    /**
     * Returns StyleLayer if layer needs to be removed.
     * @param {StyleLayer} layer
     */
    getRemovedLayer(layer) {
        if (!this._removedLayers[layer.scope])
            return null;
        return this._removedLayers[layer.scope][layer.id];
    }
    /**
     * Eliminate layer from the list of layers that need to be removed.
     * @param {StyleLayer} layer
     */
    discardLayerRemoval(layer) {
        if (!this._removedLayers[layer.scope])
            return;
        delete this._removedLayers[layer.scope][layer.id];
    }
    /**
     * Returns a list of layer ids that have been updated or removed grouped by the scope.
     * @returns {{[scope: string]: {updatedIds: Array<string>, removedIds: Array<string>}}}}
     */
    getLayerUpdatesByScope() {
        const updatesByScope = {};
        for (const scope in this._updatedLayers) {
            updatesByScope[scope] = updatesByScope[scope] || {};
            updatesByScope[scope].updatedIds = Array.from(this._updatedLayers[scope].values());
        }
        for (const scope in this._removedLayers) {
            updatesByScope[scope] = updatesByScope[scope] || {};
            updatesByScope[scope].removedIds = Object.keys(this._removedLayers[scope]);
        }
        return updatesByScope;
    }
    reset() {
        this.changed = false;
        this._updatedLayers = {};
        this._removedLayers = {};
        this.updatedSourceCaches = {};
        this.updatedPaintProps.clear();
        this.changedImages.clear();
    }
}

const viewTypes = {
    'Int8': Int8Array,
    'Uint8': Uint8Array,
    'Int16': Int16Array,
    'Uint16': Uint16Array,
    'Int32': Int32Array,
    'Uint32': Uint32Array,
    'Float32': Float32Array
};
/**
 * @private
 */
class Struct {
    // When reading the ArrayBuffer as an array of different data types, arrays have different length
    // depending on data type size. So to acess the same position,
    // we need to read different indexes depending on array data size.
    // _pos1 is the index reading an array with 1 byte data,
    // _pos2 is reading 2 byte data, and so forth.
    // The following properties are defined on the prototype of sub classes.
    /**
     * @param {StructArray} structArray The StructArray the struct is stored in
     * @param {number} index The index of the struct in the StructArray.
     * @private
     */
    constructor(structArray, index) {
        this._structArray = structArray;
        this._pos1 = index * this.size;
        this._pos2 = this._pos1 / 2;
        this._pos4 = this._pos1 / 4;
        this._pos8 = this._pos1 / 8;
    }
}
const DEFAULT_CAPACITY = 128;
const RESIZE_MULTIPLIER = 5;
/**
 * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray`
 * making it behave like an array of typed structs.
 *
 * Conceptually, a StructArray is comprised of elements, i.e., instances of its
 * associated struct type. Each particular struct type, together with an
 * alignment size, determines the memory layout of a StructArray whose elements
 * are of that type.  Thus, for each such layout that we need, we have
 * a corrseponding StructArrayLayout class, inheriting from StructArray and
 * implementing `emplaceBack()` and `_refreshViews()`.
 *
 * In some cases, where we need to access particular elements of a StructArray,
 * we implement a more specific subclass that inherits from one of the
 * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured
 * object whose properties are proxies into the underlying memory space for the
 * i-th element.  This affords the convience of working with (seemingly) plain
 * Javascript objects without the overhead of serializing/deserializing them
 * into ArrayBuffers for efficient web worker transfer.
 *
 * @private
 */
class StructArray {
    // The following properties are defined on the prototype.
    constructor() {
        this.isTransferred = false;
        this.capacity = -1;
        this.resize(0);
    }
    /**
     * Serialize a StructArray instance.  Serializes both the raw data and the
     * metadata needed to reconstruct the StructArray base class during
     * deserialization.
     * @private
     */
    static serialize(array, transferables) {
        array._trim();
        if (transferables) {
            array.isTransferred = true;
            transferables.add(array.arrayBuffer);
        }
        return {
            length: array.length,
            arrayBuffer: array.arrayBuffer
        };
    }
    static deserialize(input) {
        // $FlowFixMe not-an-object - newer Flow doesn't understand this pattern, silence for now
        const structArray = Object.create(this.prototype);
        structArray.arrayBuffer = input.arrayBuffer;
        structArray.length = input.length;
        structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement;
        structArray._refreshViews();
        return structArray;
    }
    /**
     * Resize the array to discard unused capacity.
     */
    _trim() {
        if (this.length !== this.capacity) {
            this.capacity = this.length;
            this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement);
            this._refreshViews();
        }
    }
    /**
     * Resets the the length of the array to 0 without de-allocating capacity.
     */
    clear() {
        this.length = 0;
    }
    /**
     * Resize the array.
     * If `n` is greater than the current length then additional elements with undefined values are added.
     * If `n` is less than the current length then the array will be reduced to the first `n` elements.
     * @param {number} n The new size of the array.
     */
    resize(n) {
        this.reserve(n);
        this.length = n;
    }
    /**
     * Indicate a planned increase in size, so that any necessary allocation may
     * be done once, ahead of time.
     * @param {number} n The expected size of the array.
     */
    reserve(n) {
        if (n > this.capacity) {
            this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY);
            this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);
            const oldUint8Array = this.uint8;
            this._refreshViews();
            if (oldUint8Array)
                this.uint8.set(oldUint8Array);
        }
    }
    /**
     * Create TypedArray views for the current ArrayBuffer.
     */
    _refreshViews() {
        throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');
    }
    destroy() {
        // $FlowFixMe
        this.int8 = this.uint8 = this.int16 = this.uint16 = this.int32 = this.uint32 = this.float32 = null;
        this.arrayBuffer = null;
    }
}
/**
 * Given a list of member fields, create a full StructArrayLayout, in
 * particular calculating the correct byte offset for each field.  This data
 * is used at build time to generate StructArrayLayout_*#emplaceBack() and
 * other accessors, and at runtime for binding vertex buffer attributes.
 *
 * @private
 */
function createLayout(members, alignment = 1) {
    let offset = 0;
    let maxSize = 0;
    const layoutMembers = members.map(member => {
        const typeSize = sizeOf(member.type);
        const memberOffset = offset = align$1(offset, Math.max(alignment, typeSize));
        const components = member.components || 1;
        maxSize = Math.max(maxSize, typeSize);
        offset += typeSize * components;
        return {
            name: member.name,
            type: member.type,
            components,
            offset: memberOffset
        };
    });
    const size = align$1(offset, Math.max(maxSize, alignment));
    return {
        members: layoutMembers,
        size,
        alignment
    };
}
function sizeOf(type) {
    return viewTypes[type].BYTES_PER_ELEMENT;
}
function align$1(offset, size) {
    return Math.ceil(offset / size) * size;
}

/**
 * Implementation of the StructArray layout:
 * [0]: Int16[2]
 *
 * @private
 */
class StructArrayLayout2i4 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1);
    }
    emplace(i, v0, v1) {
        const o2 = i * 2;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        return i;
    }
}
StructArrayLayout2i4.prototype.bytesPerElement = 4;
register(StructArrayLayout2i4, 'StructArrayLayout2i4');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[3]
 *
 * @private
 */
class StructArrayLayout3i6 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2);
    }
    emplace(i, v0, v1, v2) {
        const o2 = i * 3;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        return i;
    }
}
StructArrayLayout3i6.prototype.bytesPerElement = 6;
register(StructArrayLayout3i6, 'StructArrayLayout3i6');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[4]
 *
 * @private
 */
class StructArrayLayout4i8 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3);
    }
    emplace(i, v0, v1, v2, v3) {
        const o2 = i * 4;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.int16[o2 + 3] = v3;
        return i;
    }
}
StructArrayLayout4i8.prototype.bytesPerElement = 8;
register(StructArrayLayout4i8, 'StructArrayLayout4i8');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[5]
 *
 * @private
 */
class StructArrayLayout5i10 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4);
    }
    emplace(i, v0, v1, v2, v3, v4) {
        const o2 = i * 5;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.int16[o2 + 3] = v3;
        this.int16[o2 + 4] = v4;
        return i;
    }
}
StructArrayLayout5i10.prototype.bytesPerElement = 10;
register(StructArrayLayout5i10, 'StructArrayLayout5i10');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[2]
 * [4]: Uint8[4]
 * [8]: Float32[1]
 *
 * @private
 */
class StructArrayLayout2i4ub1f12 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6) {
        const o2 = i * 6;
        const o1 = i * 12;
        const o4 = i * 3;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.uint8[o1 + 4] = v2;
        this.uint8[o1 + 5] = v3;
        this.uint8[o1 + 6] = v4;
        this.uint8[o1 + 7] = v5;
        this.float32[o4 + 2] = v6;
        return i;
    }
}
StructArrayLayout2i4ub1f12.prototype.bytesPerElement = 12;
register(StructArrayLayout2i4ub1f12, 'StructArrayLayout2i4ub1f12');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[4]
 *
 * @private
 */
class StructArrayLayout4f16 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3);
    }
    emplace(i, v0, v1, v2, v3) {
        const o4 = i * 4;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.float32[o4 + 2] = v2;
        this.float32[o4 + 3] = v3;
        return i;
    }
}
StructArrayLayout4f16.prototype.bytesPerElement = 16;
register(StructArrayLayout4f16, 'StructArrayLayout4f16');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint16[4]
 * [8]: Float32[1]
 *
 * @private
 */
class StructArrayLayout4ui1f12 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4);
    }
    emplace(i, v0, v1, v2, v3, v4) {
        const o2 = i * 6;
        const o4 = i * 3;
        this.uint16[o2 + 0] = v0;
        this.uint16[o2 + 1] = v1;
        this.uint16[o2 + 2] = v2;
        this.uint16[o2 + 3] = v3;
        this.float32[o4 + 2] = v4;
        return i;
    }
}
StructArrayLayout4ui1f12.prototype.bytesPerElement = 12;
register(StructArrayLayout4ui1f12, 'StructArrayLayout4ui1f12');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint16[4]
 *
 * @private
 */
class StructArrayLayout4ui8 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3);
    }
    emplace(i, v0, v1, v2, v3) {
        const o2 = i * 4;
        this.uint16[o2 + 0] = v0;
        this.uint16[o2 + 1] = v1;
        this.uint16[o2 + 2] = v2;
        this.uint16[o2 + 3] = v3;
        return i;
    }
}
StructArrayLayout4ui8.prototype.bytesPerElement = 8;
register(StructArrayLayout4ui8, 'StructArrayLayout4ui8');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[6]
 *
 * @private
 */
class StructArrayLayout6i12 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5);
    }
    emplace(i, v0, v1, v2, v3, v4, v5) {
        const o2 = i * 6;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.int16[o2 + 3] = v3;
        this.int16[o2 + 4] = v4;
        this.int16[o2 + 5] = v5;
        return i;
    }
}
StructArrayLayout6i12.prototype.bytesPerElement = 12;
register(StructArrayLayout6i12, 'StructArrayLayout6i12');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[4]
 * [8]: Uint16[4]
 * [16]: Int16[4]
 *
 * @private
 */
class StructArrayLayout4i4ui4i24 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) {
        const o2 = i * 12;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.int16[o2 + 3] = v3;
        this.uint16[o2 + 4] = v4;
        this.uint16[o2 + 5] = v5;
        this.uint16[o2 + 6] = v6;
        this.uint16[o2 + 7] = v7;
        this.int16[o2 + 8] = v8;
        this.int16[o2 + 9] = v9;
        this.int16[o2 + 10] = v10;
        this.int16[o2 + 11] = v11;
        return i;
    }
}
StructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24;
register(StructArrayLayout4i4ui4i24, 'StructArrayLayout4i4ui4i24');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[3]
 * [8]: Float32[3]
 *
 * @private
 */
class StructArrayLayout3i3f20 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5);
    }
    emplace(i, v0, v1, v2, v3, v4, v5) {
        const o2 = i * 10;
        const o4 = i * 5;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.float32[o4 + 2] = v3;
        this.float32[o4 + 3] = v4;
        this.float32[o4 + 4] = v5;
        return i;
    }
}
StructArrayLayout3i3f20.prototype.bytesPerElement = 20;
register(StructArrayLayout3i3f20, 'StructArrayLayout3i3f20');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint32[1]
 *
 * @private
 */
class StructArrayLayout1ul4 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint32 = new Uint32Array(this.arrayBuffer);
    }
    emplaceBack(v0) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0);
    }
    emplace(i, v0) {
        const o4 = i * 1;
        this.uint32[o4 + 0] = v0;
        return i;
    }
}
StructArrayLayout1ul4.prototype.bytesPerElement = 4;
register(StructArrayLayout1ul4, 'StructArrayLayout1ul4');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint16[2]
 *
 * @private
 */
class StructArrayLayout2ui4 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1);
    }
    emplace(i, v0, v1) {
        const o2 = i * 2;
        this.uint16[o2 + 0] = v0;
        this.uint16[o2 + 1] = v1;
        return i;
    }
}
StructArrayLayout2ui4.prototype.bytesPerElement = 4;
register(StructArrayLayout2ui4, 'StructArrayLayout2ui4');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[5]
 * [12]: Float32[4]
 * [28]: Int16[1]
 * [32]: Uint32[1]
 * [36]: Uint16[2]
 *
 * @private
 */
class StructArrayLayout5i4f1i1ul2ui40 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
        this.uint32 = new Uint32Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) {
        const o2 = i * 20;
        const o4 = i * 10;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.int16[o2 + 3] = v3;
        this.int16[o2 + 4] = v4;
        this.float32[o4 + 3] = v5;
        this.float32[o4 + 4] = v6;
        this.float32[o4 + 5] = v7;
        this.float32[o4 + 6] = v8;
        this.int16[o2 + 14] = v9;
        this.uint32[o4 + 8] = v10;
        this.uint16[o2 + 18] = v11;
        this.uint16[o2 + 19] = v12;
        return i;
    }
}
StructArrayLayout5i4f1i1ul2ui40.prototype.bytesPerElement = 40;
register(StructArrayLayout5i4f1i1ul2ui40, 'StructArrayLayout5i4f1i1ul2ui40');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[3]
 * [8]: Int16[2]
 * [12]: Int16[2]
 *
 * @private
 */
class StructArrayLayout3i2i2i16 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6) {
        const o2 = i * 8;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.int16[o2 + 4] = v3;
        this.int16[o2 + 5] = v4;
        this.int16[o2 + 6] = v5;
        this.int16[o2 + 7] = v6;
        return i;
    }
}
StructArrayLayout3i2i2i16.prototype.bytesPerElement = 16;
register(StructArrayLayout3i2i2i16, 'StructArrayLayout3i2i2i16');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[2]
 * [8]: Float32[1]
 * [12]: Int16[2]
 *
 * @private
 */
class StructArrayLayout2f1f2i16 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4);
    }
    emplace(i, v0, v1, v2, v3, v4) {
        const o4 = i * 4;
        const o2 = i * 8;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.float32[o4 + 2] = v2;
        this.int16[o2 + 6] = v3;
        this.int16[o2 + 7] = v4;
        return i;
    }
}
StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16;
register(StructArrayLayout2f1f2i16, 'StructArrayLayout2f1f2i16');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint8[2]
 * [4]: Float32[2]
 *
 * @private
 */
class StructArrayLayout2ub2f12 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3);
    }
    emplace(i, v0, v1, v2, v3) {
        const o1 = i * 12;
        const o4 = i * 3;
        this.uint8[o1 + 0] = v0;
        this.uint8[o1 + 1] = v1;
        this.float32[o4 + 1] = v2;
        this.float32[o4 + 2] = v3;
        return i;
    }
}
StructArrayLayout2ub2f12.prototype.bytesPerElement = 12;
register(StructArrayLayout2ub2f12, 'StructArrayLayout2ub2f12');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[3]
 *
 * @private
 */
class StructArrayLayout3f12 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2);
    }
    emplace(i, v0, v1, v2) {
        const o4 = i * 3;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.float32[o4 + 2] = v2;
        return i;
    }
}
StructArrayLayout3f12.prototype.bytesPerElement = 12;
register(StructArrayLayout3f12, 'StructArrayLayout3f12');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint16[3]
 *
 * @private
 */
class StructArrayLayout3ui6 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2);
    }
    emplace(i, v0, v1, v2) {
        const o2 = i * 3;
        this.uint16[o2 + 0] = v0;
        this.uint16[o2 + 1] = v1;
        this.uint16[o2 + 2] = v2;
        return i;
    }
}
StructArrayLayout3ui6.prototype.bytesPerElement = 6;
register(StructArrayLayout3ui6, 'StructArrayLayout3ui6');
/**
 * Implementation of the StructArray layout:
 * [0]: Int16[3]
 * [8]: Float32[2]
 * [16]: Uint16[2]
 * [20]: Uint32[3]
 * [32]: Uint16[3]
 * [40]: Float32[2]
 * [48]: Uint8[3]
 * [52]: Uint32[1]
 * [56]: Int16[1]
 * [58]: Uint8[1]
 *
 * @private
 */
class StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
        this.uint32 = new Uint32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) {
        const o2 = i * 30;
        const o4 = i * 15;
        const o1 = i * 60;
        this.int16[o2 + 0] = v0;
        this.int16[o2 + 1] = v1;
        this.int16[o2 + 2] = v2;
        this.float32[o4 + 2] = v3;
        this.float32[o4 + 3] = v4;
        this.uint16[o2 + 8] = v5;
        this.uint16[o2 + 9] = v6;
        this.uint32[o4 + 5] = v7;
        this.uint32[o4 + 6] = v8;
        this.uint32[o4 + 7] = v9;
        this.uint16[o2 + 16] = v10;
        this.uint16[o2 + 17] = v11;
        this.uint16[o2 + 18] = v12;
        this.float32[o4 + 10] = v13;
        this.float32[o4 + 11] = v14;
        this.uint8[o1 + 48] = v15;
        this.uint8[o1 + 49] = v16;
        this.uint8[o1 + 50] = v17;
        this.uint32[o4 + 13] = v18;
        this.int16[o2 + 28] = v19;
        this.uint8[o1 + 58] = v20;
        return i;
    }
}
StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60.prototype.bytesPerElement = 60;
register(StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60, 'StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[2]
 * [8]: Int16[9]
 * [26]: Uint16[15]
 * [56]: Uint32[1]
 * [60]: Float32[4]
 * [76]: Uint8[1]
 *
 * @private
 */
class StructArrayLayout2f9i15ui1ul4f1ub80 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
        this.int16 = new Int16Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
        this.uint32 = new Uint32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) {
        const o4 = i * 20;
        const o2 = i * 40;
        const o1 = i * 80;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.int16[o2 + 4] = v2;
        this.int16[o2 + 5] = v3;
        this.int16[o2 + 6] = v4;
        this.int16[o2 + 7] = v5;
        this.int16[o2 + 8] = v6;
        this.int16[o2 + 9] = v7;
        this.int16[o2 + 10] = v8;
        this.int16[o2 + 11] = v9;
        this.int16[o2 + 12] = v10;
        this.uint16[o2 + 13] = v11;
        this.uint16[o2 + 14] = v12;
        this.uint16[o2 + 15] = v13;
        this.uint16[o2 + 16] = v14;
        this.uint16[o2 + 17] = v15;
        this.uint16[o2 + 18] = v16;
        this.uint16[o2 + 19] = v17;
        this.uint16[o2 + 20] = v18;
        this.uint16[o2 + 21] = v19;
        this.uint16[o2 + 22] = v20;
        this.uint16[o2 + 23] = v21;
        this.uint16[o2 + 24] = v22;
        this.uint16[o2 + 25] = v23;
        this.uint16[o2 + 26] = v24;
        this.uint16[o2 + 27] = v25;
        this.uint32[o4 + 14] = v26;
        this.float32[o4 + 15] = v27;
        this.float32[o4 + 16] = v28;
        this.float32[o4 + 17] = v29;
        this.float32[o4 + 18] = v30;
        this.uint8[o1 + 76] = v31;
        return i;
    }
}
StructArrayLayout2f9i15ui1ul4f1ub80.prototype.bytesPerElement = 80;
register(StructArrayLayout2f9i15ui1ul4f1ub80, 'StructArrayLayout2f9i15ui1ul4f1ub80');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[1]
 *
 * @private
 */
class StructArrayLayout1f4 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0);
    }
    emplace(i, v0) {
        const o4 = i * 1;
        this.float32[o4 + 0] = v0;
        return i;
    }
}
StructArrayLayout1f4.prototype.bytesPerElement = 4;
register(StructArrayLayout1f4, 'StructArrayLayout1f4');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[5]
 *
 * @private
 */
class StructArrayLayout5f20 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4);
    }
    emplace(i, v0, v1, v2, v3, v4) {
        const o4 = i * 5;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.float32[o4 + 2] = v2;
        this.float32[o4 + 3] = v3;
        this.float32[o4 + 4] = v4;
        return i;
    }
}
StructArrayLayout5f20.prototype.bytesPerElement = 20;
register(StructArrayLayout5f20, 'StructArrayLayout5f20');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[7]
 *
 * @private
 */
class StructArrayLayout7f28 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6) {
        const o4 = i * 7;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.float32[o4 + 2] = v2;
        this.float32[o4 + 3] = v3;
        this.float32[o4 + 4] = v4;
        this.float32[o4 + 5] = v5;
        this.float32[o4 + 6] = v6;
        return i;
    }
}
StructArrayLayout7f28.prototype.bytesPerElement = 28;
register(StructArrayLayout7f28, 'StructArrayLayout7f28');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint32[1]
 * [4]: Uint16[3]
 *
 * @private
 */
class StructArrayLayout1ul3ui12 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint32 = new Uint32Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3);
    }
    emplace(i, v0, v1, v2, v3) {
        const o4 = i * 3;
        const o2 = i * 6;
        this.uint32[o4 + 0] = v0;
        this.uint16[o2 + 2] = v1;
        this.uint16[o2 + 3] = v2;
        this.uint16[o2 + 4] = v3;
        return i;
    }
}
StructArrayLayout1ul3ui12.prototype.bytesPerElement = 12;
register(StructArrayLayout1ul3ui12, 'StructArrayLayout1ul3ui12');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint16[1]
 *
 * @private
 */
class StructArrayLayout1ui2 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0);
    }
    emplace(i, v0) {
        const o2 = i * 1;
        this.uint16[o2 + 0] = v0;
        return i;
    }
}
StructArrayLayout1ui2.prototype.bytesPerElement = 2;
register(StructArrayLayout1ui2, 'StructArrayLayout1ui2');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[2]
 *
 * @private
 */
class StructArrayLayout2f8 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1);
    }
    emplace(i, v0, v1) {
        const o4 = i * 2;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        return i;
    }
}
StructArrayLayout2f8.prototype.bytesPerElement = 8;
register(StructArrayLayout2f8, 'StructArrayLayout2f8');
/**
 * Implementation of the StructArray layout:
 * [0]: Float32[16]
 *
 * @private
 */
class StructArrayLayout16f64 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        const o4 = i * 16;
        this.float32[o4 + 0] = v0;
        this.float32[o4 + 1] = v1;
        this.float32[o4 + 2] = v2;
        this.float32[o4 + 3] = v3;
        this.float32[o4 + 4] = v4;
        this.float32[o4 + 5] = v5;
        this.float32[o4 + 6] = v6;
        this.float32[o4 + 7] = v7;
        this.float32[o4 + 8] = v8;
        this.float32[o4 + 9] = v9;
        this.float32[o4 + 10] = v10;
        this.float32[o4 + 11] = v11;
        this.float32[o4 + 12] = v12;
        this.float32[o4 + 13] = v13;
        this.float32[o4 + 14] = v14;
        this.float32[o4 + 15] = v15;
        return i;
    }
}
StructArrayLayout16f64.prototype.bytesPerElement = 64;
register(StructArrayLayout16f64, 'StructArrayLayout16f64');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint16[4]
 * [8]: Float32[3]
 *
 * @private
 */
class StructArrayLayout4ui3f20 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
        this.float32 = new Float32Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6) {
        const o2 = i * 10;
        const o4 = i * 5;
        this.uint16[o2 + 0] = v0;
        this.uint16[o2 + 1] = v1;
        this.uint16[o2 + 2] = v2;
        this.uint16[o2 + 3] = v3;
        this.float32[o4 + 2] = v4;
        this.float32[o4 + 3] = v5;
        this.float32[o4 + 4] = v6;
        return i;
    }
}
StructArrayLayout4ui3f20.prototype.bytesPerElement = 20;
register(StructArrayLayout4ui3f20, 'StructArrayLayout4ui3f20');
/**
 * Implementation of the StructArray layout:
 * [0]: Uint8[1]
 *
 * @private
 */
class StructArrayLayout1ub1 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
    }
    emplaceBack(v0) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0);
    }
    emplace(i, v0) {
        const o1 = i * 1;
        this.uint8[o1 + 0] = v0;
        return i;
    }
}
StructArrayLayout1ub1.prototype.bytesPerElement = 1;
register(StructArrayLayout1ub1, 'StructArrayLayout1ub1');
class CollisionBoxStruct extends Struct {
    get projectedAnchorX() {
        return this._structArray.int16[this._pos2 + 0];
    }
    get projectedAnchorY() {
        return this._structArray.int16[this._pos2 + 1];
    }
    get projectedAnchorZ() {
        return this._structArray.int16[this._pos2 + 2];
    }
    get tileAnchorX() {
        return this._structArray.int16[this._pos2 + 3];
    }
    get tileAnchorY() {
        return this._structArray.int16[this._pos2 + 4];
    }
    get x1() {
        return this._structArray.float32[this._pos4 + 3];
    }
    get y1() {
        return this._structArray.float32[this._pos4 + 4];
    }
    get x2() {
        return this._structArray.float32[this._pos4 + 5];
    }
    get y2() {
        return this._structArray.float32[this._pos4 + 6];
    }
    get padding() {
        return this._structArray.int16[this._pos2 + 14];
    }
    get featureIndex() {
        return this._structArray.uint32[this._pos4 + 8];
    }
    get sourceLayerIndex() {
        return this._structArray.uint16[this._pos2 + 18];
    }
    get bucketIndex() {
        return this._structArray.uint16[this._pos2 + 19];
    }
}
CollisionBoxStruct.prototype.size = 40;
/**
 * @private
 */
class CollisionBoxArray extends StructArrayLayout5i4f1i1ul2ui40 {
    /**
     * Return the CollisionBoxStruct at the given location in the array.
     * @param {number} index The index of the element.
     * @private
     */
    get(index) {
        return new CollisionBoxStruct(this, index);
    }
}
register(CollisionBoxArray, 'CollisionBoxArray');
class PlacedSymbolStruct extends Struct {
    get projectedAnchorX() {
        return this._structArray.int16[this._pos2 + 0];
    }
    get projectedAnchorY() {
        return this._structArray.int16[this._pos2 + 1];
    }
    get projectedAnchorZ() {
        return this._structArray.int16[this._pos2 + 2];
    }
    get tileAnchorX() {
        return this._structArray.float32[this._pos4 + 2];
    }
    get tileAnchorY() {
        return this._structArray.float32[this._pos4 + 3];
    }
    get glyphStartIndex() {
        return this._structArray.uint16[this._pos2 + 8];
    }
    get numGlyphs() {
        return this._structArray.uint16[this._pos2 + 9];
    }
    get vertexStartIndex() {
        return this._structArray.uint32[this._pos4 + 5];
    }
    get lineStartIndex() {
        return this._structArray.uint32[this._pos4 + 6];
    }
    get lineLength() {
        return this._structArray.uint32[this._pos4 + 7];
    }
    get segment() {
        return this._structArray.uint16[this._pos2 + 16];
    }
    get lowerSize() {
        return this._structArray.uint16[this._pos2 + 17];
    }
    get upperSize() {
        return this._structArray.uint16[this._pos2 + 18];
    }
    get lineOffsetX() {
        return this._structArray.float32[this._pos4 + 10];
    }
    get lineOffsetY() {
        return this._structArray.float32[this._pos4 + 11];
    }
    get writingMode() {
        return this._structArray.uint8[this._pos1 + 48];
    }
    get placedOrientation() {
        return this._structArray.uint8[this._pos1 + 49];
    }
    set placedOrientation(x) {
        this._structArray.uint8[this._pos1 + 49] = x;
    }
    get hidden() {
        return this._structArray.uint8[this._pos1 + 50];
    }
    set hidden(x) {
        this._structArray.uint8[this._pos1 + 50] = x;
    }
    get crossTileID() {
        return this._structArray.uint32[this._pos4 + 13];
    }
    set crossTileID(x) {
        this._structArray.uint32[this._pos4 + 13] = x;
    }
    get associatedIconIndex() {
        return this._structArray.int16[this._pos2 + 28];
    }
    get flipState() {
        return this._structArray.uint8[this._pos1 + 58];
    }
    set flipState(x) {
        this._structArray.uint8[this._pos1 + 58] = x;
    }
}
PlacedSymbolStruct.prototype.size = 60;
/**
 * @private
 */
class PlacedSymbolArray extends StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60 {
    /**
     * Return the PlacedSymbolStruct at the given location in the array.
     * @param {number} index The index of the element.
     * @private
     */
    get(index) {
        return new PlacedSymbolStruct(this, index);
    }
}
register(PlacedSymbolArray, 'PlacedSymbolArray');
class SymbolInstanceStruct extends Struct {
    get tileAnchorX() {
        return this._structArray.float32[this._pos4 + 0];
    }
    get tileAnchorY() {
        return this._structArray.float32[this._pos4 + 1];
    }
    get projectedAnchorX() {
        return this._structArray.int16[this._pos2 + 4];
    }
    get projectedAnchorY() {
        return this._structArray.int16[this._pos2 + 5];
    }
    get projectedAnchorZ() {
        return this._structArray.int16[this._pos2 + 6];
    }
    get rightJustifiedTextSymbolIndex() {
        return this._structArray.int16[this._pos2 + 7];
    }
    get centerJustifiedTextSymbolIndex() {
        return this._structArray.int16[this._pos2 + 8];
    }
    get leftJustifiedTextSymbolIndex() {
        return this._structArray.int16[this._pos2 + 9];
    }
    get verticalPlacedTextSymbolIndex() {
        return this._structArray.int16[this._pos2 + 10];
    }
    get placedIconSymbolIndex() {
        return this._structArray.int16[this._pos2 + 11];
    }
    get verticalPlacedIconSymbolIndex() {
        return this._structArray.int16[this._pos2 + 12];
    }
    get key() {
        return this._structArray.uint16[this._pos2 + 13];
    }
    get textBoxStartIndex() {
        return this._structArray.uint16[this._pos2 + 14];
    }
    get textBoxEndIndex() {
        return this._structArray.uint16[this._pos2 + 15];
    }
    get verticalTextBoxStartIndex() {
        return this._structArray.uint16[this._pos2 + 16];
    }
    get verticalTextBoxEndIndex() {
        return this._structArray.uint16[this._pos2 + 17];
    }
    get iconBoxStartIndex() {
        return this._structArray.uint16[this._pos2 + 18];
    }
    get iconBoxEndIndex() {
        return this._structArray.uint16[this._pos2 + 19];
    }
    get verticalIconBoxStartIndex() {
        return this._structArray.uint16[this._pos2 + 20];
    }
    get verticalIconBoxEndIndex() {
        return this._structArray.uint16[this._pos2 + 21];
    }
    get featureIndex() {
        return this._structArray.uint16[this._pos2 + 22];
    }
    get numHorizontalGlyphVertices() {
        return this._structArray.uint16[this._pos2 + 23];
    }
    get numVerticalGlyphVertices() {
        return this._structArray.uint16[this._pos2 + 24];
    }
    get numIconVertices() {
        return this._structArray.uint16[this._pos2 + 25];
    }
    get numVerticalIconVertices() {
        return this._structArray.uint16[this._pos2 + 26];
    }
    get useRuntimeCollisionCircles() {
        return this._structArray.uint16[this._pos2 + 27];
    }
    get crossTileID() {
        return this._structArray.uint32[this._pos4 + 14];
    }
    set crossTileID(x) {
        this._structArray.uint32[this._pos4 + 14] = x;
    }
    get textOffset0() {
        return this._structArray.float32[this._pos4 + 15];
    }
    get textOffset1() {
        return this._structArray.float32[this._pos4 + 16];
    }
    get collisionCircleDiameter() {
        return this._structArray.float32[this._pos4 + 17];
    }
    get zOffset() {
        return this._structArray.float32[this._pos4 + 18];
    }
    set zOffset(x) {
        this._structArray.float32[this._pos4 + 18] = x;
    }
    get hasIconTextFit() {
        return this._structArray.uint8[this._pos1 + 76];
    }
}
SymbolInstanceStruct.prototype.size = 80;
/**
 * @private
 */
class SymbolInstanceArray extends StructArrayLayout2f9i15ui1ul4f1ub80 {
    /**
     * Return the SymbolInstanceStruct at the given location in the array.
     * @param {number} index The index of the element.
     * @private
     */
    get(index) {
        return new SymbolInstanceStruct(this, index);
    }
}
register(SymbolInstanceArray, 'SymbolInstanceArray');
/**
 * @private
 */
class GlyphOffsetArray extends StructArrayLayout1f4 {
    getoffsetX(index) {
        return this.float32[index * 1 + 0];
    }
}
register(GlyphOffsetArray, 'GlyphOffsetArray');
/**
 * @private
 */
class SymbolLineVertexArray extends StructArrayLayout2i4 {
    getx(index) {
        return this.int16[index * 2 + 0];
    }
    gety(index) {
        return this.int16[index * 2 + 1];
    }
}
register(SymbolLineVertexArray, 'SymbolLineVertexArray');
class FeatureIndexStruct extends Struct {
    get featureIndex() {
        return this._structArray.uint32[this._pos4 + 0];
    }
    get sourceLayerIndex() {
        return this._structArray.uint16[this._pos2 + 2];
    }
    get bucketIndex() {
        return this._structArray.uint16[this._pos2 + 3];
    }
    get layoutVertexArrayOffset() {
        return this._structArray.uint16[this._pos2 + 4];
    }
}
FeatureIndexStruct.prototype.size = 12;
/**
 * @private
 */
class FeatureIndexArray extends StructArrayLayout1ul3ui12 {
    /**
     * Return the FeatureIndexStruct at the given location in the array.
     * @param {number} index The index of the element.
     * @private
     */
    get(index) {
        return new FeatureIndexStruct(this, index);
    }
}
register(FeatureIndexArray, 'FeatureIndexArray');
/**
 * @private
 */
class FillExtrusionCentroidArray extends StructArrayLayout2ui4 {
    geta_centroid_pos0(index) {
        return this.uint16[index * 2 + 0];
    }
    geta_centroid_pos1(index) {
        return this.uint16[index * 2 + 1];
    }
}
register(FillExtrusionCentroidArray, 'FillExtrusionCentroidArray');

//      
const circleAttributes = createLayout([{
        name: 'a_pos',
        components: 2,
        type: 'Int16'
    }], 4);
const circleGlobeAttributesExt = createLayout([
    {
        name: 'a_pos_3',
        components: 3,
        type: 'Int16'
    },
    {
        name: 'a_pos_normal_3',
        components: 3,
        type: 'Int16'
    }
]);

//      
class SegmentVector {
    constructor(segments = []) {
        this.segments = segments;
    }
    _prepareSegment(numVertices, vertexArrayLength, indexArrayLength, sortKey) {
        let segment = this.segments[this.segments.length - 1];
        if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH)
            warnOnce(`Max vertices per segment is ${ SegmentVector.MAX_VERTEX_ARRAY_LENGTH }: bucket requested ${ numVertices }`);
        if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) {
            segment = {
                vertexOffset: vertexArrayLength,
                primitiveOffset: indexArrayLength,
                vertexLength: 0,
                primitiveLength: 0
            };
            if (sortKey !== undefined)
                segment.sortKey = sortKey;
            this.segments.push(segment);
        }
        return segment;
    }
    prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) {
        return this._prepareSegment(numVertices, layoutVertexArray.length, indexArray.length, sortKey);
    }
    get() {
        return this.segments;
    }
    destroy() {
        for (const segment of this.segments) {
            for (const k in segment.vaos) {
                segment.vaos[k].destroy();
            }
        }
    }
    static simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) {
        return new SegmentVector([{
                vertexOffset,
                primitiveOffset,
                vertexLength,
                primitiveLength,
                vaos: {},
                sortKey: 0
            }]);
    }
}
/*
 * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit
 * addressing of vertex buffers.
 * @private
 * @readonly
 */
SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;
register(SegmentVector, 'SegmentVector');

//      
/**
 * Packs two numbers, interpreted as 8-bit unsigned integers, into a single
 * float.  Unpack them in the shader using the `unpack_float()` function,
 * defined in _prelude.vertex.glsl
 *
 * @private
 */
function packUint8ToFloat(a, b) {
    // coerce a and b to 8-bit ints
    a = clamp(Math.floor(a), 0, 255);
    b = clamp(Math.floor(b), 0, 255);
    return 256 * a + b;
}

//      
const patternAttributes = createLayout([
    // [tl.x, tl.y, br.x, br.y]
    {
        name: 'a_pattern',
        components: 4,
        type: 'Uint16'
    },
    {
        name: 'a_pixel_ratio',
        components: 1,
        type: 'Float32'
    }
]);

//      
const dashAttributes = createLayout([{
        name: 'a_dash',
        components: 4,
        type: 'Uint16'
    }    // [x, y, width, unused]
]);

var murmurhashJs = {exports: {}};

var murmurhash3_gc = {exports: {}};

/**
 * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
 * 
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/murmurhash-js
 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
 * @see http://sites.google.com/site/murmurhash/
 * 
 * @param {string} key ASCII only
 * @param {number} seed Positive integer only
 * @return {number} 32-bit positive integer hash 
 */

(function (module) {
	function murmurhash3_32_gc(key, seed) {
	    var remainder, bytes, h1, h1b, c1, c2, k1, i;
	    remainder = key.length & 3;
	    // key.length % 4
	    bytes = key.length - remainder;
	    h1 = seed;
	    c1 = 3432918353;
	    c2 = 461845907;
	    i = 0;
	    while (i < bytes) {
	        k1 = key.charCodeAt(i) & 255 | (key.charCodeAt(++i) & 255) << 8 | (key.charCodeAt(++i) & 255) << 16 | (key.charCodeAt(++i) & 255) << 24;
	        ++i;
	        k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295;
	        k1 = k1 << 15 | k1 >>> 17;
	        k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295;
	        h1 ^= k1;
	        h1 = h1 << 13 | h1 >>> 19;
	        h1b = (h1 & 65535) * 5 + (((h1 >>> 16) * 5 & 65535) << 16) & 4294967295;
	        h1 = (h1b & 65535) + 27492 + (((h1b >>> 16) + 58964 & 65535) << 16);
	    }
	    k1 = 0;
	    switch (remainder) {
	    case 3:
	        k1 ^= (key.charCodeAt(i + 2) & 255) << 16;
	    case 2:
	        k1 ^= (key.charCodeAt(i + 1) & 255) << 8;
	    case 1:
	        k1 ^= key.charCodeAt(i) & 255;
	        k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295;
	        k1 = k1 << 15 | k1 >>> 17;
	        k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295;
	        h1 ^= k1;
	    }
	    h1 ^= key.length;
	    h1 ^= h1 >>> 16;
	    h1 = (h1 & 65535) * 2246822507 + (((h1 >>> 16) * 2246822507 & 65535) << 16) & 4294967295;
	    h1 ^= h1 >>> 13;
	    h1 = (h1 & 65535) * 3266489909 + (((h1 >>> 16) * 3266489909 & 65535) << 16) & 4294967295;
	    h1 ^= h1 >>> 16;
	    return h1 >>> 0;
	}
	{
	    module.exports = murmurhash3_32_gc;
	} 
} (murmurhash3_gc));

var murmurhash3_gcExports = murmurhash3_gc.exports;

var murmurhash2_gc = {exports: {}};

/**
 * JS Implementation of MurmurHash2
 * 
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/murmurhash-js
 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
 * @see http://sites.google.com/site/murmurhash/
 * 
 * @param {string} str ASCII only
 * @param {number} seed Positive integer only
 * @return {number} 32-bit positive integer hash
 */

(function (module) {
	function murmurhash2_32_gc(str, seed) {
	    var l = str.length, h = seed ^ l, i = 0, k;
	    while (l >= 4) {
	        k = str.charCodeAt(i) & 255 | (str.charCodeAt(++i) & 255) << 8 | (str.charCodeAt(++i) & 255) << 16 | (str.charCodeAt(++i) & 255) << 24;
	        k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
	        k ^= k >>> 24;
	        k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
	        h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16) ^ k;
	        l -= 4;
	        ++i;
	    }
	    switch (l) {
	    case 3:
	        h ^= (str.charCodeAt(i + 2) & 255) << 16;
	    case 2:
	        h ^= (str.charCodeAt(i + 1) & 255) << 8;
	    case 1:
	        h ^= str.charCodeAt(i) & 255;
	        h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
	    }
	    h ^= h >>> 13;
	    h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
	    h ^= h >>> 15;
	    return h >>> 0;
	}
	{
	    module.exports = murmurhash2_32_gc;
	} 
} (murmurhash2_gc));

var murmurhash2_gcExports = murmurhash2_gc.exports;

var murmur3 = murmurhash3_gcExports;
var murmur2 = murmurhash2_gcExports;
murmurhashJs.exports = murmur3;
murmurhashJs.exports.murmur3 = murmur3;
murmurhashJs.exports.murmur2 = murmur2;

var murmurhashJsExports = murmurhashJs.exports;
var murmur3$1 = /*@__PURE__*/getDefaultExportFromCjs(murmurhashJsExports);

//      
// A transferable data structure that maps feature ids to their indices and buffer offsets
class FeaturePositionMap {
    constructor() {
        this.ids = [];
        this.uniqueIds = [];
        this.positions = [];
        this.indexed = false;
    }
    add(id, index, start, end) {
        this.ids.push(getNumericId(id));
        this.positions.push(index, start, end);
    }
    eachPosition(id, fn) {
        const intId = getNumericId(id);
        // binary search for the first occurrence of id in this.ids;
        // relies on ids/positions being sorted by id, which happens in serialization
        let i = 0;
        let j = this.ids.length - 1;
        while (i < j) {
            const m = i + j >> 1;
            if (this.ids[m] >= intId) {
                j = m;
            } else {
                i = m + 1;
            }
        }
        while (this.ids[i] === intId) {
            const index = this.positions[3 * i];
            const start = this.positions[3 * i + 1];
            const end = this.positions[3 * i + 2];
            fn(index, start, end);
            i++;
        }
    }
    static serialize(map, transferables) {
        const ids = new Float64Array(map.ids);
        const positions = new Uint32Array(map.positions);
        sort$1(ids, positions, 0, ids.length - 1);
        if (transferables) {
            transferables.add(ids.buffer);
            transferables.add(positions.buffer);
        }
        return {
            ids,
            positions
        };
    }
    static deserialize(obj) {
        const map = new FeaturePositionMap();
        // after transferring, we only use these arrays statically (no pushes),
        // so TypedArray vs Array distinction that flow points out doesn't matter
        map.ids = obj.ids;
        map.positions = obj.positions;
        let prev;
        for (const id of map.ids) {
            if (id !== prev)
                map.uniqueIds.push(id);
            prev = id;
        }
        map.indexed = true;
        return map;
    }
}
function getNumericId(value) {
    const numValue = +value;
    if (!isNaN(numValue) && Number.MIN_SAFE_INTEGER <= numValue && numValue <= Number.MAX_SAFE_INTEGER) {
        return numValue;
    }
    return murmur3$1(String(value));
}
// custom quicksort that sorts ids, indices and offsets together (by ids)
// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios
function sort$1(ids, positions, left, right) {
    while (left < right) {
        const pivot = ids[left + right >> 1];
        let i = left - 1;
        let j = right + 1;
        while (true) {
            do
                i++;
            while (ids[i] < pivot);
            do
                j--;
            while (ids[j] > pivot);
            if (i >= j)
                break;
            swap$1(ids, i, j);
            swap$1(positions, 3 * i, 3 * j);
            swap$1(positions, 3 * i + 1, 3 * j + 1);
            swap$1(positions, 3 * i + 2, 3 * j + 2);
        }
        if (j - left < right - j) {
            sort$1(ids, positions, left, j);
            left = j + 1;
        } else {
            sort$1(ids, positions, j + 1, right);
            right = j;
        }
    }
}
function swap$1(arr, i, j) {
    const tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
register(FeaturePositionMap, 'FeaturePositionMap');

//      
class Uniform {
    constructor(context) {
        this.gl = context.gl;
        this.initialized = false;
    }
    fetchUniformLocation(program, name) {
        if (!this.location && !this.initialized) {
            this.location = this.gl.getUniformLocation(program, name);
            this.initialized = true;
        }
        return !!this.location;
    }
}
class Uniform1i extends Uniform {
    constructor(context) {
        super(context);
        this.current = 0;
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        if (this.current !== v) {
            this.current = v;
            this.gl.uniform1i(this.location, v);
        }
    }
}
class Uniform1f extends Uniform {
    constructor(context) {
        super(context);
        this.current = 0;
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        if (this.current !== v) {
            this.current = v;
            this.gl.uniform1f(this.location, v);
        }
    }
}
class Uniform2f extends Uniform {
    constructor(context) {
        super(context);
        this.current = [
            0,
            0
        ];
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        if (v[0] !== this.current[0] || v[1] !== this.current[1]) {
            this.current = v;
            this.gl.uniform2f(this.location, v[0], v[1]);
        }
    }
}
class Uniform3f extends Uniform {
    constructor(context) {
        super(context);
        this.current = [
            0,
            0,
            0
        ];
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) {
            this.current = v;
            this.gl.uniform3f(this.location, v[0], v[1], v[2]);
        }
    }
}
class Uniform4f extends Uniform {
    constructor(context) {
        super(context);
        this.current = [
            0,
            0,
            0,
            0
        ];
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2] || v[3] !== this.current[3]) {
            this.current = v;
            this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]);
        }
    }
}
class UniformColor extends Uniform {
    constructor(context) {
        super(context);
        this.current = Color$1.transparent;
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        if (v.r !== this.current.r || v.g !== this.current.g || v.b !== this.current.b || v.a !== this.current.a) {
            this.current = v;
            this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a);
        }
    }
}
const emptyMat4$1 = new Float32Array(16);
class UniformMatrix4f extends Uniform {
    constructor(context) {
        super(context);
        this.current = emptyMat4$1;
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        // The vast majority of matrix comparisons that will trip this set
        // happen at i=12 or i=0, so we check those first to avoid lots of
        // unnecessary iteration:
        if (v[12] !== this.current[12] || v[0] !== this.current[0]) {
            this.current = v;
            this.gl.uniformMatrix4fv(this.location, false, v);
            return;
        }
        for (let i = 1; i < 16; i++) {
            if (v[i] !== this.current[i]) {
                this.current = v;
                this.gl.uniformMatrix4fv(this.location, false, v);
                break;
            }
        }
    }
}
const emptyMat3 = new Float32Array(9);
class UniformMatrix3f extends Uniform {
    constructor(context) {
        super(context);
        this.current = emptyMat3;
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        for (let i = 0; i < 9; i++) {
            if (v[i] !== this.current[i]) {
                this.current = v;
                this.gl.uniformMatrix3fv(this.location, false, v);
                break;
            }
        }
    }
}
const emptyMat2 = new Float32Array(4);
class UniformMatrix2f extends Uniform {
    constructor(context) {
        super(context);
        this.current = emptyMat2;
    }
    // $FlowFixMe[method-unbinding]
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        for (let i = 0; i < 4; i++) {
            if (v[i] !== this.current[i]) {
                this.current = v;
                this.gl.uniformMatrix2fv(this.location, false, v);
                break;
            }
        }
    }
}

//      
function packColor(color) {
    return [
        packUint8ToFloat(255 * color.r, 255 * color.g),
        packUint8ToFloat(255 * color.b, 255 * color.a)
    ];
}
/**
 *  `Binder` is the interface definition for the strategies for constructing,
 *  uploading, and binding paint property data as GLSL attributes. Most style-
 *  spec properties have a 1:1 relationship to shader attribute/uniforms, but
 *  some require multiple values per feature to be passed to the GPU, and in
 *  those cases we bind multiple attributes/uniforms.
 *
 *  It has three implementations, one for each of the three strategies we use:
 *
 *  * For _constant_ properties -- those whose value is a constant, or the constant
 *    result of evaluating a camera expression at a particular camera position -- we
 *    don't need a vertex attribute buffer, and instead use a uniform.
 *  * For data expressions, we use a vertex buffer with a single attribute value,
 *    the evaluated result of the source function for the given feature.
 *  * For composite expressions, we use a vertex buffer with two attributes: min and
 *    max values covering the range of zooms at which we expect the tile to be
 *    displayed. These values are calculated by evaluating the composite expression for
 *    the given feature at strategically chosen zoom levels. In addition to this
 *    attribute data, we also use a uniform value which the shader uses to interpolate
 *    between the min and max value at the final displayed zoom level. The use of a
 *    uniform allows us to cheaply update the value on every frame.
 *
 *  Note that the shader source varies depending on whether we're using a uniform or
 *  attribute. We dynamically compile shaders at runtime to accommodate this.
 *
 * @private
 */
class ConstantBinder {
    constructor(value, names, type) {
        this.value = value;
        this.uniformNames = names.map(name => `u_${ name }`);
        this.type = type;
    }
    setUniform(program, uniform, globals, currentValue, uniformName) {
        uniform.set(program, uniformName, currentValue.constantOr(this.value));
    }
    // $FlowFixMe[method-unbinding]
    getBinding(context, _) {
        // $FlowFixMe[method-unbinding]
        return this.type === 'color' ? new UniformColor(context) : new Uniform1f(context);
    }
}
class PatternConstantBinder {
    constructor(value, names) {
        this.uniformNames = names.map(name => `u_${ name }`);
        this.pattern = null;
        this.pixelRatio = 1;
    }
    setConstantPatternPositions(posTo) {
        this.pixelRatio = posTo.pixelRatio || 1;
        this.pattern = posTo.tl.concat(posTo.br);
    }
    setUniform(program, uniform, globals, currentValue, uniformName) {
        const pos = uniformName === 'u_pattern' || uniformName === 'u_dash' ? this.pattern : uniformName === 'u_pixel_ratio' ? this.pixelRatio : null;
        if (pos)
            uniform.set(program, uniformName, pos);
    }
    // $FlowFixMe[method-unbinding]
    getBinding(context, name) {
        // $FlowFixMe[method-unbinding]
        return name === 'u_pattern' || name === 'u_dash' ? new Uniform4f(context) : new Uniform1f(context);
    }
}
class SourceExpressionBinder {
    constructor(expression, names, type, PaintVertexArray) {
        this.expression = expression;
        this.type = type;
        this.maxValue = 0;
        this.paintVertexAttributes = names.map(name => ({
            name: `a_${ name }`,
            type: 'Float32',
            components: type === 'color' ? 2 : 1,
            offset: 0
        }));
        this.paintVertexArray = new PaintVertexArray();
    }
    populatePaintArray(newLength, feature, imagePositions, availableImages, canonical, brightness, formattedSection) {
        const start = this.paintVertexArray.length;
        // $FlowFixMe[method-unbinding]
        const value = this.expression.evaluate(new EvaluationParameters(0, { brightness }), feature, {}, canonical, availableImages, formattedSection);
        this.paintVertexArray.resize(newLength);
        this._setPaintValue(start, newLength, value);
    }
    updatePaintArray(start, end, feature, featureState, availableImages, spritePositions, brightness) {
        const value = this.expression.evaluate({
            zoom: 0,
            brightness
        }, feature, featureState, undefined, availableImages);
        this._setPaintValue(start, end, value);
    }
    _setPaintValue(start, end, value) {
        if (this.type === 'color') {
            const color = packColor(value);
            for (let i = start; i < end; i++) {
                this.paintVertexArray.emplace(i, color[0], color[1]);
            }
        } else {
            for (let i = start; i < end; i++) {
                this.paintVertexArray.emplace(i, value);
            }
            this.maxValue = Math.max(this.maxValue, Math.abs(value));
        }
    }
    upload(context) {
        if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {
            if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {
                this.paintVertexBuffer.updateData(this.paintVertexArray);
            } else {
                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent || !this.expression.isLightConstant);
            }
        }
    }
    destroy() {
        if (this.paintVertexBuffer) {
            this.paintVertexBuffer.destroy();
        }
    }
}
class CompositeExpressionBinder {
    constructor(expression, names, type, useIntegerZoom, zoom, PaintVertexArray) {
        this.expression = expression;
        this.uniformNames = names.map(name => `u_${ name }_t`);
        this.type = type;
        this.useIntegerZoom = useIntegerZoom;
        this.zoom = zoom;
        this.maxValue = 0;
        this.paintVertexAttributes = names.map(name => ({
            name: `a_${ name }`,
            type: 'Float32',
            components: type === 'color' ? 4 : 2,
            offset: 0
        }));
        this.paintVertexArray = new PaintVertexArray();
    }
    populatePaintArray(newLength, feature, imagePositions, availableImages, canonical, brightness, formattedSection) {
        // $FlowFixMe[method-unbinding]
        const min = this.expression.evaluate(new EvaluationParameters(this.zoom, { brightness }), feature, {}, canonical, availableImages, formattedSection);
        // $FlowFixMe[method-unbinding]
        const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, { brightness }), feature, {}, canonical, availableImages, formattedSection);
        const start = this.paintVertexArray.length;
        this.paintVertexArray.resize(newLength);
        this._setPaintValue(start, newLength, min, max);
    }
    updatePaintArray(start, end, feature, featureState, availableImages, spritePositions, brightness) {
        const min = this.expression.evaluate({
            zoom: this.zoom,
            brightness
        }, feature, featureState, undefined, availableImages);
        const max = this.expression.evaluate({
            zoom: this.zoom + 1,
            brightness
        }, feature, featureState, undefined, availableImages);
        this._setPaintValue(start, end, min, max);
    }
    _setPaintValue(start, end, min, max) {
        if (this.type === 'color') {
            const minColor = packColor(min);
            const maxColor = packColor(max);
            for (let i = start; i < end; i++) {
                this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]);
            }
        } else {
            for (let i = start; i < end; i++) {
                this.paintVertexArray.emplace(i, min, max);
            }
            this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max));
        }
    }
    upload(context) {
        if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {
            if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {
                this.paintVertexBuffer.updateData(this.paintVertexArray);
            } else {
                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent || !this.expression.isLightConstant);
            }
        }
    }
    destroy() {
        if (this.paintVertexBuffer) {
            this.paintVertexBuffer.destroy();
        }
    }
    setUniform(program, uniform, globals, _, uniformName) {
        const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom;
        const factor = clamp(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1);
        uniform.set(program, uniformName, factor);
    }
    // $FlowFixMe[method-unbinding]
    getBinding(context, _) {
        return new Uniform1f(context);
    }
}
class PatternCompositeBinder {
    constructor(expression, names, type, PaintVertexArray, layerId) {
        this.expression = expression;
        this.layerId = layerId;
        this.paintVertexAttributes = (type === 'array' ? dashAttributes : patternAttributes).members;
        for (let i = 0; i < names.length; ++i) {
        }
        this.paintVertexArray = new PaintVertexArray();
    }
    populatePaintArray(length, feature, imagePositions) {
        const start = this.paintVertexArray.length;
        this.paintVertexArray.resize(length);
        this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions);
    }
    updatePaintArray(start, end, feature, featureState, availableImages, imagePositions, _) {
        this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions);
    }
    _setPaintValues(start, end, patterns, positions) {
        if (!positions || !patterns)
            return;
        const pos = positions[patterns];
        if (!pos)
            return;
        const {tl, br, pixelRatio} = pos;
        for (let i = start; i < end; i++) {
            this.paintVertexArray.emplace(i, tl[0], tl[1], br[0], br[1], pixelRatio);
        }
    }
    upload(context) {
        if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {
            this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent || !this.expression.isLightConstant);
        }
    }
    destroy() {
        if (this.paintVertexBuffer)
            this.paintVertexBuffer.destroy();
    }
}
/**
 * ProgramConfiguration contains the logic for binding style layer properties and tile
 * layer feature data into GL program uniforms and vertex attributes.
 *
 * Non-data-driven property values are bound to shader uniforms. Data-driven property
 * values are bound to vertex attributes. In order to support a uniform GLSL syntax over
 * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma`
 * abstraction, which ProgramConfiguration is responsible for implementing. At runtime,
 * it examines the attributes of a particular layer, combines this with fixed knowledge
 * about how layers of the particular type are implemented, and determines which uniforms
 * and vertex attributes will be required. It can then substitute the appropriate text
 * into the shader source code, create and link a program, and bind the uniforms and
 * vertex attributes in preparation for drawing.
 *
 * When a vector tile is parsed, this same configuration information is used to
 * populate the attribute buffers needed for data-driven styling using the zoom
 * level and feature property data.
 *
 * @private
 */
class ProgramConfiguration {
    constructor(layer, zoom, filterProperties = () => true) {
        this.binders = {};
        this._buffers = [];
        const keys = [];
        for (const property in layer.paint._values) {
            const value = layer.paint.get(property);
            if (!filterProperties(property))
                continue;
            if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {
                continue;
            }
            const names = paintAttributeNames(property, layer.type);
            const expression = value.value;
            const type = value.property.specification.type;
            const useIntegerZoom = !!value.property.useIntegerZoom;
            const isPattern = property === 'line-dasharray' || property.endsWith('pattern');
            const sourceException = property === 'line-dasharray' && layer.layout.get('line-cap').value.kind !== 'constant';
            if (expression.kind === 'constant' && !sourceException) {
                this.binders[property] = isPattern ? new PatternConstantBinder(expression.value, names) : new ConstantBinder(expression.value, names, type);
                keys.push(`/u_${ property }`);
            } else if (expression.kind === 'source' || sourceException || isPattern) {
                const StructArrayLayout = layoutType(property, type, 'source');
                this.binders[property] = isPattern ? // $FlowFixMe[prop-missing]
                // $FlowFixMe[incompatible-call] - expression can be a `composite` or `constant` kind expression
                new PatternCompositeBinder(expression, names, type, StructArrayLayout, layer.id) : // $FlowFixMe[prop-missing]
                // $FlowFixMe[incompatible-call] - expression can be a `composite` or `constant` kind expression
                new SourceExpressionBinder(expression, names, type, StructArrayLayout);
                keys.push(`/a_${ property }`);
            } else {
                const StructArrayLayout = layoutType(property, type, 'composite');
                // $FlowFixMe[prop-missing]
                // $FlowFixMe[incompatible-call] — expression can be a `constant` kind expression
                this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout);
                keys.push(`/z_${ property }`);
            }
        }
        this.cacheKey = keys.sort().join('');
    }
    getMaxValue(property) {
        const binder = this.binders[property];
        return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0;
    }
    populatePaintArrays(newLength, feature, imagePositions, availableImages, canonical, brightness, formattedSection) {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)
                binder.populatePaintArray(newLength, feature, imagePositions, availableImages, canonical, brightness, formattedSection);
        }
    }
    setConstantPatternPositions(posTo) {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof PatternConstantBinder)
                binder.setConstantPatternPositions(posTo);
        }
    }
    updatePaintArrays(featureStates, featureMap, featureMapWithoutIds, vtLayer, layer, availableImages, imagePositions, brightness) {
        let dirty = false;
        const keys = Object.keys(featureStates);
        const featureStateUpdate = keys.length !== 0;
        const ids = featureStateUpdate ? keys : featureMap.uniqueIds;
        for (const property in this.binders) {
            const binder = this.binders[property];
            if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder) && (binder.expression.isStateDependent === true || binder.expression.isLightConstant === false)) {
                //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255
                const value = layer.paint.get(property);
                binder.expression = value.value;
                for (const id of ids) {
                    const state = featureStates[id.toString()];
                    featureMap.eachPosition(id, (index, start, end) => {
                        const feature = vtLayer.feature(index);
                        binder.updatePaintArray(start, end, feature, state, availableImages, imagePositions, brightness);
                    });
                }
                if (!featureStateUpdate) {
                    for (const id of featureMapWithoutIds.uniqueIds) {
                        const state = featureStates[id.toString()];
                        featureMapWithoutIds.eachPosition(id, (index, start, end) => {
                            const feature = vtLayer.feature(index);
                            binder.updatePaintArray(start, end, feature, state, availableImages, imagePositions, brightness);
                        });
                    }
                }
                dirty = true;
            }
        }
        return dirty;
    }
    defines() {
        const result = [];
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof ConstantBinder || binder instanceof PatternConstantBinder) {
                result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${ name }`));
            }
        }
        return result;
    }
    getBinderAttributes() {
        const result = [];
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder) {
                for (let i = 0; i < binder.paintVertexAttributes.length; i++) {
                    result.push(binder.paintVertexAttributes[i].name);
                }
            }
        }
        return result;
    }
    getBinderUniforms() {
        const uniforms = [];
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof ConstantBinder || binder instanceof PatternConstantBinder || binder instanceof CompositeExpressionBinder) {
                for (const uniformName of binder.uniformNames) {
                    uniforms.push(uniformName);
                }
            }
        }
        return uniforms;
    }
    getPaintVertexBuffers() {
        return this._buffers;
    }
    getUniforms(context) {
        const uniforms = [];
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof ConstantBinder || binder instanceof PatternConstantBinder || binder instanceof CompositeExpressionBinder) {
                for (const name of binder.uniformNames) {
                    uniforms.push({
                        name,
                        property,
                        binding: binder.getBinding(context, name)
                    });
                }
            }
        }
        return uniforms;
    }
    setUniforms(program, context, binderUniforms, properties, globals) {
        // Uniform state bindings are owned by the Program, but we set them
        // from within the ProgramConfiguration's binder members.
        for (const {name, property, binding} of binderUniforms) {
            this.binders[property].setUniform(program, binding, globals, properties.get(property), name);
        }
    }
    updatePaintBuffers() {
        this._buffers = [];
        for (const property in this.binders) {
            const binder = this.binders[property];
            if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder) && binder.paintVertexBuffer) {
                this._buffers.push(binder.paintVertexBuffer);
            }
        }
    }
    upload(context) {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)
                binder.upload(context);
        }
        this.updatePaintBuffers();
    }
    destroy() {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)
                binder.destroy();
        }
    }
}
class ProgramConfigurationSet {
    constructor(layers, zoom, filterProperties = () => true) {
        this.programConfigurations = {};
        for (const layer of layers) {
            this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties);
        }
        this.needsUpload = false;
        this._featureMap = new FeaturePositionMap();
        this._featureMapWithoutIds = new FeaturePositionMap();
        this._bufferOffset = 0;
        this._idlessCounter = 0;
    }
    populatePaintArrays(length, feature, index, imagePositions, availableImages, canonical, brightness, formattedSection) {
        for (const key in this.programConfigurations) {
            this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, availableImages, canonical, brightness, formattedSection);
        }
        if (feature.id !== undefined) {
            this._featureMap.add(feature.id, index, this._bufferOffset, length);
        } else {
            this._featureMapWithoutIds.add(this._idlessCounter, index, this._bufferOffset, length);
            this._idlessCounter += 1;
        }
        this._bufferOffset = length;
        this.needsUpload = true;
    }
    updatePaintArrays(featureStates, vtLayer, layers, availableImages, imagePositions, brightness) {
        for (const layer of layers) {
            this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, this._featureMapWithoutIds, vtLayer, layer, availableImages, imagePositions, brightness || 0) || this.needsUpload;
        }
    }
    get(layerId) {
        return this.programConfigurations[layerId];
    }
    upload(context) {
        if (!this.needsUpload)
            return;
        for (const layerId in this.programConfigurations) {
            this.programConfigurations[layerId].upload(context);
        }
        this.needsUpload = false;
    }
    destroy() {
        for (const layerId in this.programConfigurations) {
            this.programConfigurations[layerId].destroy();
        }
    }
}
const attributeNameExceptions = {
    'text-opacity': ['opacity'],
    'icon-opacity': ['opacity'],
    'text-color': ['fill_color'],
    'icon-color': ['fill_color'],
    'text-emissive-strength': ['emissive_strength'],
    'icon-emissive-strength': ['emissive_strength'],
    'text-halo-color': ['halo_color'],
    'icon-halo-color': ['halo_color'],
    'text-halo-blur': ['halo_blur'],
    'icon-halo-blur': ['halo_blur'],
    'text-halo-width': ['halo_width'],
    'icon-halo-width': ['halo_width'],
    'line-gap-width': ['gapwidth'],
    'line-pattern': [
        'pattern',
        'pixel_ratio'
    ],
    'fill-pattern': [
        'pattern',
        'pixel_ratio'
    ],
    'fill-extrusion-pattern': [
        'pattern',
        'pixel_ratio'
    ],
    'line-dasharray': ['dash']
};
function paintAttributeNames(property, type) {
    return attributeNameExceptions[property] || [property.replace(`${ type }-`, '').replace(/-/g, '_')];
}
const propertyExceptions = {
    'line-pattern': {
        'source': StructArrayLayout4ui1f12,
        'composite': StructArrayLayout4ui1f12
    },
    'fill-pattern': {
        'source': StructArrayLayout4ui1f12,
        'composite': StructArrayLayout4ui1f12
    },
    'fill-extrusion-pattern': {
        'source': StructArrayLayout4ui1f12,
        'composite': StructArrayLayout4ui1f12
    },
    'line-dasharray': {
        // temporary layout
        'source': StructArrayLayout4ui8,
        'composite': StructArrayLayout4ui8
    }
};
const defaultLayouts = {
    'color': {
        'source': StructArrayLayout2f8,
        'composite': StructArrayLayout4f16
    },
    'number': {
        'source': StructArrayLayout1f4,
        'composite': StructArrayLayout2f8
    }
};
function layoutType(property, type, binderType) {
    const layoutException = propertyExceptions[property];
    // $FlowFixMe[prop-missing] - we don't cover all types in defaultLayouts for some reason
    return layoutException && layoutException[binderType] || defaultLayouts[type][binderType];
}
register(ConstantBinder, 'ConstantBinder');
register(PatternConstantBinder, 'PatternConstantBinder');
register(SourceExpressionBinder, 'SourceExpressionBinder');
register(PatternCompositeBinder, 'PatternCompositeBinder');
register(CompositeExpressionBinder, 'CompositeExpressionBinder');
register(ProgramConfiguration, 'ProgramConfiguration', { omit: ['_buffers'] });
register(ProgramConfigurationSet, 'ProgramConfigurationSet');

//      
/**
 * A `LngLatBounds` object represents a geographical bounding box,
 * defined by its southwest and northeast points in longitude and latitude.
 *
 * If no arguments are provided to the constructor, a `null` bounding box is created.
 *
 * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option
 * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion.
 * This flexible type is documented as {@link LngLatBoundsLike}.
 *
 * @param {LngLatLike} [sw] The southwest corner of the bounding box.
 * @param {LngLatLike} [ne] The northeast corner of the bounding box.
 * @example
 * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);
 * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);
 * const llb = new mapboxgl.LngLatBounds(sw, ne);
 */
class LngLatBounds {
    // This constructor is too flexible to type. It should not be so flexible.
    constructor(sw, ne) {
        if (!sw) ; else if (ne) {
            this.setSouthWest(sw).setNorthEast(ne);
        } else if (sw.length === 4) {
            this.setSouthWest([
                sw[0],
                sw[1]
            ]).setNorthEast([
                sw[2],
                sw[3]
            ]);
        } else {
            this.setSouthWest(sw[0]).setNorthEast(sw[1]);
        }
    }
    /**
     * Set the northeast corner of the bounding box.
     *
     * @param {LngLatLike} ne A {@link LngLatLike} object describing the northeast corner of the bounding box.
     * @returns {LngLatBounds} Returns itself to allow for method chaining.
     * @example
     * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);
     * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);
     * const llb = new mapboxgl.LngLatBounds(sw, ne);
     * llb.setNorthEast([-73.9397, 42.8002]);
     */
    setNorthEast(ne) {
        this._ne = ne instanceof LngLat$1 ? new LngLat$1(ne.lng, ne.lat) : LngLat$1.convert(ne);
        return this;
    }
    /**
     * Set the southwest corner of the bounding box.
     *
     * @param {LngLatLike} sw A {@link LngLatLike} object describing the southwest corner of the bounding box.
     * @returns {LngLatBounds} Returns itself to allow for method chaining.
     * @example
     * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);
     * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);
     * const llb = new mapboxgl.LngLatBounds(sw, ne);
     * llb.setSouthWest([-73.9876, 40.2661]);
     */
    setSouthWest(sw) {
        this._sw = sw instanceof LngLat$1 ? new LngLat$1(sw.lng, sw.lat) : LngLat$1.convert(sw);
        return this;
    }
    /**
     * Extend the bounds to include a given LngLatLike or LngLatBoundsLike.
     *
     * @param {LngLatLike|LngLatBoundsLike} obj Object to extend to.
     * @returns {LngLatBounds} Returns itself to allow for method chaining.
     * @example
     * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);
     * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);
     * const llb = new mapboxgl.LngLatBounds(sw, ne);
     * llb.extend([-72.9876, 42.2661]);
     */
    extend(obj) {
        const sw = this._sw, ne = this._ne;
        let sw2, ne2;
        if (obj instanceof LngLat$1) {
            sw2 = obj;
            ne2 = obj;
        } else if (obj instanceof LngLatBounds) {
            sw2 = obj._sw;
            ne2 = obj._ne;
            if (!sw2 || !ne2)
                return this;
        } else if (Array.isArray(obj)) {
            // $FlowFixMe[method-unbinding]
            if (obj.length === 4 || obj.every(Array.isArray)) {
                const lngLatBoundsObj = obj;
                return this.extend(LngLatBounds.convert(lngLatBoundsObj));
            } else {
                const lngLatObj = obj;
                return this.extend(LngLat$1.convert(lngLatObj));
            }
        } else if (typeof obj === 'object' && obj !== null && obj.hasOwnProperty('lat') && (obj.hasOwnProperty('lon') || obj.hasOwnProperty('lng'))) {
            return this.extend(LngLat$1.convert(obj));
        } else {
            return this;
        }
        if (!sw && !ne) {
            this._sw = new LngLat$1(sw2.lng, sw2.lat);
            this._ne = new LngLat$1(ne2.lng, ne2.lat);
        } else {
            sw.lng = Math.min(sw2.lng, sw.lng);
            sw.lat = Math.min(sw2.lat, sw.lat);
            ne.lng = Math.max(ne2.lng, ne.lng);
            ne.lat = Math.max(ne2.lat, ne.lat);
        }
        return this;
    }
    /**
     * Returns the geographical coordinate equidistant from the bounding box's corners.
     *
     * @returns {LngLat} The bounding box's center.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}
     */
    getCenter() {
        return new LngLat$1((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);
    }
    /**
     * Returns the southwest corner of the bounding box.
     *
     * @returns {LngLat} The southwest corner of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getSouthWest(); // LngLat {lng: -73.9876, lat: 40.7661}
     */
    getSouthWest() {
        return this._sw;
    }
    /**
     * Returns the northeast corner of the bounding box.
     *
     * @returns {LngLat} The northeast corner of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getNorthEast(); // LngLat {lng: -73.9397, lat: 40.8002}
     */
    getNorthEast() {
        return this._ne;
    }
    /**
     * Returns the northwest corner of the bounding box.
     *
     * @returns {LngLat} The northwest corner of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getNorthWest(); // LngLat {lng: -73.9876, lat: 40.8002}
     */
    getNorthWest() {
        return new LngLat$1(this.getWest(), this.getNorth());
    }
    /**
     * Returns the southeast corner of the bounding box.
     *
     * @returns {LngLat} The southeast corner of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getSouthEast(); // LngLat {lng: -73.9397, lat: 40.7661}
     */
    getSouthEast() {
        return new LngLat$1(this.getEast(), this.getSouth());
    }
    /**
     * Returns the west edge of the bounding box.
     *
     * @returns {number} The west edge of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getWest(); // -73.9876
     */
    getWest() {
        return this._sw.lng;
    }
    /**
     * Returns the south edge of the bounding box.
     *
     * @returns {number} The south edge of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getSouth(); // 40.7661
     */
    getSouth() {
        return this._sw.lat;
    }
    /**
     * Returns the east edge of the bounding box.
     *
     * @returns {number} The east edge of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getEast(); // -73.9397
     */
    getEast() {
        return this._ne.lng;
    }
    /**
     * Returns the north edge of the bounding box.
     *
     * @returns {number} The north edge of the bounding box.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.getNorth(); // 40.8002
     */
    getNorth() {
        return this._ne.lat;
    }
    /**
     * Returns the bounding box represented as an array.
     *
     * @returns {Array<Array<number>>} The bounding box represented as an array, consisting of the
     *     southwest and northeast coordinates of the bounding represented as arrays of numbers.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]
     */
    toArray() {
        return [
            this._sw.toArray(),
            this._ne.toArray()
        ];
    }
    /**
     * Return the bounding box represented as a string.
     *
     * @returns {string} The bounding box represents as a string of the format
     *     `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`.
     * @example
     * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
     * llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))"
     */
    toString() {
        return `LngLatBounds(${ this._sw.toString() }, ${ this._ne.toString() })`;
    }
    /**
     * Check if the bounding box is an empty/`null`-type box.
     *
     * @returns {boolean} True if bounds have been defined, otherwise false.
     * @example
     * const llb = new mapboxgl.LngLatBounds();
     * llb.isEmpty(); // true
     * llb.setNorthEast([-73.9876, 40.7661]);
     * llb.setSouthWest([-73.9397, 40.8002]);
     * llb.isEmpty(); // false
     */
    isEmpty() {
        return !(this._sw && this._ne);
    }
    /**
    * Check if the point is within the bounding box.
    *
    * @param {LngLatLike} lnglat Geographic point to check against.
    * @returns {boolean} True if the point is within the bounding box.
    * @example
    * const llb = new mapboxgl.LngLatBounds(
    *   new mapboxgl.LngLat(-73.9876, 40.7661),
    *   new mapboxgl.LngLat(-73.9397, 40.8002)
    * );
    *
    * const ll = new mapboxgl.LngLat(-73.9567, 40.7789);
    *
    * console.log(llb.contains(ll)); // = true
    */
    contains(lnglat) {
        const {lng, lat} = LngLat$1.convert(lnglat);
        const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;
        let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;
        if (this._sw.lng > this._ne.lng) {
            // wrapped coordinates
            containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;
        }
        return containsLatitude && containsLongitude;
    }
    /**
     * Converts an array to a `LngLatBounds` object.
     *
     * If a `LngLatBounds` object is passed in, the function returns it unchanged.
     *
     * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values.
     *
     * @param {LngLatBoundsLike} input An array of two coordinates to convert, or a `LngLatBounds` object to return.
     * @returns {LngLatBounds} A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object.
     * @example
     * const arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
     * const llb = mapboxgl.LngLatBounds.convert(arr);
     * console.log(llb);   // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}
     */
    static convert(input) {
        if (!input || input instanceof LngLatBounds)
            return input;
        return new LngLatBounds(input);
    }
}

var cjs = {};

var common = {};

Object.defineProperty(common, '__esModule', { value: true });
common.setMatrixArrayType = setMatrixArrayType;
common.toRadian = toRadian;
common.equals = equals$a;
common.RANDOM = common.ARRAY_TYPE = common.EPSILON = void 0;
/**
 * Common utilities
 * @module glMatrix
 */
// Configuration Constants
var EPSILON = 0.000001;
common.EPSILON = EPSILON;
var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
common.ARRAY_TYPE = ARRAY_TYPE;
var RANDOM = Math.random;
/**
 * Sets the type of array used when creating new vectors and matrices
 *
 * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array
 */
common.RANDOM = RANDOM;
function setMatrixArrayType(type) {
    common.ARRAY_TYPE = ARRAY_TYPE = type;
}
var degree = Math.PI / 180;
/**
 * Convert Degree To Radian
 *
 * @param {Number} a Angle in Degrees
 */
function toRadian(a) {
    return a * degree;
}
/**
 * Tests whether or not the arguments have approximately the same value, within an absolute
 * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
 * than or equal to 1.0, and a relative tolerance is used for larger values)
 *
 * @param {Number} a The first number to test.
 * @param {Number} b The second number to test.
 * @returns {Boolean} True if the numbers are approximately equal, false otherwise.
 */
function equals$a(a, b) {
    return Math.abs(a - b) <= EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
}
if (!Math.hypot)
    Math.hypot = function () {
        var y = 0, i = arguments.length;
        while (i--) {
            y += arguments[i] * arguments[i];
        }
        return Math.sqrt(y);
    };

var mat2$1 = {};

function _typeof$9(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$9 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$9 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$9(obj);
}
Object.defineProperty(mat2$1, '__esModule', { value: true });
mat2$1.create = create$9;
mat2$1.clone = clone$8;
mat2$1.copy = copy$8;
mat2$1.identity = identity$6;
mat2$1.fromValues = fromValues$8;
mat2$1.set = set$8;
mat2$1.transpose = transpose$2;
mat2$1.invert = invert$5;
mat2$1.adjoint = adjoint$2;
mat2$1.determinant = determinant$3;
mat2$1.multiply = multiply$8;
mat2$1.rotate = rotate$5;
mat2$1.scale = scale$8;
mat2$1.fromRotation = fromRotation$4;
mat2$1.fromScaling = fromScaling$3;
mat2$1.str = str$8;
mat2$1.frob = frob$3;
mat2$1.LDU = LDU;
mat2$1.add = add$8;
mat2$1.subtract = subtract$6;
mat2$1.exactEquals = exactEquals$8;
mat2$1.equals = equals$9;
mat2$1.multiplyScalar = multiplyScalar$3;
mat2$1.multiplyScalarAndAdd = multiplyScalarAndAdd$3;
mat2$1.sub = mat2$1.mul = void 0;
var glMatrix$9 = _interopRequireWildcard$9(common);
function _getRequireWildcardCache$9(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$9 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$9(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$9(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$9(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 2x2 Matrix
 * @module mat2
 */
/**
 * Creates a new identity mat2
 *
 * @returns {mat2} a new 2x2 matrix
 */
function create$9() {
    var out = new glMatrix$9.ARRAY_TYPE(4);
    if (glMatrix$9.ARRAY_TYPE != Float32Array) {
        out[1] = 0;
        out[2] = 0;
    }
    out[0] = 1;
    out[3] = 1;
    return out;
}
/**
 * Creates a new mat2 initialized with values from an existing matrix
 *
 * @param {ReadonlyMat2} a matrix to clone
 * @returns {mat2} a new 2x2 matrix
 */
function clone$8(a) {
    var out = new glMatrix$9.ARRAY_TYPE(4);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    return out;
}
/**
 * Copy the values from one mat2 to another
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the source matrix
 * @returns {mat2} out
 */
function copy$8(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    return out;
}
/**
 * Set a mat2 to the identity matrix
 *
 * @param {mat2} out the receiving matrix
 * @returns {mat2} out
 */
function identity$6(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    return out;
}
/**
 * Create a new mat2 with the given values
 *
 * @param {Number} m00 Component in column 0, row 0 position (index 0)
 * @param {Number} m01 Component in column 0, row 1 position (index 1)
 * @param {Number} m10 Component in column 1, row 0 position (index 2)
 * @param {Number} m11 Component in column 1, row 1 position (index 3)
 * @returns {mat2} out A new 2x2 matrix
 */
function fromValues$8(m00, m01, m10, m11) {
    var out = new glMatrix$9.ARRAY_TYPE(4);
    out[0] = m00;
    out[1] = m01;
    out[2] = m10;
    out[3] = m11;
    return out;
}
/**
 * Set the components of a mat2 to the given values
 *
 * @param {mat2} out the receiving matrix
 * @param {Number} m00 Component in column 0, row 0 position (index 0)
 * @param {Number} m01 Component in column 0, row 1 position (index 1)
 * @param {Number} m10 Component in column 1, row 0 position (index 2)
 * @param {Number} m11 Component in column 1, row 1 position (index 3)
 * @returns {mat2} out
 */
function set$8(out, m00, m01, m10, m11) {
    out[0] = m00;
    out[1] = m01;
    out[2] = m10;
    out[3] = m11;
    return out;
}
/**
 * Transpose the values of a mat2
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the source matrix
 * @returns {mat2} out
 */
function transpose$2(out, a) {
    // If we are transposing ourselves we can skip a few steps but have to cache
    // some values
    if (out === a) {
        var a1 = a[1];
        out[1] = a[2];
        out[2] = a1;
    } else {
        out[0] = a[0];
        out[1] = a[2];
        out[2] = a[1];
        out[3] = a[3];
    }
    return out;
}
/**
 * Inverts a mat2
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the source matrix
 * @returns {mat2} out
 */
function invert$5(out, a) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    // Calculate the determinant
    var det = a0 * a3 - a2 * a1;
    if (!det) {
        return null;
    }
    det = 1 / det;
    out[0] = a3 * det;
    out[1] = -a1 * det;
    out[2] = -a2 * det;
    out[3] = a0 * det;
    return out;
}
/**
 * Calculates the adjugate of a mat2
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the source matrix
 * @returns {mat2} out
 */
function adjoint$2(out, a) {
    // Caching this value is nessecary if out == a
    var a0 = a[0];
    out[0] = a[3];
    out[1] = -a[1];
    out[2] = -a[2];
    out[3] = a0;
    return out;
}
/**
 * Calculates the determinant of a mat2
 *
 * @param {ReadonlyMat2} a the source matrix
 * @returns {Number} determinant of a
 */
function determinant$3(a) {
    return a[0] * a[3] - a[2] * a[1];
}
/**
 * Multiplies two mat2's
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the first operand
 * @param {ReadonlyMat2} b the second operand
 * @returns {mat2} out
 */
function multiply$8(out, a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
    out[0] = a0 * b0 + a2 * b1;
    out[1] = a1 * b0 + a3 * b1;
    out[2] = a0 * b2 + a2 * b3;
    out[3] = a1 * b2 + a3 * b3;
    return out;
}
/**
 * Rotates a mat2 by the given angle
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat2} out
 */
function rotate$5(out, a, rad) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    out[0] = a0 * c + a2 * s;
    out[1] = a1 * c + a3 * s;
    out[2] = a0 * -s + a2 * c;
    out[3] = a1 * -s + a3 * c;
    return out;
}
/**
 * Scales the mat2 by the dimensions in the given vec2
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the matrix to rotate
 * @param {ReadonlyVec2} v the vec2 to scale the matrix by
 * @returns {mat2} out
 **/
function scale$8(out, a, v) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var v0 = v[0], v1 = v[1];
    out[0] = a0 * v0;
    out[1] = a1 * v0;
    out[2] = a2 * v1;
    out[3] = a3 * v1;
    return out;
}
/**
 * Creates a matrix from a given angle
 * This is equivalent to (but much faster than):
 *
 *     mat2.identity(dest);
 *     mat2.rotate(dest, dest, rad);
 *
 * @param {mat2} out mat2 receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat2} out
 */
function fromRotation$4(out, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    out[0] = c;
    out[1] = s;
    out[2] = -s;
    out[3] = c;
    return out;
}
/**
 * Creates a matrix from a vector scaling
 * This is equivalent to (but much faster than):
 *
 *     mat2.identity(dest);
 *     mat2.scale(dest, dest, vec);
 *
 * @param {mat2} out mat2 receiving operation result
 * @param {ReadonlyVec2} v Scaling vector
 * @returns {mat2} out
 */
function fromScaling$3(out, v) {
    out[0] = v[0];
    out[1] = 0;
    out[2] = 0;
    out[3] = v[1];
    return out;
}
/**
 * Returns a string representation of a mat2
 *
 * @param {ReadonlyMat2} a matrix to represent as a string
 * @returns {String} string representation of the matrix
 */
function str$8(a) {
    return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
}
/**
 * Returns Frobenius norm of a mat2
 *
 * @param {ReadonlyMat2} a the matrix to calculate Frobenius norm of
 * @returns {Number} Frobenius norm
 */
function frob$3(a) {
    return Math.hypot(a[0], a[1], a[2], a[3]);
}
/**
 * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix
 * @param {ReadonlyMat2} L the lower triangular matrix
 * @param {ReadonlyMat2} D the diagonal matrix
 * @param {ReadonlyMat2} U the upper triangular matrix
 * @param {ReadonlyMat2} a the input matrix to factorize
 */
function LDU(L, D, U, a) {
    L[2] = a[2] / a[0];
    U[0] = a[0];
    U[1] = a[1];
    U[3] = a[3] - L[2] * U[1];
    return [
        L,
        D,
        U
    ];
}
/**
 * Adds two mat2's
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the first operand
 * @param {ReadonlyMat2} b the second operand
 * @returns {mat2} out
 */
function add$8(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    return out;
}
/**
 * Subtracts matrix b from matrix a
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the first operand
 * @param {ReadonlyMat2} b the second operand
 * @returns {mat2} out
 */
function subtract$6(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
    out[3] = a[3] - b[3];
    return out;
}
/**
 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyMat2} a The first matrix.
 * @param {ReadonlyMat2} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function exactEquals$8(a, b) {
    return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
}
/**
 * Returns whether or not the matrices have approximately the same elements in the same position.
 *
 * @param {ReadonlyMat2} a The first matrix.
 * @param {ReadonlyMat2} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function equals$9(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
    return Math.abs(a0 - b0) <= glMatrix$9.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$9.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$9.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix$9.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3));
}
/**
 * Multiply each element of the matrix by a scalar.
 *
 * @param {mat2} out the receiving matrix
 * @param {ReadonlyMat2} a the matrix to scale
 * @param {Number} b amount to scale the matrix's elements by
 * @returns {mat2} out
 */
function multiplyScalar$3(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    out[3] = a[3] * b;
    return out;
}
/**
 * Adds two mat2's after multiplying each element of the second operand by a scalar value.
 *
 * @param {mat2} out the receiving vector
 * @param {ReadonlyMat2} a the first operand
 * @param {ReadonlyMat2} b the second operand
 * @param {Number} scale the amount to scale b's elements by before adding
 * @returns {mat2} out
 */
function multiplyScalarAndAdd$3(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    out[2] = a[2] + b[2] * scale;
    out[3] = a[3] + b[3] * scale;
    return out;
}
/**
 * Alias for {@link mat2.multiply}
 * @function
 */
var mul$8 = multiply$8;
/**
 * Alias for {@link mat2.subtract}
 * @function
 */
mat2$1.mul = mul$8;
var sub$6 = subtract$6;
mat2$1.sub = sub$6;

var mat2d$1 = {};

function _typeof$8(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$8 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$8 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$8(obj);
}
Object.defineProperty(mat2d$1, '__esModule', { value: true });
mat2d$1.create = create$8;
mat2d$1.clone = clone$7;
mat2d$1.copy = copy$7;
mat2d$1.identity = identity$5;
mat2d$1.fromValues = fromValues$7;
mat2d$1.set = set$7;
mat2d$1.invert = invert$4;
mat2d$1.determinant = determinant$2;
mat2d$1.multiply = multiply$7;
mat2d$1.rotate = rotate$4;
mat2d$1.scale = scale$7;
mat2d$1.translate = translate$4;
mat2d$1.fromRotation = fromRotation$3;
mat2d$1.fromScaling = fromScaling$2;
mat2d$1.fromTranslation = fromTranslation$3;
mat2d$1.str = str$7;
mat2d$1.frob = frob$2;
mat2d$1.add = add$7;
mat2d$1.subtract = subtract$5;
mat2d$1.multiplyScalar = multiplyScalar$2;
mat2d$1.multiplyScalarAndAdd = multiplyScalarAndAdd$2;
mat2d$1.exactEquals = exactEquals$7;
mat2d$1.equals = equals$8;
mat2d$1.sub = mat2d$1.mul = void 0;
var glMatrix$8 = _interopRequireWildcard$8(common);
function _getRequireWildcardCache$8(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$8 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$8(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$8(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$8(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 2x3 Matrix
 * @module mat2d
 * @description
 * A mat2d contains six elements defined as:
 * <pre>
 * [a, b,
 *  c, d,
 *  tx, ty]
 * </pre>
 * This is a short form for the 3x3 matrix:
 * <pre>
 * [a, b, 0,
 *  c, d, 0,
 *  tx, ty, 1]
 * </pre>
 * The last column is ignored so the array is shorter and operations are faster.
 */
/**
 * Creates a new identity mat2d
 *
 * @returns {mat2d} a new 2x3 matrix
 */
function create$8() {
    var out = new glMatrix$8.ARRAY_TYPE(6);
    if (glMatrix$8.ARRAY_TYPE != Float32Array) {
        out[1] = 0;
        out[2] = 0;
        out[4] = 0;
        out[5] = 0;
    }
    out[0] = 1;
    out[3] = 1;
    return out;
}
/**
 * Creates a new mat2d initialized with values from an existing matrix
 *
 * @param {ReadonlyMat2d} a matrix to clone
 * @returns {mat2d} a new 2x3 matrix
 */
function clone$7(a) {
    var out = new glMatrix$8.ARRAY_TYPE(6);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    return out;
}
/**
 * Copy the values from one mat2d to another
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the source matrix
 * @returns {mat2d} out
 */
function copy$7(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    return out;
}
/**
 * Set a mat2d to the identity matrix
 *
 * @param {mat2d} out the receiving matrix
 * @returns {mat2d} out
 */
function identity$5(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    out[4] = 0;
    out[5] = 0;
    return out;
}
/**
 * Create a new mat2d with the given values
 *
 * @param {Number} a Component A (index 0)
 * @param {Number} b Component B (index 1)
 * @param {Number} c Component C (index 2)
 * @param {Number} d Component D (index 3)
 * @param {Number} tx Component TX (index 4)
 * @param {Number} ty Component TY (index 5)
 * @returns {mat2d} A new mat2d
 */
function fromValues$7(a, b, c, d, tx, ty) {
    var out = new glMatrix$8.ARRAY_TYPE(6);
    out[0] = a;
    out[1] = b;
    out[2] = c;
    out[3] = d;
    out[4] = tx;
    out[5] = ty;
    return out;
}
/**
 * Set the components of a mat2d to the given values
 *
 * @param {mat2d} out the receiving matrix
 * @param {Number} a Component A (index 0)
 * @param {Number} b Component B (index 1)
 * @param {Number} c Component C (index 2)
 * @param {Number} d Component D (index 3)
 * @param {Number} tx Component TX (index 4)
 * @param {Number} ty Component TY (index 5)
 * @returns {mat2d} out
 */
function set$7(out, a, b, c, d, tx, ty) {
    out[0] = a;
    out[1] = b;
    out[2] = c;
    out[3] = d;
    out[4] = tx;
    out[5] = ty;
    return out;
}
/**
 * Inverts a mat2d
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the source matrix
 * @returns {mat2d} out
 */
function invert$4(out, a) {
    var aa = a[0], ab = a[1], ac = a[2], ad = a[3];
    var atx = a[4], aty = a[5];
    var det = aa * ad - ab * ac;
    if (!det) {
        return null;
    }
    det = 1 / det;
    out[0] = ad * det;
    out[1] = -ab * det;
    out[2] = -ac * det;
    out[3] = aa * det;
    out[4] = (ac * aty - ad * atx) * det;
    out[5] = (ab * atx - aa * aty) * det;
    return out;
}
/**
 * Calculates the determinant of a mat2d
 *
 * @param {ReadonlyMat2d} a the source matrix
 * @returns {Number} determinant of a
 */
function determinant$2(a) {
    return a[0] * a[3] - a[1] * a[2];
}
/**
 * Multiplies two mat2d's
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the first operand
 * @param {ReadonlyMat2d} b the second operand
 * @returns {mat2d} out
 */
function multiply$7(out, a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5];
    out[0] = a0 * b0 + a2 * b1;
    out[1] = a1 * b0 + a3 * b1;
    out[2] = a0 * b2 + a2 * b3;
    out[3] = a1 * b2 + a3 * b3;
    out[4] = a0 * b4 + a2 * b5 + a4;
    out[5] = a1 * b4 + a3 * b5 + a5;
    return out;
}
/**
 * Rotates a mat2d by the given angle
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat2d} out
 */
function rotate$4(out, a, rad) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5];
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    out[0] = a0 * c + a2 * s;
    out[1] = a1 * c + a3 * s;
    out[2] = a0 * -s + a2 * c;
    out[3] = a1 * -s + a3 * c;
    out[4] = a4;
    out[5] = a5;
    return out;
}
/**
 * Scales the mat2d by the dimensions in the given vec2
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the matrix to translate
 * @param {ReadonlyVec2} v the vec2 to scale the matrix by
 * @returns {mat2d} out
 **/
function scale$7(out, a, v) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5];
    var v0 = v[0], v1 = v[1];
    out[0] = a0 * v0;
    out[1] = a1 * v0;
    out[2] = a2 * v1;
    out[3] = a3 * v1;
    out[4] = a4;
    out[5] = a5;
    return out;
}
/**
 * Translates the mat2d by the dimensions in the given vec2
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the matrix to translate
 * @param {ReadonlyVec2} v the vec2 to translate the matrix by
 * @returns {mat2d} out
 **/
function translate$4(out, a, v) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5];
    var v0 = v[0], v1 = v[1];
    out[0] = a0;
    out[1] = a1;
    out[2] = a2;
    out[3] = a3;
    out[4] = a0 * v0 + a2 * v1 + a4;
    out[5] = a1 * v0 + a3 * v1 + a5;
    return out;
}
/**
 * Creates a matrix from a given angle
 * This is equivalent to (but much faster than):
 *
 *     mat2d.identity(dest);
 *     mat2d.rotate(dest, dest, rad);
 *
 * @param {mat2d} out mat2d receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat2d} out
 */
function fromRotation$3(out, rad) {
    var s = Math.sin(rad), c = Math.cos(rad);
    out[0] = c;
    out[1] = s;
    out[2] = -s;
    out[3] = c;
    out[4] = 0;
    out[5] = 0;
    return out;
}
/**
 * Creates a matrix from a vector scaling
 * This is equivalent to (but much faster than):
 *
 *     mat2d.identity(dest);
 *     mat2d.scale(dest, dest, vec);
 *
 * @param {mat2d} out mat2d receiving operation result
 * @param {ReadonlyVec2} v Scaling vector
 * @returns {mat2d} out
 */
function fromScaling$2(out, v) {
    out[0] = v[0];
    out[1] = 0;
    out[2] = 0;
    out[3] = v[1];
    out[4] = 0;
    out[5] = 0;
    return out;
}
/**
 * Creates a matrix from a vector translation
 * This is equivalent to (but much faster than):
 *
 *     mat2d.identity(dest);
 *     mat2d.translate(dest, dest, vec);
 *
 * @param {mat2d} out mat2d receiving operation result
 * @param {ReadonlyVec2} v Translation vector
 * @returns {mat2d} out
 */
function fromTranslation$3(out, v) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    out[4] = v[0];
    out[5] = v[1];
    return out;
}
/**
 * Returns a string representation of a mat2d
 *
 * @param {ReadonlyMat2d} a matrix to represent as a string
 * @returns {String} string representation of the matrix
 */
function str$7(a) {
    return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ')';
}
/**
 * Returns Frobenius norm of a mat2d
 *
 * @param {ReadonlyMat2d} a the matrix to calculate Frobenius norm of
 * @returns {Number} Frobenius norm
 */
function frob$2(a) {
    return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], 1);
}
/**
 * Adds two mat2d's
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the first operand
 * @param {ReadonlyMat2d} b the second operand
 * @returns {mat2d} out
 */
function add$7(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    out[4] = a[4] + b[4];
    out[5] = a[5] + b[5];
    return out;
}
/**
 * Subtracts matrix b from matrix a
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the first operand
 * @param {ReadonlyMat2d} b the second operand
 * @returns {mat2d} out
 */
function subtract$5(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
    out[3] = a[3] - b[3];
    out[4] = a[4] - b[4];
    out[5] = a[5] - b[5];
    return out;
}
/**
 * Multiply each element of the matrix by a scalar.
 *
 * @param {mat2d} out the receiving matrix
 * @param {ReadonlyMat2d} a the matrix to scale
 * @param {Number} b amount to scale the matrix's elements by
 * @returns {mat2d} out
 */
function multiplyScalar$2(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    out[3] = a[3] * b;
    out[4] = a[4] * b;
    out[5] = a[5] * b;
    return out;
}
/**
 * Adds two mat2d's after multiplying each element of the second operand by a scalar value.
 *
 * @param {mat2d} out the receiving vector
 * @param {ReadonlyMat2d} a the first operand
 * @param {ReadonlyMat2d} b the second operand
 * @param {Number} scale the amount to scale b's elements by before adding
 * @returns {mat2d} out
 */
function multiplyScalarAndAdd$2(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    out[2] = a[2] + b[2] * scale;
    out[3] = a[3] + b[3] * scale;
    out[4] = a[4] + b[4] * scale;
    out[5] = a[5] + b[5] * scale;
    return out;
}
/**
 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyMat2d} a The first matrix.
 * @param {ReadonlyMat2d} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function exactEquals$7(a, b) {
    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];
}
/**
 * Returns whether or not the matrices have approximately the same elements in the same position.
 *
 * @param {ReadonlyMat2d} a The first matrix.
 * @param {ReadonlyMat2d} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function equals$8(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5];
    return Math.abs(a0 - b0) <= glMatrix$8.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$8.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$8.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix$8.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix$8.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix$8.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5));
}
/**
 * Alias for {@link mat2d.multiply}
 * @function
 */
var mul$7 = multiply$7;
/**
 * Alias for {@link mat2d.subtract}
 * @function
 */
mat2d$1.mul = mul$7;
var sub$5 = subtract$5;
mat2d$1.sub = sub$5;

var mat3$2 = {};

function _typeof$7(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$7 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$7 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$7(obj);
}
Object.defineProperty(mat3$2, '__esModule', { value: true });
mat3$2.create = create$7;
mat3$2.fromMat4 = fromMat4$1;
mat3$2.clone = clone$6;
mat3$2.copy = copy$6;
mat3$2.fromValues = fromValues$6;
mat3$2.set = set$6;
mat3$2.identity = identity$4;
mat3$2.transpose = transpose$1;
mat3$2.invert = invert$3;
mat3$2.adjoint = adjoint$1;
mat3$2.determinant = determinant$1;
mat3$2.multiply = multiply$6;
mat3$2.translate = translate$3;
mat3$2.rotate = rotate$3;
mat3$2.scale = scale$6;
mat3$2.fromTranslation = fromTranslation$2;
mat3$2.fromRotation = fromRotation$2;
mat3$2.fromScaling = fromScaling$1;
mat3$2.fromMat2d = fromMat2d;
mat3$2.fromQuat = fromQuat$1;
mat3$2.normalFromMat4 = normalFromMat4;
mat3$2.projection = projection;
mat3$2.str = str$6;
mat3$2.frob = frob$1;
mat3$2.add = add$6;
mat3$2.subtract = subtract$4;
mat3$2.multiplyScalar = multiplyScalar$1;
mat3$2.multiplyScalarAndAdd = multiplyScalarAndAdd$1;
mat3$2.exactEquals = exactEquals$6;
mat3$2.equals = equals$7;
mat3$2.sub = mat3$2.mul = void 0;
var glMatrix$7 = _interopRequireWildcard$7(common);
function _getRequireWildcardCache$7(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$7 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$7(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$7(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$7(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 3x3 Matrix
 * @module mat3
 */
/**
 * Creates a new identity mat3
 *
 * @returns {mat3} a new 3x3 matrix
 */
function create$7() {
    var out = new glMatrix$7.ARRAY_TYPE(9);
    if (glMatrix$7.ARRAY_TYPE != Float32Array) {
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[5] = 0;
        out[6] = 0;
        out[7] = 0;
    }
    out[0] = 1;
    out[4] = 1;
    out[8] = 1;
    return out;
}
/**
 * Copies the upper-left 3x3 values into the given mat3.
 *
 * @param {mat3} out the receiving 3x3 matrix
 * @param {ReadonlyMat4} a   the source 4x4 matrix
 * @returns {mat3} out
 */
function fromMat4$1(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[4];
    out[4] = a[5];
    out[5] = a[6];
    out[6] = a[8];
    out[7] = a[9];
    out[8] = a[10];
    return out;
}
/**
 * Creates a new mat3 initialized with values from an existing matrix
 *
 * @param {ReadonlyMat3} a matrix to clone
 * @returns {mat3} a new 3x3 matrix
 */
function clone$6(a) {
    var out = new glMatrix$7.ARRAY_TYPE(9);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    return out;
}
/**
 * Copy the values from one mat3 to another
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the source matrix
 * @returns {mat3} out
 */
function copy$6(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    return out;
}
/**
 * Create a new mat3 with the given values
 *
 * @param {Number} m00 Component in column 0, row 0 position (index 0)
 * @param {Number} m01 Component in column 0, row 1 position (index 1)
 * @param {Number} m02 Component in column 0, row 2 position (index 2)
 * @param {Number} m10 Component in column 1, row 0 position (index 3)
 * @param {Number} m11 Component in column 1, row 1 position (index 4)
 * @param {Number} m12 Component in column 1, row 2 position (index 5)
 * @param {Number} m20 Component in column 2, row 0 position (index 6)
 * @param {Number} m21 Component in column 2, row 1 position (index 7)
 * @param {Number} m22 Component in column 2, row 2 position (index 8)
 * @returns {mat3} A new mat3
 */
function fromValues$6(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
    var out = new glMatrix$7.ARRAY_TYPE(9);
    out[0] = m00;
    out[1] = m01;
    out[2] = m02;
    out[3] = m10;
    out[4] = m11;
    out[5] = m12;
    out[6] = m20;
    out[7] = m21;
    out[8] = m22;
    return out;
}
/**
 * Set the components of a mat3 to the given values
 *
 * @param {mat3} out the receiving matrix
 * @param {Number} m00 Component in column 0, row 0 position (index 0)
 * @param {Number} m01 Component in column 0, row 1 position (index 1)
 * @param {Number} m02 Component in column 0, row 2 position (index 2)
 * @param {Number} m10 Component in column 1, row 0 position (index 3)
 * @param {Number} m11 Component in column 1, row 1 position (index 4)
 * @param {Number} m12 Component in column 1, row 2 position (index 5)
 * @param {Number} m20 Component in column 2, row 0 position (index 6)
 * @param {Number} m21 Component in column 2, row 1 position (index 7)
 * @param {Number} m22 Component in column 2, row 2 position (index 8)
 * @returns {mat3} out
 */
function set$6(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {
    out[0] = m00;
    out[1] = m01;
    out[2] = m02;
    out[3] = m10;
    out[4] = m11;
    out[5] = m12;
    out[6] = m20;
    out[7] = m21;
    out[8] = m22;
    return out;
}
/**
 * Set a mat3 to the identity matrix
 *
 * @param {mat3} out the receiving matrix
 * @returns {mat3} out
 */
function identity$4(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 1;
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
    out[8] = 1;
    return out;
}
/**
 * Transpose the values of a mat3
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the source matrix
 * @returns {mat3} out
 */
function transpose$1(out, a) {
    // If we are transposing ourselves we can skip a few steps but have to cache some values
    if (out === a) {
        var a01 = a[1], a02 = a[2], a12 = a[5];
        out[1] = a[3];
        out[2] = a[6];
        out[3] = a01;
        out[5] = a[7];
        out[6] = a02;
        out[7] = a12;
    } else {
        out[0] = a[0];
        out[1] = a[3];
        out[2] = a[6];
        out[3] = a[1];
        out[4] = a[4];
        out[5] = a[7];
        out[6] = a[2];
        out[7] = a[5];
        out[8] = a[8];
    }
    return out;
}
/**
 * Inverts a mat3
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the source matrix
 * @returns {mat3} out
 */
function invert$3(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2];
    var a10 = a[3], a11 = a[4], a12 = a[5];
    var a20 = a[6], a21 = a[7], a22 = a[8];
    var b01 = a22 * a11 - a12 * a21;
    var b11 = -a22 * a10 + a12 * a20;
    var b21 = a21 * a10 - a11 * a20;
    // Calculate the determinant
    var det = a00 * b01 + a01 * b11 + a02 * b21;
    if (!det) {
        return null;
    }
    det = 1 / det;
    out[0] = b01 * det;
    out[1] = (-a22 * a01 + a02 * a21) * det;
    out[2] = (a12 * a01 - a02 * a11) * det;
    out[3] = b11 * det;
    out[4] = (a22 * a00 - a02 * a20) * det;
    out[5] = (-a12 * a00 + a02 * a10) * det;
    out[6] = b21 * det;
    out[7] = (-a21 * a00 + a01 * a20) * det;
    out[8] = (a11 * a00 - a01 * a10) * det;
    return out;
}
/**
 * Calculates the adjugate of a mat3
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the source matrix
 * @returns {mat3} out
 */
function adjoint$1(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2];
    var a10 = a[3], a11 = a[4], a12 = a[5];
    var a20 = a[6], a21 = a[7], a22 = a[8];
    out[0] = a11 * a22 - a12 * a21;
    out[1] = a02 * a21 - a01 * a22;
    out[2] = a01 * a12 - a02 * a11;
    out[3] = a12 * a20 - a10 * a22;
    out[4] = a00 * a22 - a02 * a20;
    out[5] = a02 * a10 - a00 * a12;
    out[6] = a10 * a21 - a11 * a20;
    out[7] = a01 * a20 - a00 * a21;
    out[8] = a00 * a11 - a01 * a10;
    return out;
}
/**
 * Calculates the determinant of a mat3
 *
 * @param {ReadonlyMat3} a the source matrix
 * @returns {Number} determinant of a
 */
function determinant$1(a) {
    var a00 = a[0], a01 = a[1], a02 = a[2];
    var a10 = a[3], a11 = a[4], a12 = a[5];
    var a20 = a[6], a21 = a[7], a22 = a[8];
    return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
}
/**
 * Multiplies two mat3's
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the first operand
 * @param {ReadonlyMat3} b the second operand
 * @returns {mat3} out
 */
function multiply$6(out, a, b) {
    var a00 = a[0], a01 = a[1], a02 = a[2];
    var a10 = a[3], a11 = a[4], a12 = a[5];
    var a20 = a[6], a21 = a[7], a22 = a[8];
    var b00 = b[0], b01 = b[1], b02 = b[2];
    var b10 = b[3], b11 = b[4], b12 = b[5];
    var b20 = b[6], b21 = b[7], b22 = b[8];
    out[0] = b00 * a00 + b01 * a10 + b02 * a20;
    out[1] = b00 * a01 + b01 * a11 + b02 * a21;
    out[2] = b00 * a02 + b01 * a12 + b02 * a22;
    out[3] = b10 * a00 + b11 * a10 + b12 * a20;
    out[4] = b10 * a01 + b11 * a11 + b12 * a21;
    out[5] = b10 * a02 + b11 * a12 + b12 * a22;
    out[6] = b20 * a00 + b21 * a10 + b22 * a20;
    out[7] = b20 * a01 + b21 * a11 + b22 * a21;
    out[8] = b20 * a02 + b21 * a12 + b22 * a22;
    return out;
}
/**
 * Translate a mat3 by the given vector
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to translate
 * @param {ReadonlyVec2} v vector to translate by
 * @returns {mat3} out
 */
function translate$3(out, a, v) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], x = v[0], y = v[1];
    out[0] = a00;
    out[1] = a01;
    out[2] = a02;
    out[3] = a10;
    out[4] = a11;
    out[5] = a12;
    out[6] = x * a00 + y * a10 + a20;
    out[7] = x * a01 + y * a11 + a21;
    out[8] = x * a02 + y * a12 + a22;
    return out;
}
/**
 * Rotates a mat3 by the given angle
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat3} out
 */
function rotate$3(out, a, rad) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], s = Math.sin(rad), c = Math.cos(rad);
    out[0] = c * a00 + s * a10;
    out[1] = c * a01 + s * a11;
    out[2] = c * a02 + s * a12;
    out[3] = c * a10 - s * a00;
    out[4] = c * a11 - s * a01;
    out[5] = c * a12 - s * a02;
    out[6] = a20;
    out[7] = a21;
    out[8] = a22;
    return out;
}
/**
 * Scales the mat3 by the dimensions in the given vec2
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to rotate
 * @param {ReadonlyVec2} v the vec2 to scale the matrix by
 * @returns {mat3} out
 **/
function scale$6(out, a, v) {
    var x = v[0], y = v[1];
    out[0] = x * a[0];
    out[1] = x * a[1];
    out[2] = x * a[2];
    out[3] = y * a[3];
    out[4] = y * a[4];
    out[5] = y * a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    return out;
}
/**
 * Creates a matrix from a vector translation
 * This is equivalent to (but much faster than):
 *
 *     mat3.identity(dest);
 *     mat3.translate(dest, dest, vec);
 *
 * @param {mat3} out mat3 receiving operation result
 * @param {ReadonlyVec2} v Translation vector
 * @returns {mat3} out
 */
function fromTranslation$2(out, v) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 1;
    out[5] = 0;
    out[6] = v[0];
    out[7] = v[1];
    out[8] = 1;
    return out;
}
/**
 * Creates a matrix from a given angle
 * This is equivalent to (but much faster than):
 *
 *     mat3.identity(dest);
 *     mat3.rotate(dest, dest, rad);
 *
 * @param {mat3} out mat3 receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat3} out
 */
function fromRotation$2(out, rad) {
    var s = Math.sin(rad), c = Math.cos(rad);
    out[0] = c;
    out[1] = s;
    out[2] = 0;
    out[3] = -s;
    out[4] = c;
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
    out[8] = 1;
    return out;
}
/**
 * Creates a matrix from a vector scaling
 * This is equivalent to (but much faster than):
 *
 *     mat3.identity(dest);
 *     mat3.scale(dest, dest, vec);
 *
 * @param {mat3} out mat3 receiving operation result
 * @param {ReadonlyVec2} v Scaling vector
 * @returns {mat3} out
 */
function fromScaling$1(out, v) {
    out[0] = v[0];
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = v[1];
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
    out[8] = 1;
    return out;
}
/**
 * Copies the values from a mat2d into a mat3
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat2d} a the matrix to copy
 * @returns {mat3} out
 **/
function fromMat2d(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = 0;
    out[3] = a[2];
    out[4] = a[3];
    out[5] = 0;
    out[6] = a[4];
    out[7] = a[5];
    out[8] = 1;
    return out;
}
/**
 * Calculates a 3x3 matrix from the given quaternion
 *
 * @param {mat3} out mat3 receiving operation result
 * @param {ReadonlyQuat} q Quaternion to create matrix from
 *
 * @returns {mat3} out
 */
function fromQuat$1(out, q) {
    var x = q[0], y = q[1], z = q[2], w = q[3];
    var x2 = x + x;
    var y2 = y + y;
    var z2 = z + z;
    var xx = x * x2;
    var yx = y * x2;
    var yy = y * y2;
    var zx = z * x2;
    var zy = z * y2;
    var zz = z * z2;
    var wx = w * x2;
    var wy = w * y2;
    var wz = w * z2;
    out[0] = 1 - yy - zz;
    out[3] = yx - wz;
    out[6] = zx + wy;
    out[1] = yx + wz;
    out[4] = 1 - xx - zz;
    out[7] = zy - wx;
    out[2] = zx - wy;
    out[5] = zy + wx;
    out[8] = 1 - xx - yy;
    return out;
}
/**
 * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix
 *
 * @param {mat3} out mat3 receiving operation result
 * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from
 *
 * @returns {mat3} out
 */
function normalFromMat4(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
    var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
    var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
    var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
    var b00 = a00 * a11 - a01 * a10;
    var b01 = a00 * a12 - a02 * a10;
    var b02 = a00 * a13 - a03 * a10;
    var b03 = a01 * a12 - a02 * a11;
    var b04 = a01 * a13 - a03 * a11;
    var b05 = a02 * a13 - a03 * a12;
    var b06 = a20 * a31 - a21 * a30;
    var b07 = a20 * a32 - a22 * a30;
    var b08 = a20 * a33 - a23 * a30;
    var b09 = a21 * a32 - a22 * a31;
    var b10 = a21 * a33 - a23 * a31;
    var b11 = a22 * a33 - a23 * a32;
    // Calculate the determinant
    var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
    if (!det) {
        return null;
    }
    det = 1 / det;
    out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
    out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
    out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
    out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
    out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
    out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
    out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
    out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
    out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
    return out;
}
/**
 * Generates a 2D projection matrix with the given bounds
 *
 * @param {mat3} out mat3 frustum matrix will be written into
 * @param {number} width Width of your gl context
 * @param {number} height Height of gl context
 * @returns {mat3} out
 */
function projection(out, width, height) {
    out[0] = 2 / width;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = -2 / height;
    out[5] = 0;
    out[6] = -1;
    out[7] = 1;
    out[8] = 1;
    return out;
}
/**
 * Returns a string representation of a mat3
 *
 * @param {ReadonlyMat3} a matrix to represent as a string
 * @returns {String} string representation of the matrix
 */
function str$6(a) {
    return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ')';
}
/**
 * Returns Frobenius norm of a mat3
 *
 * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of
 * @returns {Number} Frobenius norm
 */
function frob$1(a) {
    return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
}
/**
 * Adds two mat3's
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the first operand
 * @param {ReadonlyMat3} b the second operand
 * @returns {mat3} out
 */
function add$6(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    out[4] = a[4] + b[4];
    out[5] = a[5] + b[5];
    out[6] = a[6] + b[6];
    out[7] = a[7] + b[7];
    out[8] = a[8] + b[8];
    return out;
}
/**
 * Subtracts matrix b from matrix a
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the first operand
 * @param {ReadonlyMat3} b the second operand
 * @returns {mat3} out
 */
function subtract$4(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
    out[3] = a[3] - b[3];
    out[4] = a[4] - b[4];
    out[5] = a[5] - b[5];
    out[6] = a[6] - b[6];
    out[7] = a[7] - b[7];
    out[8] = a[8] - b[8];
    return out;
}
/**
 * Multiply each element of the matrix by a scalar.
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to scale
 * @param {Number} b amount to scale the matrix's elements by
 * @returns {mat3} out
 */
function multiplyScalar$1(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    out[3] = a[3] * b;
    out[4] = a[4] * b;
    out[5] = a[5] * b;
    out[6] = a[6] * b;
    out[7] = a[7] * b;
    out[8] = a[8] * b;
    return out;
}
/**
 * Adds two mat3's after multiplying each element of the second operand by a scalar value.
 *
 * @param {mat3} out the receiving vector
 * @param {ReadonlyMat3} a the first operand
 * @param {ReadonlyMat3} b the second operand
 * @param {Number} scale the amount to scale b's elements by before adding
 * @returns {mat3} out
 */
function multiplyScalarAndAdd$1(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    out[2] = a[2] + b[2] * scale;
    out[3] = a[3] + b[3] * scale;
    out[4] = a[4] + b[4] * scale;
    out[5] = a[5] + b[5] * scale;
    out[6] = a[6] + b[6] * scale;
    out[7] = a[7] + b[7] * scale;
    out[8] = a[8] + b[8] * scale;
    return out;
}
/**
 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyMat3} a The first matrix.
 * @param {ReadonlyMat3} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function exactEquals$6(a, b) {
    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];
}
/**
 * Returns whether or not the matrices have approximately the same elements in the same position.
 *
 * @param {ReadonlyMat3} a The first matrix.
 * @param {ReadonlyMat3} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function equals$7(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7], a8 = a[8];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8];
    return Math.abs(a0 - b0) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix$7.EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8));
}
/**
 * Alias for {@link mat3.multiply}
 * @function
 */
var mul$6 = multiply$6;
/**
 * Alias for {@link mat3.subtract}
 * @function
 */
mat3$2.mul = mul$6;
var sub$4 = subtract$4;
mat3$2.sub = sub$4;

var mat4$2 = {};

function _typeof$6(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$6 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$6 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$6(obj);
}
Object.defineProperty(mat4$2, '__esModule', { value: true });
mat4$2.create = create$6;
mat4$2.clone = clone$5;
mat4$2.copy = copy$5;
mat4$2.fromValues = fromValues$5;
mat4$2.set = set$5;
mat4$2.identity = identity$3;
mat4$2.transpose = transpose;
mat4$2.invert = invert$2;
mat4$2.adjoint = adjoint;
mat4$2.determinant = determinant;
mat4$2.multiply = multiply$5;
mat4$2.translate = translate$2;
mat4$2.scale = scale$5;
mat4$2.rotate = rotate$2;
mat4$2.rotateX = rotateX$3;
mat4$2.rotateY = rotateY$3;
mat4$2.rotateZ = rotateZ$3;
mat4$2.fromTranslation = fromTranslation$1;
mat4$2.fromScaling = fromScaling;
mat4$2.fromRotation = fromRotation$1;
mat4$2.fromXRotation = fromXRotation;
mat4$2.fromYRotation = fromYRotation;
mat4$2.fromZRotation = fromZRotation;
mat4$2.fromRotationTranslation = fromRotationTranslation$1;
mat4$2.fromQuat2 = fromQuat2;
mat4$2.getTranslation = getTranslation$1;
mat4$2.getScaling = getScaling;
mat4$2.getRotation = getRotation;
mat4$2.fromRotationTranslationScale = fromRotationTranslationScale;
mat4$2.fromRotationTranslationScaleOrigin = fromRotationTranslationScaleOrigin;
mat4$2.fromQuat = fromQuat;
mat4$2.frustum = frustum;
mat4$2.perspectiveNO = perspectiveNO;
mat4$2.perspectiveZO = perspectiveZO;
mat4$2.perspectiveFromFieldOfView = perspectiveFromFieldOfView;
mat4$2.orthoNO = orthoNO;
mat4$2.orthoZO = orthoZO;
mat4$2.lookAt = lookAt;
mat4$2.targetTo = targetTo;
mat4$2.str = str$5;
mat4$2.frob = frob;
mat4$2.add = add$5;
mat4$2.subtract = subtract$3;
mat4$2.multiplyScalar = multiplyScalar;
mat4$2.multiplyScalarAndAdd = multiplyScalarAndAdd;
mat4$2.exactEquals = exactEquals$5;
mat4$2.equals = equals$6;
mat4$2.sub = mat4$2.mul = mat4$2.ortho = mat4$2.perspective = void 0;
var glMatrix$6 = _interopRequireWildcard$6(common);
function _getRequireWildcardCache$6(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$6 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$6(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$6(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$6(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.
 * @module mat4
 */
/**
 * Creates a new identity mat4
 *
 * @returns {mat4} a new 4x4 matrix
 */
function create$6() {
    var out = new glMatrix$6.ARRAY_TYPE(16);
    if (glMatrix$6.ARRAY_TYPE != Float32Array) {
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
    }
    out[0] = 1;
    out[5] = 1;
    out[10] = 1;
    out[15] = 1;
    return out;
}
/**
 * Creates a new mat4 initialized with values from an existing matrix
 *
 * @param {ReadonlyMat4} a matrix to clone
 * @returns {mat4} a new 4x4 matrix
 */
function clone$5(a) {
    var out = new glMatrix$6.ARRAY_TYPE(16);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    out[9] = a[9];
    out[10] = a[10];
    out[11] = a[11];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
}
/**
 * Copy the values from one mat4 to another
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the source matrix
 * @returns {mat4} out
 */
function copy$5(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[8] = a[8];
    out[9] = a[9];
    out[10] = a[10];
    out[11] = a[11];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
}
/**
 * Create a new mat4 with the given values
 *
 * @param {Number} m00 Component in column 0, row 0 position (index 0)
 * @param {Number} m01 Component in column 0, row 1 position (index 1)
 * @param {Number} m02 Component in column 0, row 2 position (index 2)
 * @param {Number} m03 Component in column 0, row 3 position (index 3)
 * @param {Number} m10 Component in column 1, row 0 position (index 4)
 * @param {Number} m11 Component in column 1, row 1 position (index 5)
 * @param {Number} m12 Component in column 1, row 2 position (index 6)
 * @param {Number} m13 Component in column 1, row 3 position (index 7)
 * @param {Number} m20 Component in column 2, row 0 position (index 8)
 * @param {Number} m21 Component in column 2, row 1 position (index 9)
 * @param {Number} m22 Component in column 2, row 2 position (index 10)
 * @param {Number} m23 Component in column 2, row 3 position (index 11)
 * @param {Number} m30 Component in column 3, row 0 position (index 12)
 * @param {Number} m31 Component in column 3, row 1 position (index 13)
 * @param {Number} m32 Component in column 3, row 2 position (index 14)
 * @param {Number} m33 Component in column 3, row 3 position (index 15)
 * @returns {mat4} A new mat4
 */
function fromValues$5(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
    var out = new glMatrix$6.ARRAY_TYPE(16);
    out[0] = m00;
    out[1] = m01;
    out[2] = m02;
    out[3] = m03;
    out[4] = m10;
    out[5] = m11;
    out[6] = m12;
    out[7] = m13;
    out[8] = m20;
    out[9] = m21;
    out[10] = m22;
    out[11] = m23;
    out[12] = m30;
    out[13] = m31;
    out[14] = m32;
    out[15] = m33;
    return out;
}
/**
 * Set the components of a mat4 to the given values
 *
 * @param {mat4} out the receiving matrix
 * @param {Number} m00 Component in column 0, row 0 position (index 0)
 * @param {Number} m01 Component in column 0, row 1 position (index 1)
 * @param {Number} m02 Component in column 0, row 2 position (index 2)
 * @param {Number} m03 Component in column 0, row 3 position (index 3)
 * @param {Number} m10 Component in column 1, row 0 position (index 4)
 * @param {Number} m11 Component in column 1, row 1 position (index 5)
 * @param {Number} m12 Component in column 1, row 2 position (index 6)
 * @param {Number} m13 Component in column 1, row 3 position (index 7)
 * @param {Number} m20 Component in column 2, row 0 position (index 8)
 * @param {Number} m21 Component in column 2, row 1 position (index 9)
 * @param {Number} m22 Component in column 2, row 2 position (index 10)
 * @param {Number} m23 Component in column 2, row 3 position (index 11)
 * @param {Number} m30 Component in column 3, row 0 position (index 12)
 * @param {Number} m31 Component in column 3, row 1 position (index 13)
 * @param {Number} m32 Component in column 3, row 2 position (index 14)
 * @param {Number} m33 Component in column 3, row 3 position (index 15)
 * @returns {mat4} out
 */
function set$5(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
    out[0] = m00;
    out[1] = m01;
    out[2] = m02;
    out[3] = m03;
    out[4] = m10;
    out[5] = m11;
    out[6] = m12;
    out[7] = m13;
    out[8] = m20;
    out[9] = m21;
    out[10] = m22;
    out[11] = m23;
    out[12] = m30;
    out[13] = m31;
    out[14] = m32;
    out[15] = m33;
    return out;
}
/**
 * Set a mat4 to the identity matrix
 *
 * @param {mat4} out the receiving matrix
 * @returns {mat4} out
 */
function identity$3(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Transpose the values of a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the source matrix
 * @returns {mat4} out
 */
function transpose(out, a) {
    // If we are transposing ourselves we can skip a few steps but have to cache some values
    if (out === a) {
        var a01 = a[1], a02 = a[2], a03 = a[3];
        var a12 = a[6], a13 = a[7];
        var a23 = a[11];
        out[1] = a[4];
        out[2] = a[8];
        out[3] = a[12];
        out[4] = a01;
        out[6] = a[9];
        out[7] = a[13];
        out[8] = a02;
        out[9] = a12;
        out[11] = a[14];
        out[12] = a03;
        out[13] = a13;
        out[14] = a23;
    } else {
        out[0] = a[0];
        out[1] = a[4];
        out[2] = a[8];
        out[3] = a[12];
        out[4] = a[1];
        out[5] = a[5];
        out[6] = a[9];
        out[7] = a[13];
        out[8] = a[2];
        out[9] = a[6];
        out[10] = a[10];
        out[11] = a[14];
        out[12] = a[3];
        out[13] = a[7];
        out[14] = a[11];
        out[15] = a[15];
    }
    return out;
}
/**
 * Inverts a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the source matrix
 * @returns {mat4} out
 */
function invert$2(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
    var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
    var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
    var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
    var b00 = a00 * a11 - a01 * a10;
    var b01 = a00 * a12 - a02 * a10;
    var b02 = a00 * a13 - a03 * a10;
    var b03 = a01 * a12 - a02 * a11;
    var b04 = a01 * a13 - a03 * a11;
    var b05 = a02 * a13 - a03 * a12;
    var b06 = a20 * a31 - a21 * a30;
    var b07 = a20 * a32 - a22 * a30;
    var b08 = a20 * a33 - a23 * a30;
    var b09 = a21 * a32 - a22 * a31;
    var b10 = a21 * a33 - a23 * a31;
    var b11 = a22 * a33 - a23 * a32;
    // Calculate the determinant
    var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
    if (!det) {
        return null;
    }
    det = 1 / det;
    out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
    out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
    out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
    out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
    out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
    out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
    out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
    out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
    out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
    out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
    out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
    out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
    out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
    out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
    out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
    out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
    return out;
}
/**
 * Calculates the adjugate of a mat4
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the source matrix
 * @returns {mat4} out
 */
function adjoint(out, a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
    var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
    var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
    var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
    out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
    out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
    out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
    out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
    out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
    out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
    out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
    out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
    out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
    out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
    out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
    out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
    out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
    out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
    out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
    out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
    return out;
}
/**
 * Calculates the determinant of a mat4
 *
 * @param {ReadonlyMat4} a the source matrix
 * @returns {Number} determinant of a
 */
function determinant(a) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
    var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
    var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
    var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
    var b00 = a00 * a11 - a01 * a10;
    var b01 = a00 * a12 - a02 * a10;
    var b02 = a00 * a13 - a03 * a10;
    var b03 = a01 * a12 - a02 * a11;
    var b04 = a01 * a13 - a03 * a11;
    var b05 = a02 * a13 - a03 * a12;
    var b06 = a20 * a31 - a21 * a30;
    var b07 = a20 * a32 - a22 * a30;
    var b08 = a20 * a33 - a23 * a30;
    var b09 = a21 * a32 - a22 * a31;
    var b10 = a21 * a33 - a23 * a31;
    var b11 = a22 * a33 - a23 * a32;
    // Calculate the determinant
    return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
}
/**
 * Multiplies two mat4s
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the first operand
 * @param {ReadonlyMat4} b the second operand
 * @returns {mat4} out
 */
function multiply$5(out, a, b) {
    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
    var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
    var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
    var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
    // Cache only the current line of the second matrix
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
    out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
    out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
    out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
    out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
    b0 = b[4];
    b1 = b[5];
    b2 = b[6];
    b3 = b[7];
    out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
    out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
    out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
    out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
    b0 = b[8];
    b1 = b[9];
    b2 = b[10];
    b3 = b[11];
    out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
    out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
    out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
    out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
    b0 = b[12];
    b1 = b[13];
    b2 = b[14];
    b3 = b[15];
    out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
    out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
    out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
    out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
    return out;
}
/**
 * Translate a mat4 by the given vector
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to translate
 * @param {ReadonlyVec3} v vector to translate by
 * @returns {mat4} out
 */
function translate$2(out, a, v) {
    var x = v[0], y = v[1], z = v[2];
    var a00, a01, a02, a03;
    var a10, a11, a12, a13;
    var a20, a21, a22, a23;
    if (a === out) {
        out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
        out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
        out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
        out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
    } else {
        a00 = a[0];
        a01 = a[1];
        a02 = a[2];
        a03 = a[3];
        a10 = a[4];
        a11 = a[5];
        a12 = a[6];
        a13 = a[7];
        a20 = a[8];
        a21 = a[9];
        a22 = a[10];
        a23 = a[11];
        out[0] = a00;
        out[1] = a01;
        out[2] = a02;
        out[3] = a03;
        out[4] = a10;
        out[5] = a11;
        out[6] = a12;
        out[7] = a13;
        out[8] = a20;
        out[9] = a21;
        out[10] = a22;
        out[11] = a23;
        out[12] = a00 * x + a10 * y + a20 * z + a[12];
        out[13] = a01 * x + a11 * y + a21 * z + a[13];
        out[14] = a02 * x + a12 * y + a22 * z + a[14];
        out[15] = a03 * x + a13 * y + a23 * z + a[15];
    }
    return out;
}
/**
 * Scales the mat4 by the dimensions in the given vec3 not using vectorization
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to scale
 * @param {ReadonlyVec3} v the vec3 to scale the matrix by
 * @returns {mat4} out
 **/
function scale$5(out, a, v) {
    var x = v[0], y = v[1], z = v[2];
    out[0] = a[0] * x;
    out[1] = a[1] * x;
    out[2] = a[2] * x;
    out[3] = a[3] * x;
    out[4] = a[4] * y;
    out[5] = a[5] * y;
    out[6] = a[6] * y;
    out[7] = a[7] * y;
    out[8] = a[8] * z;
    out[9] = a[9] * z;
    out[10] = a[10] * z;
    out[11] = a[11] * z;
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
    return out;
}
/**
 * Rotates a mat4 by the given angle around the given axis
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @param {ReadonlyVec3} axis the axis to rotate around
 * @returns {mat4} out
 */
function rotate$2(out, a, rad, axis) {
    var x = axis[0], y = axis[1], z = axis[2];
    var len = Math.hypot(x, y, z);
    var s, c, t;
    var a00, a01, a02, a03;
    var a10, a11, a12, a13;
    var a20, a21, a22, a23;
    var b00, b01, b02;
    var b10, b11, b12;
    var b20, b21, b22;
    if (len < glMatrix$6.EPSILON) {
        return null;
    }
    len = 1 / len;
    x *= len;
    y *= len;
    z *= len;
    s = Math.sin(rad);
    c = Math.cos(rad);
    t = 1 - c;
    a00 = a[0];
    a01 = a[1];
    a02 = a[2];
    a03 = a[3];
    a10 = a[4];
    a11 = a[5];
    a12 = a[6];
    a13 = a[7];
    a20 = a[8];
    a21 = a[9];
    a22 = a[10];
    a23 = a[11];
    // Construct the elements of the rotation matrix
    b00 = x * x * t + c;
    b01 = y * x * t + z * s;
    b02 = z * x * t - y * s;
    b10 = x * y * t - z * s;
    b11 = y * y * t + c;
    b12 = z * y * t + x * s;
    b20 = x * z * t + y * s;
    b21 = y * z * t - x * s;
    b22 = z * z * t + c;
    // Perform rotation-specific matrix multiplication
    out[0] = a00 * b00 + a10 * b01 + a20 * b02;
    out[1] = a01 * b00 + a11 * b01 + a21 * b02;
    out[2] = a02 * b00 + a12 * b01 + a22 * b02;
    out[3] = a03 * b00 + a13 * b01 + a23 * b02;
    out[4] = a00 * b10 + a10 * b11 + a20 * b12;
    out[5] = a01 * b10 + a11 * b11 + a21 * b12;
    out[6] = a02 * b10 + a12 * b11 + a22 * b12;
    out[7] = a03 * b10 + a13 * b11 + a23 * b12;
    out[8] = a00 * b20 + a10 * b21 + a20 * b22;
    out[9] = a01 * b20 + a11 * b21 + a21 * b22;
    out[10] = a02 * b20 + a12 * b21 + a22 * b22;
    out[11] = a03 * b20 + a13 * b21 + a23 * b22;
    if (a !== out) {
        // If the source and destination differ, copy the unchanged last row
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }
    return out;
}
/**
 * Rotates a matrix by the given angle around the X axis
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateX$3(out, a, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    var a10 = a[4];
    var a11 = a[5];
    var a12 = a[6];
    var a13 = a[7];
    var a20 = a[8];
    var a21 = a[9];
    var a22 = a[10];
    var a23 = a[11];
    if (a !== out) {
        // If the source and destination differ, copy the unchanged rows
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }
    // Perform axis-specific matrix multiplication
    out[4] = a10 * c + a20 * s;
    out[5] = a11 * c + a21 * s;
    out[6] = a12 * c + a22 * s;
    out[7] = a13 * c + a23 * s;
    out[8] = a20 * c - a10 * s;
    out[9] = a21 * c - a11 * s;
    out[10] = a22 * c - a12 * s;
    out[11] = a23 * c - a13 * s;
    return out;
}
/**
 * Rotates a matrix by the given angle around the Y axis
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateY$3(out, a, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    var a00 = a[0];
    var a01 = a[1];
    var a02 = a[2];
    var a03 = a[3];
    var a20 = a[8];
    var a21 = a[9];
    var a22 = a[10];
    var a23 = a[11];
    if (a !== out) {
        // If the source and destination differ, copy the unchanged rows
        out[4] = a[4];
        out[5] = a[5];
        out[6] = a[6];
        out[7] = a[7];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }
    // Perform axis-specific matrix multiplication
    out[0] = a00 * c - a20 * s;
    out[1] = a01 * c - a21 * s;
    out[2] = a02 * c - a22 * s;
    out[3] = a03 * c - a23 * s;
    out[8] = a00 * s + a20 * c;
    out[9] = a01 * s + a21 * c;
    out[10] = a02 * s + a22 * c;
    out[11] = a03 * s + a23 * c;
    return out;
}
/**
 * Rotates a matrix by the given angle around the Z axis
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function rotateZ$3(out, a, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    var a00 = a[0];
    var a01 = a[1];
    var a02 = a[2];
    var a03 = a[3];
    var a10 = a[4];
    var a11 = a[5];
    var a12 = a[6];
    var a13 = a[7];
    if (a !== out) {
        // If the source and destination differ, copy the unchanged last row
        out[8] = a[8];
        out[9] = a[9];
        out[10] = a[10];
        out[11] = a[11];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
    }
    // Perform axis-specific matrix multiplication
    out[0] = a00 * c + a10 * s;
    out[1] = a01 * c + a11 * s;
    out[2] = a02 * c + a12 * s;
    out[3] = a03 * c + a13 * s;
    out[4] = a10 * c - a00 * s;
    out[5] = a11 * c - a01 * s;
    out[6] = a12 * c - a02 * s;
    out[7] = a13 * c - a03 * s;
    return out;
}
/**
 * Creates a matrix from a vector translation
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.translate(dest, dest, vec);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {ReadonlyVec3} v Translation vector
 * @returns {mat4} out
 */
function fromTranslation$1(out, v) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = v[0];
    out[13] = v[1];
    out[14] = v[2];
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from a vector scaling
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.scale(dest, dest, vec);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {ReadonlyVec3} v Scaling vector
 * @returns {mat4} out
 */
function fromScaling(out, v) {
    out[0] = v[0];
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = v[1];
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = v[2];
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from a given angle around a given axis
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.rotate(dest, dest, rad, axis);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @param {ReadonlyVec3} axis the axis to rotate around
 * @returns {mat4} out
 */
function fromRotation$1(out, rad, axis) {
    var x = axis[0], y = axis[1], z = axis[2];
    var len = Math.hypot(x, y, z);
    var s, c, t;
    if (len < glMatrix$6.EPSILON) {
        return null;
    }
    len = 1 / len;
    x *= len;
    y *= len;
    z *= len;
    s = Math.sin(rad);
    c = Math.cos(rad);
    t = 1 - c;
    // Perform rotation-specific matrix multiplication
    out[0] = x * x * t + c;
    out[1] = y * x * t + z * s;
    out[2] = z * x * t - y * s;
    out[3] = 0;
    out[4] = x * y * t - z * s;
    out[5] = y * y * t + c;
    out[6] = z * y * t + x * s;
    out[7] = 0;
    out[8] = x * z * t + y * s;
    out[9] = y * z * t - x * s;
    out[10] = z * z * t + c;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from the given angle around the X axis
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.rotateX(dest, dest, rad);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function fromXRotation(out, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    // Perform axis-specific matrix multiplication
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = c;
    out[6] = s;
    out[7] = 0;
    out[8] = 0;
    out[9] = -s;
    out[10] = c;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from the given angle around the Y axis
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.rotateY(dest, dest, rad);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function fromYRotation(out, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    // Perform axis-specific matrix multiplication
    out[0] = c;
    out[1] = 0;
    out[2] = -s;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = s;
    out[9] = 0;
    out[10] = c;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from the given angle around the Z axis
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.rotateZ(dest, dest, rad);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat4} out
 */
function fromZRotation(out, rad) {
    var s = Math.sin(rad);
    var c = Math.cos(rad);
    // Perform axis-specific matrix multiplication
    out[0] = c;
    out[1] = s;
    out[2] = 0;
    out[3] = 0;
    out[4] = -s;
    out[5] = c;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from a quaternion rotation and vector translation
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.translate(dest, vec);
 *     let quatMat = mat4.create();
 *     quat4.toMat4(quat, quatMat);
 *     mat4.multiply(dest, quatMat);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @param {ReadonlyVec3} v Translation vector
 * @returns {mat4} out
 */
function fromRotationTranslation$1(out, q, v) {
    // Quaternion math
    var x = q[0], y = q[1], z = q[2], w = q[3];
    var x2 = x + x;
    var y2 = y + y;
    var z2 = z + z;
    var xx = x * x2;
    var xy = x * y2;
    var xz = x * z2;
    var yy = y * y2;
    var yz = y * z2;
    var zz = z * z2;
    var wx = w * x2;
    var wy = w * y2;
    var wz = w * z2;
    out[0] = 1 - (yy + zz);
    out[1] = xy + wz;
    out[2] = xz - wy;
    out[3] = 0;
    out[4] = xy - wz;
    out[5] = 1 - (xx + zz);
    out[6] = yz + wx;
    out[7] = 0;
    out[8] = xz + wy;
    out[9] = yz - wx;
    out[10] = 1 - (xx + yy);
    out[11] = 0;
    out[12] = v[0];
    out[13] = v[1];
    out[14] = v[2];
    out[15] = 1;
    return out;
}
/**
 * Creates a new mat4 from a dual quat.
 *
 * @param {mat4} out Matrix
 * @param {ReadonlyQuat2} a Dual Quaternion
 * @returns {mat4} mat4 receiving operation result
 */
function fromQuat2(out, a) {
    var translation = new glMatrix$6.ARRAY_TYPE(3);
    var bx = -a[0], by = -a[1], bz = -a[2], bw = a[3], ax = a[4], ay = a[5], az = a[6], aw = a[7];
    var magnitude = bx * bx + by * by + bz * bz + bw * bw;
    //Only scale if it makes sense
    if (magnitude > 0) {
        translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;
        translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;
        translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;
    } else {
        translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
        translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
        translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
    }
    fromRotationTranslation$1(out, a, translation);
    return out;
}
/**
 * Returns the translation vector component of a transformation
 *  matrix. If a matrix is built with fromRotationTranslation,
 *  the returned vector will be the same as the translation vector
 *  originally supplied.
 * @param  {vec3} out Vector to receive translation component
 * @param  {ReadonlyMat4} mat Matrix to be decomposed (input)
 * @return {vec3} out
 */
function getTranslation$1(out, mat) {
    out[0] = mat[12];
    out[1] = mat[13];
    out[2] = mat[14];
    return out;
}
/**
 * Returns the scaling factor component of a transformation
 *  matrix. If a matrix is built with fromRotationTranslationScale
 *  with a normalized Quaternion paramter, the returned vector will be
 *  the same as the scaling vector
 *  originally supplied.
 * @param  {vec3} out Vector to receive scaling factor component
 * @param  {ReadonlyMat4} mat Matrix to be decomposed (input)
 * @return {vec3} out
 */
function getScaling(out, mat) {
    var m11 = mat[0];
    var m12 = mat[1];
    var m13 = mat[2];
    var m21 = mat[4];
    var m22 = mat[5];
    var m23 = mat[6];
    var m31 = mat[8];
    var m32 = mat[9];
    var m33 = mat[10];
    out[0] = Math.hypot(m11, m12, m13);
    out[1] = Math.hypot(m21, m22, m23);
    out[2] = Math.hypot(m31, m32, m33);
    return out;
}
/**
 * Returns a quaternion representing the rotational component
 *  of a transformation matrix. If a matrix is built with
 *  fromRotationTranslation, the returned quaternion will be the
 *  same as the quaternion originally supplied.
 * @param {quat} out Quaternion to receive the rotation component
 * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
 * @return {quat} out
 */
function getRotation(out, mat) {
    var scaling = new glMatrix$6.ARRAY_TYPE(3);
    getScaling(scaling, mat);
    var is1 = 1 / scaling[0];
    var is2 = 1 / scaling[1];
    var is3 = 1 / scaling[2];
    var sm11 = mat[0] * is1;
    var sm12 = mat[1] * is2;
    var sm13 = mat[2] * is3;
    var sm21 = mat[4] * is1;
    var sm22 = mat[5] * is2;
    var sm23 = mat[6] * is3;
    var sm31 = mat[8] * is1;
    var sm32 = mat[9] * is2;
    var sm33 = mat[10] * is3;
    var trace = sm11 + sm22 + sm33;
    var S = 0;
    if (trace > 0) {
        S = Math.sqrt(trace + 1) * 2;
        out[3] = 0.25 * S;
        out[0] = (sm23 - sm32) / S;
        out[1] = (sm31 - sm13) / S;
        out[2] = (sm12 - sm21) / S;
    } else if (sm11 > sm22 && sm11 > sm33) {
        S = Math.sqrt(1 + sm11 - sm22 - sm33) * 2;
        out[3] = (sm23 - sm32) / S;
        out[0] = 0.25 * S;
        out[1] = (sm12 + sm21) / S;
        out[2] = (sm31 + sm13) / S;
    } else if (sm22 > sm33) {
        S = Math.sqrt(1 + sm22 - sm11 - sm33) * 2;
        out[3] = (sm31 - sm13) / S;
        out[0] = (sm12 + sm21) / S;
        out[1] = 0.25 * S;
        out[2] = (sm23 + sm32) / S;
    } else {
        S = Math.sqrt(1 + sm33 - sm11 - sm22) * 2;
        out[3] = (sm12 - sm21) / S;
        out[0] = (sm31 + sm13) / S;
        out[1] = (sm23 + sm32) / S;
        out[2] = 0.25 * S;
    }
    return out;
}
/**
 * Creates a matrix from a quaternion rotation, vector translation and vector scale
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.translate(dest, vec);
 *     let quatMat = mat4.create();
 *     quat4.toMat4(quat, quatMat);
 *     mat4.multiply(dest, quatMat);
 *     mat4.scale(dest, scale)
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @param {ReadonlyVec3} v Translation vector
 * @param {ReadonlyVec3} s Scaling vector
 * @returns {mat4} out
 */
function fromRotationTranslationScale(out, q, v, s) {
    // Quaternion math
    var x = q[0], y = q[1], z = q[2], w = q[3];
    var x2 = x + x;
    var y2 = y + y;
    var z2 = z + z;
    var xx = x * x2;
    var xy = x * y2;
    var xz = x * z2;
    var yy = y * y2;
    var yz = y * z2;
    var zz = z * z2;
    var wx = w * x2;
    var wy = w * y2;
    var wz = w * z2;
    var sx = s[0];
    var sy = s[1];
    var sz = s[2];
    out[0] = (1 - (yy + zz)) * sx;
    out[1] = (xy + wz) * sx;
    out[2] = (xz - wy) * sx;
    out[3] = 0;
    out[4] = (xy - wz) * sy;
    out[5] = (1 - (xx + zz)) * sy;
    out[6] = (yz + wx) * sy;
    out[7] = 0;
    out[8] = (xz + wy) * sz;
    out[9] = (yz - wx) * sz;
    out[10] = (1 - (xx + yy)) * sz;
    out[11] = 0;
    out[12] = v[0];
    out[13] = v[1];
    out[14] = v[2];
    out[15] = 1;
    return out;
}
/**
 * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin
 * This is equivalent to (but much faster than):
 *
 *     mat4.identity(dest);
 *     mat4.translate(dest, vec);
 *     mat4.translate(dest, origin);
 *     let quatMat = mat4.create();
 *     quat4.toMat4(quat, quatMat);
 *     mat4.multiply(dest, quatMat);
 *     mat4.scale(dest, scale)
 *     mat4.translate(dest, negativeOrigin);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @param {ReadonlyVec3} v Translation vector
 * @param {ReadonlyVec3} s Scaling vector
 * @param {ReadonlyVec3} o The origin vector around which to scale and rotate
 * @returns {mat4} out
 */
function fromRotationTranslationScaleOrigin(out, q, v, s, o) {
    // Quaternion math
    var x = q[0], y = q[1], z = q[2], w = q[3];
    var x2 = x + x;
    var y2 = y + y;
    var z2 = z + z;
    var xx = x * x2;
    var xy = x * y2;
    var xz = x * z2;
    var yy = y * y2;
    var yz = y * z2;
    var zz = z * z2;
    var wx = w * x2;
    var wy = w * y2;
    var wz = w * z2;
    var sx = s[0];
    var sy = s[1];
    var sz = s[2];
    var ox = o[0];
    var oy = o[1];
    var oz = o[2];
    var out0 = (1 - (yy + zz)) * sx;
    var out1 = (xy + wz) * sx;
    var out2 = (xz - wy) * sx;
    var out4 = (xy - wz) * sy;
    var out5 = (1 - (xx + zz)) * sy;
    var out6 = (yz + wx) * sy;
    var out8 = (xz + wy) * sz;
    var out9 = (yz - wx) * sz;
    var out10 = (1 - (xx + yy)) * sz;
    out[0] = out0;
    out[1] = out1;
    out[2] = out2;
    out[3] = 0;
    out[4] = out4;
    out[5] = out5;
    out[6] = out6;
    out[7] = 0;
    out[8] = out8;
    out[9] = out9;
    out[10] = out10;
    out[11] = 0;
    out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
    out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
    out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
    out[15] = 1;
    return out;
}
/**
 * Calculates a 4x4 matrix from the given quaternion
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {ReadonlyQuat} q Quaternion to create matrix from
 *
 * @returns {mat4} out
 */
function fromQuat(out, q) {
    var x = q[0], y = q[1], z = q[2], w = q[3];
    var x2 = x + x;
    var y2 = y + y;
    var z2 = z + z;
    var xx = x * x2;
    var yx = y * x2;
    var yy = y * y2;
    var zx = z * x2;
    var zy = z * y2;
    var zz = z * z2;
    var wx = w * x2;
    var wy = w * y2;
    var wz = w * z2;
    out[0] = 1 - yy - zz;
    out[1] = yx + wz;
    out[2] = zx - wy;
    out[3] = 0;
    out[4] = yx - wz;
    out[5] = 1 - xx - zz;
    out[6] = zy + wx;
    out[7] = 0;
    out[8] = zx + wy;
    out[9] = zy - wx;
    out[10] = 1 - xx - yy;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;
    return out;
}
/**
 * Generates a frustum matrix with the given bounds
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {Number} left Left bound of the frustum
 * @param {Number} right Right bound of the frustum
 * @param {Number} bottom Bottom bound of the frustum
 * @param {Number} top Top bound of the frustum
 * @param {Number} near Near bound of the frustum
 * @param {Number} far Far bound of the frustum
 * @returns {mat4} out
 */
function frustum(out, left, right, bottom, top, near, far) {
    var rl = 1 / (right - left);
    var tb = 1 / (top - bottom);
    var nf = 1 / (near - far);
    out[0] = near * 2 * rl;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = near * 2 * tb;
    out[6] = 0;
    out[7] = 0;
    out[8] = (right + left) * rl;
    out[9] = (top + bottom) * tb;
    out[10] = (far + near) * nf;
    out[11] = -1;
    out[12] = 0;
    out[13] = 0;
    out[14] = far * near * 2 * nf;
    out[15] = 0;
    return out;
}
/**
 * Generates a perspective projection matrix with the given bounds.
 * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
 * which matches WebGL/OpenGL's clip volume.
 * Passing null/undefined/no value for far will generate infinite projection matrix.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} fovy Vertical field of view in radians
 * @param {number} aspect Aspect ratio. typically viewport width/height
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum, can be null or Infinity
 * @returns {mat4} out
 */
function perspectiveNO(out, fovy, aspect, near, far) {
    var f = 1 / Math.tan(fovy / 2), nf;
    out[0] = f / aspect;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = f;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[11] = -1;
    out[12] = 0;
    out[13] = 0;
    out[15] = 0;
    if (far != null && far !== Infinity) {
        nf = 1 / (near - far);
        out[10] = (far + near) * nf;
        out[14] = 2 * far * near * nf;
    } else {
        out[10] = -1;
        out[14] = -2 * near;
    }
    return out;
}
/**
 * Alias for {@link mat4.perspectiveNO}
 * @function
 */
var perspective = perspectiveNO;
/**
 * Generates a perspective projection matrix suitable for WebGPU with the given bounds.
 * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
 * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
 * Passing null/undefined/no value for far will generate infinite projection matrix.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} fovy Vertical field of view in radians
 * @param {number} aspect Aspect ratio. typically viewport width/height
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum, can be null or Infinity
 * @returns {mat4} out
 */
mat4$2.perspective = perspective;
function perspectiveZO(out, fovy, aspect, near, far) {
    var f = 1 / Math.tan(fovy / 2), nf;
    out[0] = f / aspect;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = f;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[11] = -1;
    out[12] = 0;
    out[13] = 0;
    out[15] = 0;
    if (far != null && far !== Infinity) {
        nf = 1 / (near - far);
        out[10] = far * nf;
        out[14] = far * near * nf;
    } else {
        out[10] = -1;
        out[14] = -near;
    }
    return out;
}
/**
 * Generates a perspective projection matrix with the given field of view.
 * This is primarily useful for generating projection matrices to be used
 * with the still experiemental WebVR API.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum
 * @returns {mat4} out
 */
function perspectiveFromFieldOfView(out, fov, near, far) {
    var upTan = Math.tan(fov.upDegrees * Math.PI / 180);
    var downTan = Math.tan(fov.downDegrees * Math.PI / 180);
    var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180);
    var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180);
    var xScale = 2 / (leftTan + rightTan);
    var yScale = 2 / (upTan + downTan);
    out[0] = xScale;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = yScale;
    out[6] = 0;
    out[7] = 0;
    out[8] = -((leftTan - rightTan) * xScale * 0.5);
    out[9] = (upTan - downTan) * yScale * 0.5;
    out[10] = far / (near - far);
    out[11] = -1;
    out[12] = 0;
    out[13] = 0;
    out[14] = far * near / (near - far);
    out[15] = 0;
    return out;
}
/**
 * Generates a orthogonal projection matrix with the given bounds.
 * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
 * which matches WebGL/OpenGL's clip volume.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} left Left bound of the frustum
 * @param {number} right Right bound of the frustum
 * @param {number} bottom Bottom bound of the frustum
 * @param {number} top Top bound of the frustum
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum
 * @returns {mat4} out
 */
function orthoNO(out, left, right, bottom, top, near, far) {
    var lr = 1 / (left - right);
    var bt = 1 / (bottom - top);
    var nf = 1 / (near - far);
    out[0] = -2 * lr;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = -2 * bt;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 2 * nf;
    out[11] = 0;
    out[12] = (left + right) * lr;
    out[13] = (top + bottom) * bt;
    out[14] = (far + near) * nf;
    out[15] = 1;
    return out;
}
/**
 * Alias for {@link mat4.orthoNO}
 * @function
 */
var ortho = orthoNO;
/**
 * Generates a orthogonal projection matrix with the given bounds.
 * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
 * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {number} left Left bound of the frustum
 * @param {number} right Right bound of the frustum
 * @param {number} bottom Bottom bound of the frustum
 * @param {number} top Top bound of the frustum
 * @param {number} near Near bound of the frustum
 * @param {number} far Far bound of the frustum
 * @returns {mat4} out
 */
mat4$2.ortho = ortho;
function orthoZO(out, left, right, bottom, top, near, far) {
    var lr = 1 / (left - right);
    var bt = 1 / (bottom - top);
    var nf = 1 / (near - far);
    out[0] = -2 * lr;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = -2 * bt;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = nf;
    out[11] = 0;
    out[12] = (left + right) * lr;
    out[13] = (top + bottom) * bt;
    out[14] = near * nf;
    out[15] = 1;
    return out;
}
/**
 * Generates a look-at matrix with the given eye position, focal point, and up axis.
 * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {ReadonlyVec3} eye Position of the viewer
 * @param {ReadonlyVec3} center Point the viewer is looking at
 * @param {ReadonlyVec3} up vec3 pointing up
 * @returns {mat4} out
 */
function lookAt(out, eye, center, up) {
    var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
    var eyex = eye[0];
    var eyey = eye[1];
    var eyez = eye[2];
    var upx = up[0];
    var upy = up[1];
    var upz = up[2];
    var centerx = center[0];
    var centery = center[1];
    var centerz = center[2];
    if (Math.abs(eyex - centerx) < glMatrix$6.EPSILON && Math.abs(eyey - centery) < glMatrix$6.EPSILON && Math.abs(eyez - centerz) < glMatrix$6.EPSILON) {
        return identity$3(out);
    }
    z0 = eyex - centerx;
    z1 = eyey - centery;
    z2 = eyez - centerz;
    len = 1 / Math.hypot(z0, z1, z2);
    z0 *= len;
    z1 *= len;
    z2 *= len;
    x0 = upy * z2 - upz * z1;
    x1 = upz * z0 - upx * z2;
    x2 = upx * z1 - upy * z0;
    len = Math.hypot(x0, x1, x2);
    if (!len) {
        x0 = 0;
        x1 = 0;
        x2 = 0;
    } else {
        len = 1 / len;
        x0 *= len;
        x1 *= len;
        x2 *= len;
    }
    y0 = z1 * x2 - z2 * x1;
    y1 = z2 * x0 - z0 * x2;
    y2 = z0 * x1 - z1 * x0;
    len = Math.hypot(y0, y1, y2);
    if (!len) {
        y0 = 0;
        y1 = 0;
        y2 = 0;
    } else {
        len = 1 / len;
        y0 *= len;
        y1 *= len;
        y2 *= len;
    }
    out[0] = x0;
    out[1] = y0;
    out[2] = z0;
    out[3] = 0;
    out[4] = x1;
    out[5] = y1;
    out[6] = z1;
    out[7] = 0;
    out[8] = x2;
    out[9] = y2;
    out[10] = z2;
    out[11] = 0;
    out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
    out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
    out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
    out[15] = 1;
    return out;
}
/**
 * Generates a matrix that makes something look at something else.
 *
 * @param {mat4} out mat4 frustum matrix will be written into
 * @param {ReadonlyVec3} eye Position of the viewer
 * @param {ReadonlyVec3} center Point the viewer is looking at
 * @param {ReadonlyVec3} up vec3 pointing up
 * @returns {mat4} out
 */
function targetTo(out, eye, target, up) {
    var eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2];
    var z0 = eyex - target[0], z1 = eyey - target[1], z2 = eyez - target[2];
    var len = z0 * z0 + z1 * z1 + z2 * z2;
    if (len > 0) {
        len = 1 / Math.sqrt(len);
        z0 *= len;
        z1 *= len;
        z2 *= len;
    }
    var x0 = upy * z2 - upz * z1, x1 = upz * z0 - upx * z2, x2 = upx * z1 - upy * z0;
    len = x0 * x0 + x1 * x1 + x2 * x2;
    if (len > 0) {
        len = 1 / Math.sqrt(len);
        x0 *= len;
        x1 *= len;
        x2 *= len;
    }
    out[0] = x0;
    out[1] = x1;
    out[2] = x2;
    out[3] = 0;
    out[4] = z1 * x2 - z2 * x1;
    out[5] = z2 * x0 - z0 * x2;
    out[6] = z0 * x1 - z1 * x0;
    out[7] = 0;
    out[8] = z0;
    out[9] = z1;
    out[10] = z2;
    out[11] = 0;
    out[12] = eyex;
    out[13] = eyey;
    out[14] = eyez;
    out[15] = 1;
    return out;
}
/**
 * Returns a string representation of a mat4
 *
 * @param {ReadonlyMat4} a matrix to represent as a string
 * @returns {String} string representation of the matrix
 */
function str$5(a) {
    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] + ')';
}
/**
 * Returns Frobenius norm of a mat4
 *
 * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of
 * @returns {Number} Frobenius norm
 */
function frob(a) {
    return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);
}
/**
 * Adds two mat4's
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the first operand
 * @param {ReadonlyMat4} b the second operand
 * @returns {mat4} out
 */
function add$5(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    out[4] = a[4] + b[4];
    out[5] = a[5] + b[5];
    out[6] = a[6] + b[6];
    out[7] = a[7] + b[7];
    out[8] = a[8] + b[8];
    out[9] = a[9] + b[9];
    out[10] = a[10] + b[10];
    out[11] = a[11] + b[11];
    out[12] = a[12] + b[12];
    out[13] = a[13] + b[13];
    out[14] = a[14] + b[14];
    out[15] = a[15] + b[15];
    return out;
}
/**
 * Subtracts matrix b from matrix a
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the first operand
 * @param {ReadonlyMat4} b the second operand
 * @returns {mat4} out
 */
function subtract$3(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
    out[3] = a[3] - b[3];
    out[4] = a[4] - b[4];
    out[5] = a[5] - b[5];
    out[6] = a[6] - b[6];
    out[7] = a[7] - b[7];
    out[8] = a[8] - b[8];
    out[9] = a[9] - b[9];
    out[10] = a[10] - b[10];
    out[11] = a[11] - b[11];
    out[12] = a[12] - b[12];
    out[13] = a[13] - b[13];
    out[14] = a[14] - b[14];
    out[15] = a[15] - b[15];
    return out;
}
/**
 * Multiply each element of the matrix by a scalar.
 *
 * @param {mat4} out the receiving matrix
 * @param {ReadonlyMat4} a the matrix to scale
 * @param {Number} b amount to scale the matrix's elements by
 * @returns {mat4} out
 */
function multiplyScalar(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    out[3] = a[3] * b;
    out[4] = a[4] * b;
    out[5] = a[5] * b;
    out[6] = a[6] * b;
    out[7] = a[7] * b;
    out[8] = a[8] * b;
    out[9] = a[9] * b;
    out[10] = a[10] * b;
    out[11] = a[11] * b;
    out[12] = a[12] * b;
    out[13] = a[13] * b;
    out[14] = a[14] * b;
    out[15] = a[15] * b;
    return out;
}
/**
 * Adds two mat4's after multiplying each element of the second operand by a scalar value.
 *
 * @param {mat4} out the receiving vector
 * @param {ReadonlyMat4} a the first operand
 * @param {ReadonlyMat4} b the second operand
 * @param {Number} scale the amount to scale b's elements by before adding
 * @returns {mat4} out
 */
function multiplyScalarAndAdd(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    out[2] = a[2] + b[2] * scale;
    out[3] = a[3] + b[3] * scale;
    out[4] = a[4] + b[4] * scale;
    out[5] = a[5] + b[5] * scale;
    out[6] = a[6] + b[6] * scale;
    out[7] = a[7] + b[7] * scale;
    out[8] = a[8] + b[8] * scale;
    out[9] = a[9] + b[9] * scale;
    out[10] = a[10] + b[10] * scale;
    out[11] = a[11] + b[11] * scale;
    out[12] = a[12] + b[12] * scale;
    out[13] = a[13] + b[13] * scale;
    out[14] = a[14] + b[14] * scale;
    out[15] = a[15] + b[15] * scale;
    return out;
}
/**
 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyMat4} a The first matrix.
 * @param {ReadonlyMat4} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function exactEquals$5(a, b) {
    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];
}
/**
 * Returns whether or not the matrices have approximately the same elements in the same position.
 *
 * @param {ReadonlyMat4} a The first matrix.
 * @param {ReadonlyMat4} b The second matrix.
 * @returns {Boolean} True if the matrices are equal, false otherwise.
 */
function equals$6(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7];
    var a8 = a[8], a9 = a[9], a10 = a[10], a11 = a[11];
    var a12 = a[12], a13 = a[13], a14 = a[14], a15 = a[15];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
    var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
    var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11];
    var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
    return Math.abs(a0 - b0) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix$6.EPSILON * Math.max(1, Math.abs(a15), Math.abs(b15));
}
/**
 * Alias for {@link mat4.multiply}
 * @function
 */
var mul$5 = multiply$5;
/**
 * Alias for {@link mat4.subtract}
 * @function
 */
mat4$2.mul = mul$5;
var sub$3 = subtract$3;
mat4$2.sub = sub$3;

var quat$2 = {};

var vec3$2 = {};

function _typeof$5(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$5 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$5 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$5(obj);
}
Object.defineProperty(vec3$2, '__esModule', { value: true });
vec3$2.create = create$5;
vec3$2.clone = clone$4;
vec3$2.length = length$4;
vec3$2.fromValues = fromValues$4;
vec3$2.copy = copy$4;
vec3$2.set = set$4;
vec3$2.add = add$4;
vec3$2.subtract = subtract$2;
vec3$2.multiply = multiply$4;
vec3$2.divide = divide$2;
vec3$2.ceil = ceil$2;
vec3$2.floor = floor$2;
vec3$2.min = min$2;
vec3$2.max = max$2;
vec3$2.round = round$2;
vec3$2.scale = scale$4;
vec3$2.scaleAndAdd = scaleAndAdd$2;
vec3$2.distance = distance$2;
vec3$2.squaredDistance = squaredDistance$2;
vec3$2.squaredLength = squaredLength$4;
vec3$2.negate = negate$2;
vec3$2.inverse = inverse$2;
vec3$2.normalize = normalize$4;
vec3$2.dot = dot$5;
vec3$2.cross = cross$2;
vec3$2.lerp = lerp$5;
vec3$2.hermite = hermite;
vec3$2.bezier = bezier;
vec3$2.random = random$3;
vec3$2.transformMat4 = transformMat4$2;
vec3$2.transformMat3 = transformMat3$1;
vec3$2.transformQuat = transformQuat$1;
vec3$2.rotateX = rotateX$2;
vec3$2.rotateY = rotateY$2;
vec3$2.rotateZ = rotateZ$2;
vec3$2.angle = angle$1;
vec3$2.zero = zero$2;
vec3$2.str = str$4;
vec3$2.exactEquals = exactEquals$4;
vec3$2.equals = equals$5;
vec3$2.forEach = vec3$2.sqrLen = vec3$2.len = vec3$2.sqrDist = vec3$2.dist = vec3$2.div = vec3$2.mul = vec3$2.sub = void 0;
var glMatrix$5 = _interopRequireWildcard$5(common);
function _getRequireWildcardCache$5(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$5 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$5(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$5(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$5(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 3 Dimensional Vector
 * @module vec3
 */
/**
 * Creates a new, empty vec3
 *
 * @returns {vec3} a new 3D vector
 */
function create$5() {
    var out = new glMatrix$5.ARRAY_TYPE(3);
    if (glMatrix$5.ARRAY_TYPE != Float32Array) {
        out[0] = 0;
        out[1] = 0;
        out[2] = 0;
    }
    return out;
}
/**
 * Creates a new vec3 initialized with values from an existing vector
 *
 * @param {ReadonlyVec3} a vector to clone
 * @returns {vec3} a new 3D vector
 */
function clone$4(a) {
    var out = new glMatrix$5.ARRAY_TYPE(3);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    return out;
}
/**
 * Calculates the length of a vec3
 *
 * @param {ReadonlyVec3} a vector to calculate length of
 * @returns {Number} length of a
 */
function length$4(a) {
    var x = a[0];
    var y = a[1];
    var z = a[2];
    return Math.hypot(x, y, z);
}
/**
 * Creates a new vec3 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @returns {vec3} a new 3D vector
 */
function fromValues$4(x, y, z) {
    var out = new glMatrix$5.ARRAY_TYPE(3);
    out[0] = x;
    out[1] = y;
    out[2] = z;
    return out;
}
/**
 * Copy the values from one vec3 to another
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the source vector
 * @returns {vec3} out
 */
function copy$4(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    return out;
}
/**
 * Set the components of a vec3 to the given values
 *
 * @param {vec3} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @returns {vec3} out
 */
function set$4(out, x, y, z) {
    out[0] = x;
    out[1] = y;
    out[2] = z;
    return out;
}
/**
 * Adds two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function add$4(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    return out;
}
/**
 * Subtracts vector b from vector a
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function subtract$2(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
    return out;
}
/**
 * Multiplies two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function multiply$4(out, a, b) {
    out[0] = a[0] * b[0];
    out[1] = a[1] * b[1];
    out[2] = a[2] * b[2];
    return out;
}
/**
 * Divides two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function divide$2(out, a, b) {
    out[0] = a[0] / b[0];
    out[1] = a[1] / b[1];
    out[2] = a[2] / b[2];
    return out;
}
/**
 * Math.ceil the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a vector to ceil
 * @returns {vec3} out
 */
function ceil$2(out, a) {
    out[0] = Math.ceil(a[0]);
    out[1] = Math.ceil(a[1]);
    out[2] = Math.ceil(a[2]);
    return out;
}
/**
 * Math.floor the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a vector to floor
 * @returns {vec3} out
 */
function floor$2(out, a) {
    out[0] = Math.floor(a[0]);
    out[1] = Math.floor(a[1]);
    out[2] = Math.floor(a[2]);
    return out;
}
/**
 * Returns the minimum of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function min$2(out, a, b) {
    out[0] = Math.min(a[0], b[0]);
    out[1] = Math.min(a[1], b[1]);
    out[2] = Math.min(a[2], b[2]);
    return out;
}
/**
 * Returns the maximum of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function max$2(out, a, b) {
    out[0] = Math.max(a[0], b[0]);
    out[1] = Math.max(a[1], b[1]);
    out[2] = Math.max(a[2], b[2]);
    return out;
}
/**
 * Math.round the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a vector to round
 * @returns {vec3} out
 */
function round$2(out, a) {
    out[0] = Math.round(a[0]);
    out[1] = Math.round(a[1]);
    out[2] = Math.round(a[2]);
    return out;
}
/**
 * Scales a vec3 by a scalar number
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec3} out
 */
function scale$4(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    return out;
}
/**
 * Adds two vec3's after scaling the second operand by a scalar value
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec3} out
 */
function scaleAndAdd$2(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    out[2] = a[2] + b[2] * scale;
    return out;
}
/**
 * Calculates the euclidian distance between two vec3's
 *
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {Number} distance between a and b
 */
function distance$2(a, b) {
    var x = b[0] - a[0];
    var y = b[1] - a[1];
    var z = b[2] - a[2];
    return Math.hypot(x, y, z);
}
/**
 * Calculates the squared euclidian distance between two vec3's
 *
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance$2(a, b) {
    var x = b[0] - a[0];
    var y = b[1] - a[1];
    var z = b[2] - a[2];
    return x * x + y * y + z * z;
}
/**
 * Calculates the squared length of a vec3
 *
 * @param {ReadonlyVec3} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength$4(a) {
    var x = a[0];
    var y = a[1];
    var z = a[2];
    return x * x + y * y + z * z;
}
/**
 * Negates the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a vector to negate
 * @returns {vec3} out
 */
function negate$2(out, a) {
    out[0] = -a[0];
    out[1] = -a[1];
    out[2] = -a[2];
    return out;
}
/**
 * Returns the inverse of the components of a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a vector to invert
 * @returns {vec3} out
 */
function inverse$2(out, a) {
    out[0] = 1 / a[0];
    out[1] = 1 / a[1];
    out[2] = 1 / a[2];
    return out;
}
/**
 * Normalize a vec3
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a vector to normalize
 * @returns {vec3} out
 */
function normalize$4(out, a) {
    var x = a[0];
    var y = a[1];
    var z = a[2];
    var len = x * x + y * y + z * z;
    if (len > 0) {
        //TODO: evaluate use of glm_invsqrt here?
        len = 1 / Math.sqrt(len);
    }
    out[0] = a[0] * len;
    out[1] = a[1] * len;
    out[2] = a[2] * len;
    return out;
}
/**
 * Calculates the dot product of two vec3's
 *
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot$5(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
/**
 * Computes the cross product of two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @returns {vec3} out
 */
function cross$2(out, a, b) {
    var ax = a[0], ay = a[1], az = a[2];
    var bx = b[0], by = b[1], bz = b[2];
    out[0] = ay * bz - az * by;
    out[1] = az * bx - ax * bz;
    out[2] = ax * by - ay * bx;
    return out;
}
/**
 * Performs a linear interpolation between two vec3's
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {vec3} out
 */
function lerp$5(out, a, b, t) {
    var ax = a[0];
    var ay = a[1];
    var az = a[2];
    out[0] = ax + t * (b[0] - ax);
    out[1] = ay + t * (b[1] - ay);
    out[2] = az + t * (b[2] - az);
    return out;
}
/**
 * Performs a hermite interpolation with two control points
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @param {ReadonlyVec3} c the third operand
 * @param {ReadonlyVec3} d the fourth operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {vec3} out
 */
function hermite(out, a, b, c, d, t) {
    var factorTimes2 = t * t;
    var factor1 = factorTimes2 * (2 * t - 3) + 1;
    var factor2 = factorTimes2 * (t - 2) + t;
    var factor3 = factorTimes2 * (t - 1);
    var factor4 = factorTimes2 * (3 - 2 * t);
    out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;
    out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;
    out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;
    return out;
}
/**
 * Performs a bezier interpolation with two control points
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the first operand
 * @param {ReadonlyVec3} b the second operand
 * @param {ReadonlyVec3} c the third operand
 * @param {ReadonlyVec3} d the fourth operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {vec3} out
 */
function bezier(out, a, b, c, d, t) {
    var inverseFactor = 1 - t;
    var inverseFactorTimesTwo = inverseFactor * inverseFactor;
    var factorTimes2 = t * t;
    var factor1 = inverseFactorTimesTwo * inverseFactor;
    var factor2 = 3 * t * inverseFactorTimesTwo;
    var factor3 = 3 * factorTimes2 * inverseFactor;
    var factor4 = factorTimes2 * t;
    out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;
    out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;
    out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;
    return out;
}
/**
 * Generates a random vector with the given scale
 *
 * @param {vec3} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec3} out
 */
function random$3(out, scale) {
    scale = scale || 1;
    var r = glMatrix$5.RANDOM() * 2 * Math.PI;
    var z = glMatrix$5.RANDOM() * 2 - 1;
    var zScale = Math.sqrt(1 - z * z) * scale;
    out[0] = Math.cos(r) * zScale;
    out[1] = Math.sin(r) * zScale;
    out[2] = z * scale;
    return out;
}
/**
 * Transforms the vec3 with a mat4.
 * 4th vector component is implicitly '1'
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the vector to transform
 * @param {ReadonlyMat4} m matrix to transform with
 * @returns {vec3} out
 */
function transformMat4$2(out, a, m) {
    var x = a[0], y = a[1], z = a[2];
    var w = m[3] * x + m[7] * y + m[11] * z + m[15];
    w = w || 1;
    out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
    out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
    out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
    return out;
}
/**
 * Transforms the vec3 with a mat3.
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the vector to transform
 * @param {ReadonlyMat3} m the 3x3 matrix to transform with
 * @returns {vec3} out
 */
function transformMat3$1(out, a, m) {
    var x = a[0], y = a[1], z = a[2];
    out[0] = x * m[0] + y * m[3] + z * m[6];
    out[1] = x * m[1] + y * m[4] + z * m[7];
    out[2] = x * m[2] + y * m[5] + z * m[8];
    return out;
}
/**
 * Transforms the vec3 with a quat
 * Can also be used for dual quaternions. (Multiply it with the real part)
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec3} a the vector to transform
 * @param {ReadonlyQuat} q quaternion to transform with
 * @returns {vec3} out
 */
function transformQuat$1(out, a, q) {
    // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
    var qx = q[0], qy = q[1], qz = q[2], qw = q[3];
    var x = a[0], y = a[1], z = a[2];
    // var qvec = [qx, qy, qz];
    // var uv = vec3.cross([], qvec, a);
    var uvx = qy * z - qz * y, uvy = qz * x - qx * z, uvz = qx * y - qy * x;
    // var uuv = vec3.cross([], qvec, uv);
    var uuvx = qy * uvz - qz * uvy, uuvy = qz * uvx - qx * uvz, uuvz = qx * uvy - qy * uvx;
    // vec3.scale(uv, uv, 2 * w);
    var w2 = qw * 2;
    uvx *= w2;
    uvy *= w2;
    uvz *= w2;
    // vec3.scale(uuv, uuv, 2);
    uuvx *= 2;
    uuvy *= 2;
    uuvz *= 2;
    // return vec3.add(out, a, vec3.add(out, uv, uuv));
    out[0] = x + uvx + uuvx;
    out[1] = y + uvy + uuvy;
    out[2] = z + uvz + uuvz;
    return out;
}
/**
 * Rotate a 3D vector around the x-axis
 * @param {vec3} out The receiving vec3
 * @param {ReadonlyVec3} a The vec3 point to rotate
 * @param {ReadonlyVec3} b The origin of the rotation
 * @param {Number} rad The angle of rotation in radians
 * @returns {vec3} out
 */
function rotateX$2(out, a, b, rad) {
    var p = [], r = [];
    //Translate point to the origin
    p[0] = a[0] - b[0];
    p[1] = a[1] - b[1];
    p[2] = a[2] - b[2];
    //perform rotation
    r[0] = p[0];
    r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
    r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad);
    //translate to correct position
    out[0] = r[0] + b[0];
    out[1] = r[1] + b[1];
    out[2] = r[2] + b[2];
    return out;
}
/**
 * Rotate a 3D vector around the y-axis
 * @param {vec3} out The receiving vec3
 * @param {ReadonlyVec3} a The vec3 point to rotate
 * @param {ReadonlyVec3} b The origin of the rotation
 * @param {Number} rad The angle of rotation in radians
 * @returns {vec3} out
 */
function rotateY$2(out, a, b, rad) {
    var p = [], r = [];
    //Translate point to the origin
    p[0] = a[0] - b[0];
    p[1] = a[1] - b[1];
    p[2] = a[2] - b[2];
    //perform rotation
    r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
    r[1] = p[1];
    r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad);
    //translate to correct position
    out[0] = r[0] + b[0];
    out[1] = r[1] + b[1];
    out[2] = r[2] + b[2];
    return out;
}
/**
 * Rotate a 3D vector around the z-axis
 * @param {vec3} out The receiving vec3
 * @param {ReadonlyVec3} a The vec3 point to rotate
 * @param {ReadonlyVec3} b The origin of the rotation
 * @param {Number} rad The angle of rotation in radians
 * @returns {vec3} out
 */
function rotateZ$2(out, a, b, rad) {
    var p = [], r = [];
    //Translate point to the origin
    p[0] = a[0] - b[0];
    p[1] = a[1] - b[1];
    p[2] = a[2] - b[2];
    //perform rotation
    r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
    r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
    r[2] = p[2];
    //translate to correct position
    out[0] = r[0] + b[0];
    out[1] = r[1] + b[1];
    out[2] = r[2] + b[2];
    return out;
}
/**
 * Get the angle between two 3D vectors
 * @param {ReadonlyVec3} a The first operand
 * @param {ReadonlyVec3} b The second operand
 * @returns {Number} The angle in radians
 */
function angle$1(a, b) {
    var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2], mag1 = Math.sqrt(ax * ax + ay * ay + az * az), mag2 = Math.sqrt(bx * bx + by * by + bz * bz), mag = mag1 * mag2, cosine = mag && dot$5(a, b) / mag;
    return Math.acos(Math.min(Math.max(cosine, -1), 1));
}
/**
 * Set the components of a vec3 to zero
 *
 * @param {vec3} out the receiving vector
 * @returns {vec3} out
 */
function zero$2(out) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
    return out;
}
/**
 * Returns a string representation of a vector
 *
 * @param {ReadonlyVec3} a vector to represent as a string
 * @returns {String} string representation of the vector
 */
function str$4(a) {
    return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';
}
/**
 * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyVec3} a The first vector.
 * @param {ReadonlyVec3} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function exactEquals$4(a, b) {
    return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
}
/**
 * Returns whether or not the vectors have approximately the same elements in the same position.
 *
 * @param {ReadonlyVec3} a The first vector.
 * @param {ReadonlyVec3} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function equals$5(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2];
    var b0 = b[0], b1 = b[1], b2 = b[2];
    return Math.abs(a0 - b0) <= glMatrix$5.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$5.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$5.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2));
}
/**
 * Alias for {@link vec3.subtract}
 * @function
 */
var sub$2 = subtract$2;
/**
 * Alias for {@link vec3.multiply}
 * @function
 */
vec3$2.sub = sub$2;
var mul$4 = multiply$4;
/**
 * Alias for {@link vec3.divide}
 * @function
 */
vec3$2.mul = mul$4;
var div$2 = divide$2;
/**
 * Alias for {@link vec3.distance}
 * @function
 */
vec3$2.div = div$2;
var dist$2 = distance$2;
/**
 * Alias for {@link vec3.squaredDistance}
 * @function
 */
vec3$2.dist = dist$2;
var sqrDist$2 = squaredDistance$2;
/**
 * Alias for {@link vec3.length}
 * @function
 */
vec3$2.sqrDist = sqrDist$2;
var len$4 = length$4;
/**
 * Alias for {@link vec3.squaredLength}
 * @function
 */
vec3$2.len = len$4;
var sqrLen$4 = squaredLength$4;
/**
 * Perform some operation over an array of vec3s.
 *
 * @param {Array} a the array of vectors to iterate over
 * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
 * @param {Number} offset Number of elements to skip at the beginning of the array
 * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
 * @param {Function} fn Function to call for each vector in the array
 * @param {Object} [arg] additional argument to pass to fn
 * @returns {Array} a
 * @function
 */
vec3$2.sqrLen = sqrLen$4;
var forEach$2 = (function () {
    var vec = create$5();
    return function (a, stride, offset, count, fn, arg) {
        var i, l;
        if (!stride) {
            stride = 3;
        }
        if (!offset) {
            offset = 0;
        }
        if (count) {
            l = Math.min(count * stride + offset, a.length);
        } else {
            l = a.length;
        }
        for (i = offset; i < l; i += stride) {
            vec[0] = a[i];
            vec[1] = a[i + 1];
            vec[2] = a[i + 2];
            fn(vec, vec, arg);
            a[i] = vec[0];
            a[i + 1] = vec[1];
            a[i + 2] = vec[2];
        }
        return a;
    };
}());
vec3$2.forEach = forEach$2;

var vec4$2 = {};

function _typeof$4(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$4 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$4 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$4(obj);
}
Object.defineProperty(vec4$2, '__esModule', { value: true });
vec4$2.create = create$4;
vec4$2.clone = clone$3;
vec4$2.fromValues = fromValues$3;
vec4$2.copy = copy$3;
vec4$2.set = set$3;
vec4$2.add = add$3;
vec4$2.subtract = subtract$1;
vec4$2.multiply = multiply$3;
vec4$2.divide = divide$1;
vec4$2.ceil = ceil$1;
vec4$2.floor = floor$1;
vec4$2.min = min$1;
vec4$2.max = max$1;
vec4$2.round = round$1;
vec4$2.scale = scale$3;
vec4$2.scaleAndAdd = scaleAndAdd$1;
vec4$2.distance = distance$1;
vec4$2.squaredDistance = squaredDistance$1;
vec4$2.length = length$3;
vec4$2.squaredLength = squaredLength$3;
vec4$2.negate = negate$1;
vec4$2.inverse = inverse$1;
vec4$2.normalize = normalize$3;
vec4$2.dot = dot$4;
vec4$2.cross = cross$1;
vec4$2.lerp = lerp$4;
vec4$2.random = random$2;
vec4$2.transformMat4 = transformMat4$1;
vec4$2.transformQuat = transformQuat;
vec4$2.zero = zero$1;
vec4$2.str = str$3;
vec4$2.exactEquals = exactEquals$3;
vec4$2.equals = equals$4;
vec4$2.forEach = vec4$2.sqrLen = vec4$2.len = vec4$2.sqrDist = vec4$2.dist = vec4$2.div = vec4$2.mul = vec4$2.sub = void 0;
var glMatrix$4 = _interopRequireWildcard$4(common);
function _getRequireWildcardCache$4(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$4 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$4(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$4(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$4(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 4 Dimensional Vector
 * @module vec4
 */
/**
 * Creates a new, empty vec4
 *
 * @returns {vec4} a new 4D vector
 */
function create$4() {
    var out = new glMatrix$4.ARRAY_TYPE(4);
    if (glMatrix$4.ARRAY_TYPE != Float32Array) {
        out[0] = 0;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
    }
    return out;
}
/**
 * Creates a new vec4 initialized with values from an existing vector
 *
 * @param {ReadonlyVec4} a vector to clone
 * @returns {vec4} a new 4D vector
 */
function clone$3(a) {
    var out = new glMatrix$4.ARRAY_TYPE(4);
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    return out;
}
/**
 * Creates a new vec4 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {vec4} a new 4D vector
 */
function fromValues$3(x, y, z, w) {
    var out = new glMatrix$4.ARRAY_TYPE(4);
    out[0] = x;
    out[1] = y;
    out[2] = z;
    out[3] = w;
    return out;
}
/**
 * Copy the values from one vec4 to another
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the source vector
 * @returns {vec4} out
 */
function copy$3(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    return out;
}
/**
 * Set the components of a vec4 to the given values
 *
 * @param {vec4} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {vec4} out
 */
function set$3(out, x, y, z, w) {
    out[0] = x;
    out[1] = y;
    out[2] = z;
    out[3] = w;
    return out;
}
/**
 * Adds two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {vec4} out
 */
function add$3(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    return out;
}
/**
 * Subtracts vector b from vector a
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {vec4} out
 */
function subtract$1(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
    out[3] = a[3] - b[3];
    return out;
}
/**
 * Multiplies two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {vec4} out
 */
function multiply$3(out, a, b) {
    out[0] = a[0] * b[0];
    out[1] = a[1] * b[1];
    out[2] = a[2] * b[2];
    out[3] = a[3] * b[3];
    return out;
}
/**
 * Divides two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {vec4} out
 */
function divide$1(out, a, b) {
    out[0] = a[0] / b[0];
    out[1] = a[1] / b[1];
    out[2] = a[2] / b[2];
    out[3] = a[3] / b[3];
    return out;
}
/**
 * Math.ceil the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a vector to ceil
 * @returns {vec4} out
 */
function ceil$1(out, a) {
    out[0] = Math.ceil(a[0]);
    out[1] = Math.ceil(a[1]);
    out[2] = Math.ceil(a[2]);
    out[3] = Math.ceil(a[3]);
    return out;
}
/**
 * Math.floor the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a vector to floor
 * @returns {vec4} out
 */
function floor$1(out, a) {
    out[0] = Math.floor(a[0]);
    out[1] = Math.floor(a[1]);
    out[2] = Math.floor(a[2]);
    out[3] = Math.floor(a[3]);
    return out;
}
/**
 * Returns the minimum of two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {vec4} out
 */
function min$1(out, a, b) {
    out[0] = Math.min(a[0], b[0]);
    out[1] = Math.min(a[1], b[1]);
    out[2] = Math.min(a[2], b[2]);
    out[3] = Math.min(a[3], b[3]);
    return out;
}
/**
 * Returns the maximum of two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {vec4} out
 */
function max$1(out, a, b) {
    out[0] = Math.max(a[0], b[0]);
    out[1] = Math.max(a[1], b[1]);
    out[2] = Math.max(a[2], b[2]);
    out[3] = Math.max(a[3], b[3]);
    return out;
}
/**
 * Math.round the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a vector to round
 * @returns {vec4} out
 */
function round$1(out, a) {
    out[0] = Math.round(a[0]);
    out[1] = Math.round(a[1]);
    out[2] = Math.round(a[2]);
    out[3] = Math.round(a[3]);
    return out;
}
/**
 * Scales a vec4 by a scalar number
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec4} out
 */
function scale$3(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    out[3] = a[3] * b;
    return out;
}
/**
 * Adds two vec4's after scaling the second operand by a scalar value
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec4} out
 */
function scaleAndAdd$1(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    out[2] = a[2] + b[2] * scale;
    out[3] = a[3] + b[3] * scale;
    return out;
}
/**
 * Calculates the euclidian distance between two vec4's
 *
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {Number} distance between a and b
 */
function distance$1(a, b) {
    var x = b[0] - a[0];
    var y = b[1] - a[1];
    var z = b[2] - a[2];
    var w = b[3] - a[3];
    return Math.hypot(x, y, z, w);
}
/**
 * Calculates the squared euclidian distance between two vec4's
 *
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance$1(a, b) {
    var x = b[0] - a[0];
    var y = b[1] - a[1];
    var z = b[2] - a[2];
    var w = b[3] - a[3];
    return x * x + y * y + z * z + w * w;
}
/**
 * Calculates the length of a vec4
 *
 * @param {ReadonlyVec4} a vector to calculate length of
 * @returns {Number} length of a
 */
function length$3(a) {
    var x = a[0];
    var y = a[1];
    var z = a[2];
    var w = a[3];
    return Math.hypot(x, y, z, w);
}
/**
 * Calculates the squared length of a vec4
 *
 * @param {ReadonlyVec4} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength$3(a) {
    var x = a[0];
    var y = a[1];
    var z = a[2];
    var w = a[3];
    return x * x + y * y + z * z + w * w;
}
/**
 * Negates the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a vector to negate
 * @returns {vec4} out
 */
function negate$1(out, a) {
    out[0] = -a[0];
    out[1] = -a[1];
    out[2] = -a[2];
    out[3] = -a[3];
    return out;
}
/**
 * Returns the inverse of the components of a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a vector to invert
 * @returns {vec4} out
 */
function inverse$1(out, a) {
    out[0] = 1 / a[0];
    out[1] = 1 / a[1];
    out[2] = 1 / a[2];
    out[3] = 1 / a[3];
    return out;
}
/**
 * Normalize a vec4
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a vector to normalize
 * @returns {vec4} out
 */
function normalize$3(out, a) {
    var x = a[0];
    var y = a[1];
    var z = a[2];
    var w = a[3];
    var len = x * x + y * y + z * z + w * w;
    if (len > 0) {
        len = 1 / Math.sqrt(len);
    }
    out[0] = x * len;
    out[1] = y * len;
    out[2] = z * len;
    out[3] = w * len;
    return out;
}
/**
 * Calculates the dot product of two vec4's
 *
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot$4(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
/**
 * Returns the cross-product of three vectors in a 4-dimensional space
 *
 * @param {ReadonlyVec4} result the receiving vector
 * @param {ReadonlyVec4} U the first vector
 * @param {ReadonlyVec4} V the second vector
 * @param {ReadonlyVec4} W the third vector
 * @returns {vec4} result
 */
function cross$1(out, u, v, w) {
    var A = v[0] * w[1] - v[1] * w[0], B = v[0] * w[2] - v[2] * w[0], C = v[0] * w[3] - v[3] * w[0], D = v[1] * w[2] - v[2] * w[1], E = v[1] * w[3] - v[3] * w[1], F = v[2] * w[3] - v[3] * w[2];
    var G = u[0];
    var H = u[1];
    var I = u[2];
    var J = u[3];
    out[0] = H * F - I * E + J * D;
    out[1] = -(G * F) + I * C - J * B;
    out[2] = G * E - H * C + J * A;
    out[3] = -(G * D) + H * B - I * A;
    return out;
}
/**
 * Performs a linear interpolation between two vec4's
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the first operand
 * @param {ReadonlyVec4} b the second operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {vec4} out
 */
function lerp$4(out, a, b, t) {
    var ax = a[0];
    var ay = a[1];
    var az = a[2];
    var aw = a[3];
    out[0] = ax + t * (b[0] - ax);
    out[1] = ay + t * (b[1] - ay);
    out[2] = az + t * (b[2] - az);
    out[3] = aw + t * (b[3] - aw);
    return out;
}
/**
 * Generates a random vector with the given scale
 *
 * @param {vec4} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec4} out
 */
function random$2(out, scale) {
    scale = scale || 1;
    // Marsaglia, George. Choosing a Point from the Surface of a
    // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.
    // http://projecteuclid.org/euclid.aoms/1177692644;
    var v1, v2, v3, v4;
    var s1, s2;
    do {
        v1 = glMatrix$4.RANDOM() * 2 - 1;
        v2 = glMatrix$4.RANDOM() * 2 - 1;
        s1 = v1 * v1 + v2 * v2;
    } while (s1 >= 1);
    do {
        v3 = glMatrix$4.RANDOM() * 2 - 1;
        v4 = glMatrix$4.RANDOM() * 2 - 1;
        s2 = v3 * v3 + v4 * v4;
    } while (s2 >= 1);
    var d = Math.sqrt((1 - s1) / s2);
    out[0] = scale * v1;
    out[1] = scale * v2;
    out[2] = scale * v3 * d;
    out[3] = scale * v4 * d;
    return out;
}
/**
 * Transforms the vec4 with a mat4.
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the vector to transform
 * @param {ReadonlyMat4} m matrix to transform with
 * @returns {vec4} out
 */
function transformMat4$1(out, a, m) {
    var x = a[0], y = a[1], z = a[2], w = a[3];
    out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
    out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
    out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
    out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
    return out;
}
/**
 * Transforms the vec4 with a quat
 *
 * @param {vec4} out the receiving vector
 * @param {ReadonlyVec4} a the vector to transform
 * @param {ReadonlyQuat} q quaternion to transform with
 * @returns {vec4} out
 */
function transformQuat(out, a, q) {
    var x = a[0], y = a[1], z = a[2];
    var qx = q[0], qy = q[1], qz = q[2], qw = q[3];
    // calculate quat * vec
    var ix = qw * x + qy * z - qz * y;
    var iy = qw * y + qz * x - qx * z;
    var iz = qw * z + qx * y - qy * x;
    var iw = -qx * x - qy * y - qz * z;
    // calculate result * inverse quat
    out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
    out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
    out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
    out[3] = a[3];
    return out;
}
/**
 * Set the components of a vec4 to zero
 *
 * @param {vec4} out the receiving vector
 * @returns {vec4} out
 */
function zero$1(out) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    return out;
}
/**
 * Returns a string representation of a vector
 *
 * @param {ReadonlyVec4} a vector to represent as a string
 * @returns {String} string representation of the vector
 */
function str$3(a) {
    return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
}
/**
 * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyVec4} a The first vector.
 * @param {ReadonlyVec4} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function exactEquals$3(a, b) {
    return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
}
/**
 * Returns whether or not the vectors have approximately the same elements in the same position.
 *
 * @param {ReadonlyVec4} a The first vector.
 * @param {ReadonlyVec4} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function equals$4(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
    return Math.abs(a0 - b0) <= glMatrix$4.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$4.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$4.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix$4.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3));
}
/**
 * Alias for {@link vec4.subtract}
 * @function
 */
var sub$1 = subtract$1;
/**
 * Alias for {@link vec4.multiply}
 * @function
 */
vec4$2.sub = sub$1;
var mul$3 = multiply$3;
/**
 * Alias for {@link vec4.divide}
 * @function
 */
vec4$2.mul = mul$3;
var div$1 = divide$1;
/**
 * Alias for {@link vec4.distance}
 * @function
 */
vec4$2.div = div$1;
var dist$1 = distance$1;
/**
 * Alias for {@link vec4.squaredDistance}
 * @function
 */
vec4$2.dist = dist$1;
var sqrDist$1 = squaredDistance$1;
/**
 * Alias for {@link vec4.length}
 * @function
 */
vec4$2.sqrDist = sqrDist$1;
var len$3 = length$3;
/**
 * Alias for {@link vec4.squaredLength}
 * @function
 */
vec4$2.len = len$3;
var sqrLen$3 = squaredLength$3;
/**
 * Perform some operation over an array of vec4s.
 *
 * @param {Array} a the array of vectors to iterate over
 * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
 * @param {Number} offset Number of elements to skip at the beginning of the array
 * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
 * @param {Function} fn Function to call for each vector in the array
 * @param {Object} [arg] additional argument to pass to fn
 * @returns {Array} a
 * @function
 */
vec4$2.sqrLen = sqrLen$3;
var forEach$1 = (function () {
    var vec = create$4();
    return function (a, stride, offset, count, fn, arg) {
        var i, l;
        if (!stride) {
            stride = 4;
        }
        if (!offset) {
            offset = 0;
        }
        if (count) {
            l = Math.min(count * stride + offset, a.length);
        } else {
            l = a.length;
        }
        for (i = offset; i < l; i += stride) {
            vec[0] = a[i];
            vec[1] = a[i + 1];
            vec[2] = a[i + 2];
            vec[3] = a[i + 3];
            fn(vec, vec, arg);
            a[i] = vec[0];
            a[i + 1] = vec[1];
            a[i + 2] = vec[2];
            a[i + 3] = vec[3];
        }
        return a;
    };
}());
vec4$2.forEach = forEach$1;

function _typeof$3(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$3 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$3 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$3(obj);
}
Object.defineProperty(quat$2, '__esModule', { value: true });
quat$2.create = create$3;
quat$2.identity = identity$2;
quat$2.setAxisAngle = setAxisAngle;
quat$2.getAxisAngle = getAxisAngle;
quat$2.getAngle = getAngle;
quat$2.multiply = multiply$2;
quat$2.rotateX = rotateX$1;
quat$2.rotateY = rotateY$1;
quat$2.rotateZ = rotateZ$1;
quat$2.calculateW = calculateW;
quat$2.exp = exp;
quat$2.ln = ln;
quat$2.pow = pow;
quat$2.slerp = slerp$1;
quat$2.random = random$1;
quat$2.invert = invert$1;
quat$2.conjugate = conjugate$1;
quat$2.fromMat3 = fromMat3;
quat$2.fromEuler = fromEuler;
quat$2.str = str$2;
quat$2.setAxes = quat$2.sqlerp = quat$2.rotationTo = quat$2.equals = quat$2.exactEquals = quat$2.normalize = quat$2.sqrLen = quat$2.squaredLength = quat$2.len = quat$2.length = quat$2.lerp = quat$2.dot = quat$2.scale = quat$2.mul = quat$2.add = quat$2.set = quat$2.copy = quat$2.fromValues = quat$2.clone = void 0;
var glMatrix$3 = _interopRequireWildcard$3(common);
var mat3$1 = _interopRequireWildcard$3(mat3$2);
var vec3$1 = _interopRequireWildcard$3(vec3$2);
var vec4$1 = _interopRequireWildcard$3(vec4$2);
function _getRequireWildcardCache$3(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$3 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$3(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$3(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$3(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * Quaternion
 * @module quat
 */
/**
 * Creates a new identity quat
 *
 * @returns {quat} a new quaternion
 */
function create$3() {
    var out = new glMatrix$3.ARRAY_TYPE(4);
    if (glMatrix$3.ARRAY_TYPE != Float32Array) {
        out[0] = 0;
        out[1] = 0;
        out[2] = 0;
    }
    out[3] = 1;
    return out;
}
/**
 * Set a quat to the identity quaternion
 *
 * @param {quat} out the receiving quaternion
 * @returns {quat} out
 */
function identity$2(out) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    return out;
}
/**
 * Sets a quat from the given angle and rotation axis,
 * then returns it.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyVec3} axis the axis around which to rotate
 * @param {Number} rad the angle in radians
 * @returns {quat} out
 **/
function setAxisAngle(out, axis, rad) {
    rad = rad * 0.5;
    var s = Math.sin(rad);
    out[0] = s * axis[0];
    out[1] = s * axis[1];
    out[2] = s * axis[2];
    out[3] = Math.cos(rad);
    return out;
}
/**
 * Gets the rotation axis and angle for a given
 *  quaternion. If a quaternion is created with
 *  setAxisAngle, this method will return the same
 *  values as providied in the original parameter list
 *  OR functionally equivalent values.
 * Example: The quaternion formed by axis [0, 0, 1] and
 *  angle -90 is the same as the quaternion formed by
 *  [0, 0, 1] and 270. This method favors the latter.
 * @param  {vec3} out_axis  Vector receiving the axis of rotation
 * @param  {ReadonlyQuat} q     Quaternion to be decomposed
 * @return {Number}     Angle, in radians, of the rotation
 */
function getAxisAngle(out_axis, q) {
    var rad = Math.acos(q[3]) * 2;
    var s = Math.sin(rad / 2);
    if (s > glMatrix$3.EPSILON) {
        out_axis[0] = q[0] / s;
        out_axis[1] = q[1] / s;
        out_axis[2] = q[2] / s;
    } else {
        // If s is zero, return any axis (no rotation - axis does not matter)
        out_axis[0] = 1;
        out_axis[1] = 0;
        out_axis[2] = 0;
    }
    return rad;
}
/**
 * Gets the angular distance between two unit quaternions
 *
 * @param  {ReadonlyQuat} a     Origin unit quaternion
 * @param  {ReadonlyQuat} b     Destination unit quaternion
 * @return {Number}     Angle, in radians, between the two quaternions
 */
function getAngle(a, b) {
    var dotproduct = dot$3(a, b);
    return Math.acos(2 * dotproduct * dotproduct - 1);
}
/**
 * Multiplies two quat's
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a the first operand
 * @param {ReadonlyQuat} b the second operand
 * @returns {quat} out
 */
function multiply$2(out, a, b) {
    var ax = a[0], ay = a[1], az = a[2], aw = a[3];
    var bx = b[0], by = b[1], bz = b[2], bw = b[3];
    out[0] = ax * bw + aw * bx + ay * bz - az * by;
    out[1] = ay * bw + aw * by + az * bx - ax * bz;
    out[2] = az * bw + aw * bz + ax * by - ay * bx;
    out[3] = aw * bw - ax * bx - ay * by - az * bz;
    return out;
}
/**
 * Rotates a quaternion by the given angle about the X axis
 *
 * @param {quat} out quat receiving operation result
 * @param {ReadonlyQuat} a quat to rotate
 * @param {number} rad angle (in radians) to rotate
 * @returns {quat} out
 */
function rotateX$1(out, a, rad) {
    rad *= 0.5;
    var ax = a[0], ay = a[1], az = a[2], aw = a[3];
    var bx = Math.sin(rad), bw = Math.cos(rad);
    out[0] = ax * bw + aw * bx;
    out[1] = ay * bw + az * bx;
    out[2] = az * bw - ay * bx;
    out[3] = aw * bw - ax * bx;
    return out;
}
/**
 * Rotates a quaternion by the given angle about the Y axis
 *
 * @param {quat} out quat receiving operation result
 * @param {ReadonlyQuat} a quat to rotate
 * @param {number} rad angle (in radians) to rotate
 * @returns {quat} out
 */
function rotateY$1(out, a, rad) {
    rad *= 0.5;
    var ax = a[0], ay = a[1], az = a[2], aw = a[3];
    var by = Math.sin(rad), bw = Math.cos(rad);
    out[0] = ax * bw - az * by;
    out[1] = ay * bw + aw * by;
    out[2] = az * bw + ax * by;
    out[3] = aw * bw - ay * by;
    return out;
}
/**
 * Rotates a quaternion by the given angle about the Z axis
 *
 * @param {quat} out quat receiving operation result
 * @param {ReadonlyQuat} a quat to rotate
 * @param {number} rad angle (in radians) to rotate
 * @returns {quat} out
 */
function rotateZ$1(out, a, rad) {
    rad *= 0.5;
    var ax = a[0], ay = a[1], az = a[2], aw = a[3];
    var bz = Math.sin(rad), bw = Math.cos(rad);
    out[0] = ax * bw + ay * bz;
    out[1] = ay * bw - ax * bz;
    out[2] = az * bw + aw * bz;
    out[3] = aw * bw - az * bz;
    return out;
}
/**
 * Calculates the W component of a quat from the X, Y, and Z components.
 * Assumes that quaternion is 1 unit in length.
 * Any existing W component will be ignored.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quat to calculate W component of
 * @returns {quat} out
 */
function calculateW(out, a) {
    var x = a[0], y = a[1], z = a[2];
    out[0] = x;
    out[1] = y;
    out[2] = z;
    out[3] = Math.sqrt(Math.abs(1 - x * x - y * y - z * z));
    return out;
}
/**
 * Calculate the exponential of a unit quaternion.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quat to calculate the exponential of
 * @returns {quat} out
 */
function exp(out, a) {
    var x = a[0], y = a[1], z = a[2], w = a[3];
    var r = Math.sqrt(x * x + y * y + z * z);
    var et = Math.exp(w);
    var s = r > 0 ? et * Math.sin(r) / r : 0;
    out[0] = x * s;
    out[1] = y * s;
    out[2] = z * s;
    out[3] = et * Math.cos(r);
    return out;
}
/**
 * Calculate the natural logarithm of a unit quaternion.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quat to calculate the exponential of
 * @returns {quat} out
 */
function ln(out, a) {
    var x = a[0], y = a[1], z = a[2], w = a[3];
    var r = Math.sqrt(x * x + y * y + z * z);
    var t = r > 0 ? Math.atan2(r, w) / r : 0;
    out[0] = x * t;
    out[1] = y * t;
    out[2] = z * t;
    out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);
    return out;
}
/**
 * Calculate the scalar power of a unit quaternion.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quat to calculate the exponential of
 * @param {Number} b amount to scale the quaternion by
 * @returns {quat} out
 */
function pow(out, a, b) {
    ln(out, a);
    scale$2(out, out, b);
    exp(out, out);
    return out;
}
/**
 * Performs a spherical linear interpolation between two quat
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a the first operand
 * @param {ReadonlyQuat} b the second operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {quat} out
 */
function slerp$1(out, a, b, t) {
    // benchmarks:
    //    http://jsperf.com/quaternion-slerp-implementations
    var ax = a[0], ay = a[1], az = a[2], aw = a[3];
    var bx = b[0], by = b[1], bz = b[2], bw = b[3];
    var omega, cosom, sinom, scale0, scale1;
    // calc cosine
    cosom = ax * bx + ay * by + az * bz + aw * bw;
    // adjust signs (if necessary)
    if (cosom < 0) {
        cosom = -cosom;
        bx = -bx;
        by = -by;
        bz = -bz;
        bw = -bw;
    }
    // calculate coefficients
    if (1 - cosom > glMatrix$3.EPSILON) {
        // standard case (slerp)
        omega = Math.acos(cosom);
        sinom = Math.sin(omega);
        scale0 = Math.sin((1 - t) * omega) / sinom;
        scale1 = Math.sin(t * omega) / sinom;
    } else {
        // "from" and "to" quaternions are very close
        //  ... so we can do a linear interpolation
        scale0 = 1 - t;
        scale1 = t;
    }
    // calculate final values
    out[0] = scale0 * ax + scale1 * bx;
    out[1] = scale0 * ay + scale1 * by;
    out[2] = scale0 * az + scale1 * bz;
    out[3] = scale0 * aw + scale1 * bw;
    return out;
}
/**
 * Generates a random unit quaternion
 *
 * @param {quat} out the receiving quaternion
 * @returns {quat} out
 */
function random$1(out) {
    // Implementation of http://planning.cs.uiuc.edu/node198.html
    // TODO: Calling random 3 times is probably not the fastest solution
    var u1 = glMatrix$3.RANDOM();
    var u2 = glMatrix$3.RANDOM();
    var u3 = glMatrix$3.RANDOM();
    var sqrt1MinusU1 = Math.sqrt(1 - u1);
    var sqrtU1 = Math.sqrt(u1);
    out[0] = sqrt1MinusU1 * Math.sin(2 * Math.PI * u2);
    out[1] = sqrt1MinusU1 * Math.cos(2 * Math.PI * u2);
    out[2] = sqrtU1 * Math.sin(2 * Math.PI * u3);
    out[3] = sqrtU1 * Math.cos(2 * Math.PI * u3);
    return out;
}
/**
 * Calculates the inverse of a quat
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quat to calculate inverse of
 * @returns {quat} out
 */
function invert$1(out, a) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
    var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
    var invDot = dot ? 1 / dot : 0;
    // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
    out[0] = -a0 * invDot;
    out[1] = -a1 * invDot;
    out[2] = -a2 * invDot;
    out[3] = a3 * invDot;
    return out;
}
/**
 * Calculates the conjugate of a quat
 * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quat to calculate conjugate of
 * @returns {quat} out
 */
function conjugate$1(out, a) {
    out[0] = -a[0];
    out[1] = -a[1];
    out[2] = -a[2];
    out[3] = a[3];
    return out;
}
/**
 * Creates a quaternion from the given 3x3 rotation matrix.
 *
 * NOTE: The resultant quaternion is not normalized, so you should be sure
 * to renormalize the quaternion yourself where necessary.
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyMat3} m rotation matrix
 * @returns {quat} out
 * @function
 */
function fromMat3(out, m) {
    // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
    // article "Quaternion Calculus and Fast Animation".
    var fTrace = m[0] + m[4] + m[8];
    var fRoot;
    if (fTrace > 0) {
        // |w| > 1/2, may as well choose w > 1/2
        fRoot = Math.sqrt(fTrace + 1);
        // 2w
        out[3] = 0.5 * fRoot;
        fRoot = 0.5 / fRoot;
        // 1/(4w)
        out[0] = (m[5] - m[7]) * fRoot;
        out[1] = (m[6] - m[2]) * fRoot;
        out[2] = (m[1] - m[3]) * fRoot;
    } else {
        // |w| <= 1/2
        var i = 0;
        if (m[4] > m[0])
            i = 1;
        if (m[8] > m[i * 3 + i])
            i = 2;
        var j = (i + 1) % 3;
        var k = (i + 2) % 3;
        fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1);
        out[i] = 0.5 * fRoot;
        fRoot = 0.5 / fRoot;
        out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
        out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
        out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
    }
    return out;
}
/**
 * Creates a quaternion from the given euler angle x, y, z.
 *
 * @param {quat} out the receiving quaternion
 * @param {x} Angle to rotate around X axis in degrees.
 * @param {y} Angle to rotate around Y axis in degrees.
 * @param {z} Angle to rotate around Z axis in degrees.
 * @returns {quat} out
 * @function
 */
function fromEuler(out, x, y, z) {
    var halfToRad = 0.5 * Math.PI / 180;
    x *= halfToRad;
    y *= halfToRad;
    z *= halfToRad;
    var sx = Math.sin(x);
    var cx = Math.cos(x);
    var sy = Math.sin(y);
    var cy = Math.cos(y);
    var sz = Math.sin(z);
    var cz = Math.cos(z);
    out[0] = sx * cy * cz - cx * sy * sz;
    out[1] = cx * sy * cz + sx * cy * sz;
    out[2] = cx * cy * sz - sx * sy * cz;
    out[3] = cx * cy * cz + sx * sy * sz;
    return out;
}
/**
 * Returns a string representation of a quatenion
 *
 * @param {ReadonlyQuat} a vector to represent as a string
 * @returns {String} string representation of the vector
 */
function str$2(a) {
    return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
}
/**
 * Creates a new quat initialized with values from an existing quaternion
 *
 * @param {ReadonlyQuat} a quaternion to clone
 * @returns {quat} a new quaternion
 * @function
 */
var clone$2 = vec4$1.clone;
/**
 * Creates a new quat initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {quat} a new quaternion
 * @function
 */
quat$2.clone = clone$2;
var fromValues$2 = vec4$1.fromValues;
/**
 * Copy the values from one quat to another
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a the source quaternion
 * @returns {quat} out
 * @function
 */
quat$2.fromValues = fromValues$2;
var copy$2 = vec4$1.copy;
/**
 * Set the components of a quat to the given values
 *
 * @param {quat} out the receiving quaternion
 * @param {Number} x X component
 * @param {Number} y Y component
 * @param {Number} z Z component
 * @param {Number} w W component
 * @returns {quat} out
 * @function
 */
quat$2.copy = copy$2;
var set$2 = vec4$1.set;
/**
 * Adds two quat's
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a the first operand
 * @param {ReadonlyQuat} b the second operand
 * @returns {quat} out
 * @function
 */
quat$2.set = set$2;
var add$2 = vec4$1.add;
/**
 * Alias for {@link quat.multiply}
 * @function
 */
quat$2.add = add$2;
var mul$2 = multiply$2;
/**
 * Scales a quat by a scalar number
 *
 * @param {quat} out the receiving vector
 * @param {ReadonlyQuat} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {quat} out
 * @function
 */
quat$2.mul = mul$2;
var scale$2 = vec4$1.scale;
/**
 * Calculates the dot product of two quat's
 *
 * @param {ReadonlyQuat} a the first operand
 * @param {ReadonlyQuat} b the second operand
 * @returns {Number} dot product of a and b
 * @function
 */
quat$2.scale = scale$2;
var dot$3 = vec4$1.dot;
/**
 * Performs a linear interpolation between two quat's
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a the first operand
 * @param {ReadonlyQuat} b the second operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {quat} out
 * @function
 */
quat$2.dot = dot$3;
var lerp$3 = vec4$1.lerp;
/**
 * Calculates the length of a quat
 *
 * @param {ReadonlyQuat} a vector to calculate length of
 * @returns {Number} length of a
 */
quat$2.lerp = lerp$3;
var length$2 = vec4$1.length;
/**
 * Alias for {@link quat.length}
 * @function
 */
quat$2.length = length$2;
var len$2 = length$2;
/**
 * Calculates the squared length of a quat
 *
 * @param {ReadonlyQuat} a vector to calculate squared length of
 * @returns {Number} squared length of a
 * @function
 */
quat$2.len = len$2;
var squaredLength$2 = vec4$1.squaredLength;
/**
 * Alias for {@link quat.squaredLength}
 * @function
 */
quat$2.squaredLength = squaredLength$2;
var sqrLen$2 = squaredLength$2;
/**
 * Normalize a quat
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a quaternion to normalize
 * @returns {quat} out
 * @function
 */
quat$2.sqrLen = sqrLen$2;
var normalize$2 = vec4$1.normalize;
/**
 * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyQuat} a The first quaternion.
 * @param {ReadonlyQuat} b The second quaternion.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
quat$2.normalize = normalize$2;
var exactEquals$2 = vec4$1.exactEquals;
/**
 * Returns whether or not the quaternions have approximately the same elements in the same position.
 *
 * @param {ReadonlyQuat} a The first vector.
 * @param {ReadonlyQuat} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
quat$2.exactEquals = exactEquals$2;
var equals$3 = vec4$1.equals;
/**
 * Sets a quaternion to represent the shortest rotation from one
 * vector to another.
 *
 * Both vectors are assumed to be unit length.
 *
 * @param {quat} out the receiving quaternion.
 * @param {ReadonlyVec3} a the initial vector
 * @param {ReadonlyVec3} b the destination vector
 * @returns {quat} out
 */
quat$2.equals = equals$3;
var rotationTo = (function () {
    var tmpvec3 = vec3$1.create();
    var xUnitVec3 = vec3$1.fromValues(1, 0, 0);
    var yUnitVec3 = vec3$1.fromValues(0, 1, 0);
    return function (out, a, b) {
        var dot = vec3$1.dot(a, b);
        if (dot < -0.999999) {
            vec3$1.cross(tmpvec3, xUnitVec3, a);
            if (vec3$1.len(tmpvec3) < 0.000001)
                vec3$1.cross(tmpvec3, yUnitVec3, a);
            vec3$1.normalize(tmpvec3, tmpvec3);
            setAxisAngle(out, tmpvec3, Math.PI);
            return out;
        } else if (dot > 0.999999) {
            out[0] = 0;
            out[1] = 0;
            out[2] = 0;
            out[3] = 1;
            return out;
        } else {
            vec3$1.cross(tmpvec3, a, b);
            out[0] = tmpvec3[0];
            out[1] = tmpvec3[1];
            out[2] = tmpvec3[2];
            out[3] = 1 + dot;
            return normalize$2(out, out);
        }
    };
}());
/**
 * Performs a spherical linear interpolation with two control points
 *
 * @param {quat} out the receiving quaternion
 * @param {ReadonlyQuat} a the first operand
 * @param {ReadonlyQuat} b the second operand
 * @param {ReadonlyQuat} c the third operand
 * @param {ReadonlyQuat} d the fourth operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {quat} out
 */
quat$2.rotationTo = rotationTo;
var sqlerp = (function () {
    var temp1 = create$3();
    var temp2 = create$3();
    return function (out, a, b, c, d, t) {
        slerp$1(temp1, a, d, t);
        slerp$1(temp2, b, c, t);
        slerp$1(out, temp1, temp2, 2 * t * (1 - t));
        return out;
    };
}());
/**
 * Sets the specified quaternion with values corresponding to the given
 * axes. Each axis is a vec3 and is expected to be unit length and
 * perpendicular to all other specified axes.
 *
 * @param {ReadonlyVec3} view  the vector representing the viewing direction
 * @param {ReadonlyVec3} right the vector representing the local "right" direction
 * @param {ReadonlyVec3} up    the vector representing the local "up" direction
 * @returns {quat} out
 */
quat$2.sqlerp = sqlerp;
var setAxes = (function () {
    var matr = mat3$1.create();
    return function (out, view, right, up) {
        matr[0] = right[0];
        matr[3] = right[1];
        matr[6] = right[2];
        matr[1] = up[0];
        matr[4] = up[1];
        matr[7] = up[2];
        matr[2] = -view[0];
        matr[5] = -view[1];
        matr[8] = -view[2];
        return normalize$2(out, fromMat3(out, matr));
    };
}());
quat$2.setAxes = setAxes;

var quat2$1 = {};

function _typeof$2(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$2 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$2 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$2(obj);
}
Object.defineProperty(quat2$1, '__esModule', { value: true });
quat2$1.create = create$2;
quat2$1.clone = clone$1;
quat2$1.fromValues = fromValues$1;
quat2$1.fromRotationTranslationValues = fromRotationTranslationValues;
quat2$1.fromRotationTranslation = fromRotationTranslation;
quat2$1.fromTranslation = fromTranslation;
quat2$1.fromRotation = fromRotation;
quat2$1.fromMat4 = fromMat4;
quat2$1.copy = copy$1;
quat2$1.identity = identity$1;
quat2$1.set = set$1;
quat2$1.getDual = getDual;
quat2$1.setDual = setDual;
quat2$1.getTranslation = getTranslation;
quat2$1.translate = translate$1;
quat2$1.rotateX = rotateX;
quat2$1.rotateY = rotateY;
quat2$1.rotateZ = rotateZ;
quat2$1.rotateByQuatAppend = rotateByQuatAppend;
quat2$1.rotateByQuatPrepend = rotateByQuatPrepend;
quat2$1.rotateAroundAxis = rotateAroundAxis;
quat2$1.add = add$1;
quat2$1.multiply = multiply$1;
quat2$1.scale = scale$1;
quat2$1.lerp = lerp$2;
quat2$1.invert = invert;
quat2$1.conjugate = conjugate;
quat2$1.normalize = normalize$1;
quat2$1.str = str$1;
quat2$1.exactEquals = exactEquals$1;
quat2$1.equals = equals$2;
quat2$1.sqrLen = quat2$1.squaredLength = quat2$1.len = quat2$1.length = quat2$1.dot = quat2$1.mul = quat2$1.setReal = quat2$1.getReal = void 0;
var glMatrix$2 = _interopRequireWildcard$2(common);
var quat$1 = _interopRequireWildcard$2(quat$2);
var mat4$1 = _interopRequireWildcard$2(mat4$2);
function _getRequireWildcardCache$2(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$2 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$2(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$2(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$2(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * Dual Quaternion<br>
 * Format: [real, dual]<br>
 * Quaternion format: XYZW<br>
 * Make sure to have normalized dual quaternions, otherwise the functions may not work as intended.<br>
 * @module quat2
 */
/**
 * Creates a new identity dual quat
 *
 * @returns {quat2} a new dual quaternion [real -> rotation, dual -> translation]
 */
function create$2() {
    var dq = new glMatrix$2.ARRAY_TYPE(8);
    if (glMatrix$2.ARRAY_TYPE != Float32Array) {
        dq[0] = 0;
        dq[1] = 0;
        dq[2] = 0;
        dq[4] = 0;
        dq[5] = 0;
        dq[6] = 0;
        dq[7] = 0;
    }
    dq[3] = 1;
    return dq;
}
/**
 * Creates a new quat initialized with values from an existing quaternion
 *
 * @param {ReadonlyQuat2} a dual quaternion to clone
 * @returns {quat2} new dual quaternion
 * @function
 */
function clone$1(a) {
    var dq = new glMatrix$2.ARRAY_TYPE(8);
    dq[0] = a[0];
    dq[1] = a[1];
    dq[2] = a[2];
    dq[3] = a[3];
    dq[4] = a[4];
    dq[5] = a[5];
    dq[6] = a[6];
    dq[7] = a[7];
    return dq;
}
/**
 * Creates a new dual quat initialized with the given values
 *
 * @param {Number} x1 X component
 * @param {Number} y1 Y component
 * @param {Number} z1 Z component
 * @param {Number} w1 W component
 * @param {Number} x2 X component
 * @param {Number} y2 Y component
 * @param {Number} z2 Z component
 * @param {Number} w2 W component
 * @returns {quat2} new dual quaternion
 * @function
 */
function fromValues$1(x1, y1, z1, w1, x2, y2, z2, w2) {
    var dq = new glMatrix$2.ARRAY_TYPE(8);
    dq[0] = x1;
    dq[1] = y1;
    dq[2] = z1;
    dq[3] = w1;
    dq[4] = x2;
    dq[5] = y2;
    dq[6] = z2;
    dq[7] = w2;
    return dq;
}
/**
 * Creates a new dual quat from the given values (quat and translation)
 *
 * @param {Number} x1 X component
 * @param {Number} y1 Y component
 * @param {Number} z1 Z component
 * @param {Number} w1 W component
 * @param {Number} x2 X component (translation)
 * @param {Number} y2 Y component (translation)
 * @param {Number} z2 Z component (translation)
 * @returns {quat2} new dual quaternion
 * @function
 */
function fromRotationTranslationValues(x1, y1, z1, w1, x2, y2, z2) {
    var dq = new glMatrix$2.ARRAY_TYPE(8);
    dq[0] = x1;
    dq[1] = y1;
    dq[2] = z1;
    dq[3] = w1;
    var ax = x2 * 0.5, ay = y2 * 0.5, az = z2 * 0.5;
    dq[4] = ax * w1 + ay * z1 - az * y1;
    dq[5] = ay * w1 + az * x1 - ax * z1;
    dq[6] = az * w1 + ax * y1 - ay * x1;
    dq[7] = -ax * x1 - ay * y1 - az * z1;
    return dq;
}
/**
 * Creates a dual quat from a quaternion and a translation
 *
 * @param {ReadonlyQuat2} dual quaternion receiving operation result
 * @param {ReadonlyQuat} q a normalized quaternion
 * @param {ReadonlyVec3} t tranlation vector
 * @returns {quat2} dual quaternion receiving operation result
 * @function
 */
function fromRotationTranslation(out, q, t) {
    var ax = t[0] * 0.5, ay = t[1] * 0.5, az = t[2] * 0.5, bx = q[0], by = q[1], bz = q[2], bw = q[3];
    out[0] = bx;
    out[1] = by;
    out[2] = bz;
    out[3] = bw;
    out[4] = ax * bw + ay * bz - az * by;
    out[5] = ay * bw + az * bx - ax * bz;
    out[6] = az * bw + ax * by - ay * bx;
    out[7] = -ax * bx - ay * by - az * bz;
    return out;
}
/**
 * Creates a dual quat from a translation
 *
 * @param {ReadonlyQuat2} dual quaternion receiving operation result
 * @param {ReadonlyVec3} t translation vector
 * @returns {quat2} dual quaternion receiving operation result
 * @function
 */
function fromTranslation(out, t) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    out[4] = t[0] * 0.5;
    out[5] = t[1] * 0.5;
    out[6] = t[2] * 0.5;
    out[7] = 0;
    return out;
}
/**
 * Creates a dual quat from a quaternion
 *
 * @param {ReadonlyQuat2} dual quaternion receiving operation result
 * @param {ReadonlyQuat} q the quaternion
 * @returns {quat2} dual quaternion receiving operation result
 * @function
 */
function fromRotation(out, q) {
    out[0] = q[0];
    out[1] = q[1];
    out[2] = q[2];
    out[3] = q[3];
    out[4] = 0;
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
    return out;
}
/**
 * Creates a new dual quat from a matrix (4x4)
 *
 * @param {quat2} out the dual quaternion
 * @param {ReadonlyMat4} a the matrix
 * @returns {quat2} dual quat receiving operation result
 * @function
 */
function fromMat4(out, a) {
    //TODO Optimize this
    var outer = quat$1.create();
    mat4$1.getRotation(outer, a);
    var t = new glMatrix$2.ARRAY_TYPE(3);
    mat4$1.getTranslation(t, a);
    fromRotationTranslation(out, outer, t);
    return out;
}
/**
 * Copy the values from one dual quat to another
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the source dual quaternion
 * @returns {quat2} out
 * @function
 */
function copy$1(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    return out;
}
/**
 * Set a dual quat to the identity dual quaternion
 *
 * @param {quat2} out the receiving quaternion
 * @returns {quat2} out
 */
function identity$1(out) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    out[4] = 0;
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
    return out;
}
/**
 * Set the components of a dual quat to the given values
 *
 * @param {quat2} out the receiving quaternion
 * @param {Number} x1 X component
 * @param {Number} y1 Y component
 * @param {Number} z1 Z component
 * @param {Number} w1 W component
 * @param {Number} x2 X component
 * @param {Number} y2 Y component
 * @param {Number} z2 Z component
 * @param {Number} w2 W component
 * @returns {quat2} out
 * @function
 */
function set$1(out, x1, y1, z1, w1, x2, y2, z2, w2) {
    out[0] = x1;
    out[1] = y1;
    out[2] = z1;
    out[3] = w1;
    out[4] = x2;
    out[5] = y2;
    out[6] = z2;
    out[7] = w2;
    return out;
}
/**
 * Gets the real part of a dual quat
 * @param  {quat} out real part
 * @param  {ReadonlyQuat2} a Dual Quaternion
 * @return {quat} real part
 */
var getReal = quat$1.copy;
/**
 * Gets the dual part of a dual quat
 * @param  {quat} out dual part
 * @param  {ReadonlyQuat2} a Dual Quaternion
 * @return {quat} dual part
 */
quat2$1.getReal = getReal;
function getDual(out, a) {
    out[0] = a[4];
    out[1] = a[5];
    out[2] = a[6];
    out[3] = a[7];
    return out;
}
/**
 * Set the real component of a dual quat to the given quaternion
 *
 * @param {quat2} out the receiving quaternion
 * @param {ReadonlyQuat} q a quaternion representing the real part
 * @returns {quat2} out
 * @function
 */
var setReal = quat$1.copy;
/**
 * Set the dual component of a dual quat to the given quaternion
 *
 * @param {quat2} out the receiving quaternion
 * @param {ReadonlyQuat} q a quaternion representing the dual part
 * @returns {quat2} out
 * @function
 */
quat2$1.setReal = setReal;
function setDual(out, q) {
    out[4] = q[0];
    out[5] = q[1];
    out[6] = q[2];
    out[7] = q[3];
    return out;
}
/**
 * Gets the translation of a normalized dual quat
 * @param  {vec3} out translation
 * @param  {ReadonlyQuat2} a Dual Quaternion to be decomposed
 * @return {vec3} translation
 */
function getTranslation(out, a) {
    var ax = a[4], ay = a[5], az = a[6], aw = a[7], bx = -a[0], by = -a[1], bz = -a[2], bw = a[3];
    out[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
    out[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
    out[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
    return out;
}
/**
 * Translates a dual quat by the given vector
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the dual quaternion to translate
 * @param {ReadonlyVec3} v vector to translate by
 * @returns {quat2} out
 */
function translate$1(out, a, v) {
    var ax1 = a[0], ay1 = a[1], az1 = a[2], aw1 = a[3], bx1 = v[0] * 0.5, by1 = v[1] * 0.5, bz1 = v[2] * 0.5, ax2 = a[4], ay2 = a[5], az2 = a[6], aw2 = a[7];
    out[0] = ax1;
    out[1] = ay1;
    out[2] = az1;
    out[3] = aw1;
    out[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2;
    out[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2;
    out[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2;
    out[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2;
    return out;
}
/**
 * Rotates a dual quat around the X axis
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the dual quaternion to rotate
 * @param {number} rad how far should the rotation be
 * @returns {quat2} out
 */
function rotateX(out, a, rad) {
    var bx = -a[0], by = -a[1], bz = -a[2], bw = a[3], ax = a[4], ay = a[5], az = a[6], aw = a[7], ax1 = ax * bw + aw * bx + ay * bz - az * by, ay1 = ay * bw + aw * by + az * bx - ax * bz, az1 = az * bw + aw * bz + ax * by - ay * bx, aw1 = aw * bw - ax * bx - ay * by - az * bz;
    quat$1.rotateX(out, a, rad);
    bx = out[0];
    by = out[1];
    bz = out[2];
    bw = out[3];
    out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
    out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
    out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
    out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
    return out;
}
/**
 * Rotates a dual quat around the Y axis
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the dual quaternion to rotate
 * @param {number} rad how far should the rotation be
 * @returns {quat2} out
 */
function rotateY(out, a, rad) {
    var bx = -a[0], by = -a[1], bz = -a[2], bw = a[3], ax = a[4], ay = a[5], az = a[6], aw = a[7], ax1 = ax * bw + aw * bx + ay * bz - az * by, ay1 = ay * bw + aw * by + az * bx - ax * bz, az1 = az * bw + aw * bz + ax * by - ay * bx, aw1 = aw * bw - ax * bx - ay * by - az * bz;
    quat$1.rotateY(out, a, rad);
    bx = out[0];
    by = out[1];
    bz = out[2];
    bw = out[3];
    out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
    out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
    out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
    out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
    return out;
}
/**
 * Rotates a dual quat around the Z axis
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the dual quaternion to rotate
 * @param {number} rad how far should the rotation be
 * @returns {quat2} out
 */
function rotateZ(out, a, rad) {
    var bx = -a[0], by = -a[1], bz = -a[2], bw = a[3], ax = a[4], ay = a[5], az = a[6], aw = a[7], ax1 = ax * bw + aw * bx + ay * bz - az * by, ay1 = ay * bw + aw * by + az * bx - ax * bz, az1 = az * bw + aw * bz + ax * by - ay * bx, aw1 = aw * bw - ax * bx - ay * by - az * bz;
    quat$1.rotateZ(out, a, rad);
    bx = out[0];
    by = out[1];
    bz = out[2];
    bw = out[3];
    out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
    out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
    out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
    out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
    return out;
}
/**
 * Rotates a dual quat by a given quaternion (a * q)
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the dual quaternion to rotate
 * @param {ReadonlyQuat} q quaternion to rotate by
 * @returns {quat2} out
 */
function rotateByQuatAppend(out, a, q) {
    var qx = q[0], qy = q[1], qz = q[2], qw = q[3], ax = a[0], ay = a[1], az = a[2], aw = a[3];
    out[0] = ax * qw + aw * qx + ay * qz - az * qy;
    out[1] = ay * qw + aw * qy + az * qx - ax * qz;
    out[2] = az * qw + aw * qz + ax * qy - ay * qx;
    out[3] = aw * qw - ax * qx - ay * qy - az * qz;
    ax = a[4];
    ay = a[5];
    az = a[6];
    aw = a[7];
    out[4] = ax * qw + aw * qx + ay * qz - az * qy;
    out[5] = ay * qw + aw * qy + az * qx - ax * qz;
    out[6] = az * qw + aw * qz + ax * qy - ay * qx;
    out[7] = aw * qw - ax * qx - ay * qy - az * qz;
    return out;
}
/**
 * Rotates a dual quat by a given quaternion (q * a)
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat} q quaternion to rotate by
 * @param {ReadonlyQuat2} a the dual quaternion to rotate
 * @returns {quat2} out
 */
function rotateByQuatPrepend(out, q, a) {
    var qx = q[0], qy = q[1], qz = q[2], qw = q[3], bx = a[0], by = a[1], bz = a[2], bw = a[3];
    out[0] = qx * bw + qw * bx + qy * bz - qz * by;
    out[1] = qy * bw + qw * by + qz * bx - qx * bz;
    out[2] = qz * bw + qw * bz + qx * by - qy * bx;
    out[3] = qw * bw - qx * bx - qy * by - qz * bz;
    bx = a[4];
    by = a[5];
    bz = a[6];
    bw = a[7];
    out[4] = qx * bw + qw * bx + qy * bz - qz * by;
    out[5] = qy * bw + qw * by + qz * bx - qx * bz;
    out[6] = qz * bw + qw * bz + qx * by - qy * bx;
    out[7] = qw * bw - qx * bx - qy * by - qz * bz;
    return out;
}
/**
 * Rotates a dual quat around a given axis. Does the normalisation automatically
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the dual quaternion to rotate
 * @param {ReadonlyVec3} axis the axis to rotate around
 * @param {Number} rad how far the rotation should be
 * @returns {quat2} out
 */
function rotateAroundAxis(out, a, axis, rad) {
    //Special case for rad = 0
    if (Math.abs(rad) < glMatrix$2.EPSILON) {
        return copy$1(out, a);
    }
    var axisLength = Math.hypot(axis[0], axis[1], axis[2]);
    rad = rad * 0.5;
    var s = Math.sin(rad);
    var bx = s * axis[0] / axisLength;
    var by = s * axis[1] / axisLength;
    var bz = s * axis[2] / axisLength;
    var bw = Math.cos(rad);
    var ax1 = a[0], ay1 = a[1], az1 = a[2], aw1 = a[3];
    out[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
    out[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
    out[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
    out[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
    var ax = a[4], ay = a[5], az = a[6], aw = a[7];
    out[4] = ax * bw + aw * bx + ay * bz - az * by;
    out[5] = ay * bw + aw * by + az * bx - ax * bz;
    out[6] = az * bw + aw * bz + ax * by - ay * bx;
    out[7] = aw * bw - ax * bx - ay * by - az * bz;
    return out;
}
/**
 * Adds two dual quat's
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the first operand
 * @param {ReadonlyQuat2} b the second operand
 * @returns {quat2} out
 * @function
 */
function add$1(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    out[4] = a[4] + b[4];
    out[5] = a[5] + b[5];
    out[6] = a[6] + b[6];
    out[7] = a[7] + b[7];
    return out;
}
/**
 * Multiplies two dual quat's
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a the first operand
 * @param {ReadonlyQuat2} b the second operand
 * @returns {quat2} out
 */
function multiply$1(out, a, b) {
    var ax0 = a[0], ay0 = a[1], az0 = a[2], aw0 = a[3], bx1 = b[4], by1 = b[5], bz1 = b[6], bw1 = b[7], ax1 = a[4], ay1 = a[5], az1 = a[6], aw1 = a[7], bx0 = b[0], by0 = b[1], bz0 = b[2], bw0 = b[3];
    out[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
    out[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
    out[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
    out[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
    out[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
    out[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
    out[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
    out[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
    return out;
}
/**
 * Alias for {@link quat2.multiply}
 * @function
 */
var mul$1 = multiply$1;
/**
 * Scales a dual quat by a scalar number
 *
 * @param {quat2} out the receiving dual quat
 * @param {ReadonlyQuat2} a the dual quat to scale
 * @param {Number} b amount to scale the dual quat by
 * @returns {quat2} out
 * @function
 */
quat2$1.mul = mul$1;
function scale$1(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    out[2] = a[2] * b;
    out[3] = a[3] * b;
    out[4] = a[4] * b;
    out[5] = a[5] * b;
    out[6] = a[6] * b;
    out[7] = a[7] * b;
    return out;
}
/**
 * Calculates the dot product of two dual quat's (The dot product of the real parts)
 *
 * @param {ReadonlyQuat2} a the first operand
 * @param {ReadonlyQuat2} b the second operand
 * @returns {Number} dot product of a and b
 * @function
 */
var dot$2 = quat$1.dot;
/**
 * Performs a linear interpolation between two dual quats's
 * NOTE: The resulting dual quaternions won't always be normalized (The error is most noticeable when t = 0.5)
 *
 * @param {quat2} out the receiving dual quat
 * @param {ReadonlyQuat2} a the first operand
 * @param {ReadonlyQuat2} b the second operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {quat2} out
 */
quat2$1.dot = dot$2;
function lerp$2(out, a, b, t) {
    var mt = 1 - t;
    if (dot$2(a, b) < 0)
        t = -t;
    out[0] = a[0] * mt + b[0] * t;
    out[1] = a[1] * mt + b[1] * t;
    out[2] = a[2] * mt + b[2] * t;
    out[3] = a[3] * mt + b[3] * t;
    out[4] = a[4] * mt + b[4] * t;
    out[5] = a[5] * mt + b[5] * t;
    out[6] = a[6] * mt + b[6] * t;
    out[7] = a[7] * mt + b[7] * t;
    return out;
}
/**
 * Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a dual quat to calculate inverse of
 * @returns {quat2} out
 */
function invert(out, a) {
    var sqlen = squaredLength$1(a);
    out[0] = -a[0] / sqlen;
    out[1] = -a[1] / sqlen;
    out[2] = -a[2] / sqlen;
    out[3] = a[3] / sqlen;
    out[4] = -a[4] / sqlen;
    out[5] = -a[5] / sqlen;
    out[6] = -a[6] / sqlen;
    out[7] = a[7] / sqlen;
    return out;
}
/**
 * Calculates the conjugate of a dual quat
 * If the dual quaternion is normalized, this function is faster than quat2.inverse and produces the same result.
 *
 * @param {quat2} out the receiving quaternion
 * @param {ReadonlyQuat2} a quat to calculate conjugate of
 * @returns {quat2} out
 */
function conjugate(out, a) {
    out[0] = -a[0];
    out[1] = -a[1];
    out[2] = -a[2];
    out[3] = a[3];
    out[4] = -a[4];
    out[5] = -a[5];
    out[6] = -a[6];
    out[7] = a[7];
    return out;
}
/**
 * Calculates the length of a dual quat
 *
 * @param {ReadonlyQuat2} a dual quat to calculate length of
 * @returns {Number} length of a
 * @function
 */
var length$1 = quat$1.length;
/**
 * Alias for {@link quat2.length}
 * @function
 */
quat2$1.length = length$1;
var len$1 = length$1;
/**
 * Calculates the squared length of a dual quat
 *
 * @param {ReadonlyQuat2} a dual quat to calculate squared length of
 * @returns {Number} squared length of a
 * @function
 */
quat2$1.len = len$1;
var squaredLength$1 = quat$1.squaredLength;
/**
 * Alias for {@link quat2.squaredLength}
 * @function
 */
quat2$1.squaredLength = squaredLength$1;
var sqrLen$1 = squaredLength$1;
/**
 * Normalize a dual quat
 *
 * @param {quat2} out the receiving dual quaternion
 * @param {ReadonlyQuat2} a dual quaternion to normalize
 * @returns {quat2} out
 * @function
 */
quat2$1.sqrLen = sqrLen$1;
function normalize$1(out, a) {
    var magnitude = squaredLength$1(a);
    if (magnitude > 0) {
        magnitude = Math.sqrt(magnitude);
        var a0 = a[0] / magnitude;
        var a1 = a[1] / magnitude;
        var a2 = a[2] / magnitude;
        var a3 = a[3] / magnitude;
        var b0 = a[4];
        var b1 = a[5];
        var b2 = a[6];
        var b3 = a[7];
        var a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3;
        out[0] = a0;
        out[1] = a1;
        out[2] = a2;
        out[3] = a3;
        out[4] = (b0 - a0 * a_dot_b) / magnitude;
        out[5] = (b1 - a1 * a_dot_b) / magnitude;
        out[6] = (b2 - a2 * a_dot_b) / magnitude;
        out[7] = (b3 - a3 * a_dot_b) / magnitude;
    }
    return out;
}
/**
 * Returns a string representation of a dual quatenion
 *
 * @param {ReadonlyQuat2} a dual quaternion to represent as a string
 * @returns {String} string representation of the dual quat
 */
function str$1(a) {
    return 'quat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ')';
}
/**
 * Returns whether or not the dual quaternions have exactly the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyQuat2} a the first dual quaternion.
 * @param {ReadonlyQuat2} b the second dual quaternion.
 * @returns {Boolean} true if the dual quaternions are equal, false otherwise.
 */
function exactEquals$1(a, b) {
    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];
}
/**
 * Returns whether or not the dual quaternions have approximately the same elements in the same position.
 *
 * @param {ReadonlyQuat2} a the first dual quat.
 * @param {ReadonlyQuat2} b the second dual quat.
 * @returns {Boolean} true if the dual quats are equal, false otherwise.
 */
function equals$2(a, b) {
    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7];
    var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
    return Math.abs(a0 - b0) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix$2.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7));
}

var vec2$1 = {};

function _typeof$1(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof$1 = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof$1 = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof$1(obj);
}
Object.defineProperty(vec2$1, '__esModule', { value: true });
vec2$1.create = create$1;
vec2$1.clone = clone;
vec2$1.fromValues = fromValues;
vec2$1.copy = copy;
vec2$1.set = set;
vec2$1.add = add;
vec2$1.subtract = subtract;
vec2$1.multiply = multiply;
vec2$1.divide = divide;
vec2$1.ceil = ceil;
vec2$1.floor = floor;
vec2$1.min = min;
vec2$1.max = max;
vec2$1.round = round;
vec2$1.scale = scale;
vec2$1.scaleAndAdd = scaleAndAdd;
vec2$1.distance = distance;
vec2$1.squaredDistance = squaredDistance;
vec2$1.length = length;
vec2$1.squaredLength = squaredLength;
vec2$1.negate = negate;
vec2$1.inverse = inverse;
vec2$1.normalize = normalize;
vec2$1.dot = dot$1;
vec2$1.cross = cross;
vec2$1.lerp = lerp$1;
vec2$1.random = random;
vec2$1.transformMat2 = transformMat2;
vec2$1.transformMat2d = transformMat2d;
vec2$1.transformMat3 = transformMat3;
vec2$1.transformMat4 = transformMat4;
vec2$1.rotate = rotate$1;
vec2$1.angle = angle;
vec2$1.zero = zero;
vec2$1.str = str;
vec2$1.exactEquals = exactEquals;
vec2$1.equals = equals$1;
vec2$1.forEach = vec2$1.sqrLen = vec2$1.sqrDist = vec2$1.dist = vec2$1.div = vec2$1.mul = vec2$1.sub = vec2$1.len = void 0;
var glMatrix$1 = _interopRequireWildcard$1(common);
function _getRequireWildcardCache$1(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache$1 = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard$1(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof$1(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache$1(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 2 Dimensional Vector
 * @module vec2
 */
/**
 * Creates a new, empty vec2
 *
 * @returns {vec2} a new 2D vector
 */
function create$1() {
    var out = new glMatrix$1.ARRAY_TYPE(2);
    if (glMatrix$1.ARRAY_TYPE != Float32Array) {
        out[0] = 0;
        out[1] = 0;
    }
    return out;
}
/**
 * Creates a new vec2 initialized with values from an existing vector
 *
 * @param {ReadonlyVec2} a vector to clone
 * @returns {vec2} a new 2D vector
 */
function clone(a) {
    var out = new glMatrix$1.ARRAY_TYPE(2);
    out[0] = a[0];
    out[1] = a[1];
    return out;
}
/**
 * Creates a new vec2 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @returns {vec2} a new 2D vector
 */
function fromValues(x, y) {
    var out = new glMatrix$1.ARRAY_TYPE(2);
    out[0] = x;
    out[1] = y;
    return out;
}
/**
 * Copy the values from one vec2 to another
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the source vector
 * @returns {vec2} out
 */
function copy(out, a) {
    out[0] = a[0];
    out[1] = a[1];
    return out;
}
/**
 * Set the components of a vec2 to the given values
 *
 * @param {vec2} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @returns {vec2} out
 */
function set(out, x, y) {
    out[0] = x;
    out[1] = y;
    return out;
}
/**
 * Adds two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec2} out
 */
function add(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    return out;
}
/**
 * Subtracts vector b from vector a
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec2} out
 */
function subtract(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    return out;
}
/**
 * Multiplies two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec2} out
 */
function multiply(out, a, b) {
    out[0] = a[0] * b[0];
    out[1] = a[1] * b[1];
    return out;
}
/**
 * Divides two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec2} out
 */
function divide(out, a, b) {
    out[0] = a[0] / b[0];
    out[1] = a[1] / b[1];
    return out;
}
/**
 * Math.ceil the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a vector to ceil
 * @returns {vec2} out
 */
function ceil(out, a) {
    out[0] = Math.ceil(a[0]);
    out[1] = Math.ceil(a[1]);
    return out;
}
/**
 * Math.floor the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a vector to floor
 * @returns {vec2} out
 */
function floor(out, a) {
    out[0] = Math.floor(a[0]);
    out[1] = Math.floor(a[1]);
    return out;
}
/**
 * Returns the minimum of two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec2} out
 */
function min(out, a, b) {
    out[0] = Math.min(a[0], b[0]);
    out[1] = Math.min(a[1], b[1]);
    return out;
}
/**
 * Returns the maximum of two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec2} out
 */
function max(out, a, b) {
    out[0] = Math.max(a[0], b[0]);
    out[1] = Math.max(a[1], b[1]);
    return out;
}
/**
 * Math.round the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a vector to round
 * @returns {vec2} out
 */
function round(out, a) {
    out[0] = Math.round(a[0]);
    out[1] = Math.round(a[1]);
    return out;
}
/**
 * Scales a vec2 by a scalar number
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec2} out
 */
function scale(out, a, b) {
    out[0] = a[0] * b;
    out[1] = a[1] * b;
    return out;
}
/**
 * Adds two vec2's after scaling the second operand by a scalar value
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec2} out
 */
function scaleAndAdd(out, a, b, scale) {
    out[0] = a[0] + b[0] * scale;
    out[1] = a[1] + b[1] * scale;
    return out;
}
/**
 * Calculates the euclidian distance between two vec2's
 *
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {Number} distance between a and b
 */
function distance(a, b) {
    var x = b[0] - a[0], y = b[1] - a[1];
    return Math.hypot(x, y);
}
/**
 * Calculates the squared euclidian distance between two vec2's
 *
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {Number} squared distance between a and b
 */
function squaredDistance(a, b) {
    var x = b[0] - a[0], y = b[1] - a[1];
    return x * x + y * y;
}
/**
 * Calculates the length of a vec2
 *
 * @param {ReadonlyVec2} a vector to calculate length of
 * @returns {Number} length of a
 */
function length(a) {
    var x = a[0], y = a[1];
    return Math.hypot(x, y);
}
/**
 * Calculates the squared length of a vec2
 *
 * @param {ReadonlyVec2} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
function squaredLength(a) {
    var x = a[0], y = a[1];
    return x * x + y * y;
}
/**
 * Negates the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a vector to negate
 * @returns {vec2} out
 */
function negate(out, a) {
    out[0] = -a[0];
    out[1] = -a[1];
    return out;
}
/**
 * Returns the inverse of the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a vector to invert
 * @returns {vec2} out
 */
function inverse(out, a) {
    out[0] = 1 / a[0];
    out[1] = 1 / a[1];
    return out;
}
/**
 * Normalize a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a vector to normalize
 * @returns {vec2} out
 */
function normalize(out, a) {
    var x = a[0], y = a[1];
    var len = x * x + y * y;
    if (len > 0) {
        //TODO: evaluate use of glm_invsqrt here?
        len = 1 / Math.sqrt(len);
    }
    out[0] = a[0] * len;
    out[1] = a[1] * len;
    return out;
}
/**
 * Calculates the dot product of two vec2's
 *
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {Number} dot product of a and b
 */
function dot$1(a, b) {
    return a[0] * b[0] + a[1] * b[1];
}
/**
 * Computes the cross product of two vec2's
 * Note that the cross product must by definition produce a 3D vector
 *
 * @param {vec3} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @returns {vec3} out
 */
function cross(out, a, b) {
    var z = a[0] * b[1] - a[1] * b[0];
    out[0] = out[1] = 0;
    out[2] = z;
    return out;
}
/**
 * Performs a linear interpolation between two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the first operand
 * @param {ReadonlyVec2} b the second operand
 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
 * @returns {vec2} out
 */
function lerp$1(out, a, b, t) {
    var ax = a[0], ay = a[1];
    out[0] = ax + t * (b[0] - ax);
    out[1] = ay + t * (b[1] - ay);
    return out;
}
/**
 * Generates a random vector with the given scale
 *
 * @param {vec2} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec2} out
 */
function random(out, scale) {
    scale = scale || 1;
    var r = glMatrix$1.RANDOM() * 2 * Math.PI;
    out[0] = Math.cos(r) * scale;
    out[1] = Math.sin(r) * scale;
    return out;
}
/**
 * Transforms the vec2 with a mat2
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the vector to transform
 * @param {ReadonlyMat2} m matrix to transform with
 * @returns {vec2} out
 */
function transformMat2(out, a, m) {
    var x = a[0], y = a[1];
    out[0] = m[0] * x + m[2] * y;
    out[1] = m[1] * x + m[3] * y;
    return out;
}
/**
 * Transforms the vec2 with a mat2d
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the vector to transform
 * @param {ReadonlyMat2d} m matrix to transform with
 * @returns {vec2} out
 */
function transformMat2d(out, a, m) {
    var x = a[0], y = a[1];
    out[0] = m[0] * x + m[2] * y + m[4];
    out[1] = m[1] * x + m[3] * y + m[5];
    return out;
}
/**
 * Transforms the vec2 with a mat3
 * 3rd vector component is implicitly '1'
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the vector to transform
 * @param {ReadonlyMat3} m matrix to transform with
 * @returns {vec2} out
 */
function transformMat3(out, a, m) {
    var x = a[0], y = a[1];
    out[0] = m[0] * x + m[3] * y + m[6];
    out[1] = m[1] * x + m[4] * y + m[7];
    return out;
}
/**
 * Transforms the vec2 with a mat4
 * 3rd vector component is implicitly '0'
 * 4th vector component is implicitly '1'
 *
 * @param {vec2} out the receiving vector
 * @param {ReadonlyVec2} a the vector to transform
 * @param {ReadonlyMat4} m matrix to transform with
 * @returns {vec2} out
 */
function transformMat4(out, a, m) {
    var x = a[0];
    var y = a[1];
    out[0] = m[0] * x + m[4] * y + m[12];
    out[1] = m[1] * x + m[5] * y + m[13];
    return out;
}
/**
 * Rotate a 2D vector
 * @param {vec2} out The receiving vec2
 * @param {ReadonlyVec2} a The vec2 point to rotate
 * @param {ReadonlyVec2} b The origin of the rotation
 * @param {Number} rad The angle of rotation in radians
 * @returns {vec2} out
 */
function rotate$1(out, a, b, rad) {
    //Translate point to the origin
    var p0 = a[0] - b[0], p1 = a[1] - b[1], sinC = Math.sin(rad), cosC = Math.cos(rad);
    //perform rotation and translate to correct position
    out[0] = p0 * cosC - p1 * sinC + b[0];
    out[1] = p0 * sinC + p1 * cosC + b[1];
    return out;
}
/**
 * Get the angle between two 2D vectors
 * @param {ReadonlyVec2} a The first operand
 * @param {ReadonlyVec2} b The second operand
 * @returns {Number} The angle in radians
 */
function angle(a, b) {
    var x1 = a[0], y1 = a[1], x2 = b[0], y2 = b[1],
        // mag is the product of the magnitudes of a and b
        mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2),
        // mag &&.. short circuits if mag == 0
        cosine = mag && (x1 * x2 + y1 * y2) / mag;
    // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1
    return Math.acos(Math.min(Math.max(cosine, -1), 1));
}
/**
 * Set the components of a vec2 to zero
 *
 * @param {vec2} out the receiving vector
 * @returns {vec2} out
 */
function zero(out) {
    out[0] = 0;
    out[1] = 0;
    return out;
}
/**
 * Returns a string representation of a vector
 *
 * @param {ReadonlyVec2} a vector to represent as a string
 * @returns {String} string representation of the vector
 */
function str(a) {
    return 'vec2(' + a[0] + ', ' + a[1] + ')';
}
/**
 * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
 *
 * @param {ReadonlyVec2} a The first vector.
 * @param {ReadonlyVec2} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function exactEquals(a, b) {
    return a[0] === b[0] && a[1] === b[1];
}
/**
 * Returns whether or not the vectors have approximately the same elements in the same position.
 *
 * @param {ReadonlyVec2} a The first vector.
 * @param {ReadonlyVec2} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
function equals$1(a, b) {
    var a0 = a[0], a1 = a[1];
    var b0 = b[0], b1 = b[1];
    return Math.abs(a0 - b0) <= glMatrix$1.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix$1.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1));
}
/**
 * Alias for {@link vec2.length}
 * @function
 */
var len = length;
/**
 * Alias for {@link vec2.subtract}
 * @function
 */
vec2$1.len = len;
var sub = subtract;
/**
 * Alias for {@link vec2.multiply}
 * @function
 */
vec2$1.sub = sub;
var mul = multiply;
/**
 * Alias for {@link vec2.divide}
 * @function
 */
vec2$1.mul = mul;
var div = divide;
/**
 * Alias for {@link vec2.distance}
 * @function
 */
vec2$1.div = div;
var dist = distance;
/**
 * Alias for {@link vec2.squaredDistance}
 * @function
 */
vec2$1.dist = dist;
var sqrDist = squaredDistance;
/**
 * Alias for {@link vec2.squaredLength}
 * @function
 */
vec2$1.sqrDist = sqrDist;
var sqrLen = squaredLength;
/**
 * Perform some operation over an array of vec2s.
 *
 * @param {Array} a the array of vectors to iterate over
 * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
 * @param {Number} offset Number of elements to skip at the beginning of the array
 * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
 * @param {Function} fn Function to call for each vector in the array
 * @param {Object} [arg] additional argument to pass to fn
 * @returns {Array} a
 * @function
 */
vec2$1.sqrLen = sqrLen;
var forEach = (function () {
    var vec = create$1();
    return function (a, stride, offset, count, fn, arg) {
        var i, l;
        if (!stride) {
            stride = 2;
        }
        if (!offset) {
            offset = 0;
        }
        if (count) {
            l = Math.min(count * stride + offset, a.length);
        } else {
            l = a.length;
        }
        for (i = offset; i < l; i += stride) {
            vec[0] = a[i];
            vec[1] = a[i + 1];
            fn(vec, vec, arg);
            a[i] = vec[0];
            a[i + 1] = vec[1];
        }
        return a;
    };
}());
vec2$1.forEach = forEach;

function _typeof(obj) {
    '@babel/helpers - typeof';
    if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
        _typeof = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof = function _typeof(obj) {
            return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
        };
    }
    return _typeof(obj);
}
Object.defineProperty(cjs, '__esModule', { value: true });
var vec4_1 = cjs.vec4 = vec3_1 = cjs.vec3 = cjs.vec2 = cjs.quat2 = quat_1 = cjs.quat = mat4_1 = cjs.mat4 = mat3_1 = cjs.mat3 = cjs.mat2d = mat2_1 = cjs.mat2 = cjs.glMatrix = void 0;
var glMatrix = _interopRequireWildcard(common);
cjs.glMatrix = glMatrix;
var mat2 = _interopRequireWildcard(mat2$1);
var mat2_1 = cjs.mat2 = mat2;
var mat2d = _interopRequireWildcard(mat2d$1);
cjs.mat2d = mat2d;
var mat3 = _interopRequireWildcard(mat3$2);
var mat3_1 = cjs.mat3 = mat3;
var mat4 = _interopRequireWildcard(mat4$2);
var mat4_1 = cjs.mat4 = mat4;
var quat = _interopRequireWildcard(quat$2);
var quat_1 = cjs.quat = quat;
var quat2 = _interopRequireWildcard(quat2$1);
cjs.quat2 = quat2;
var vec2 = _interopRequireWildcard(vec2$1);
cjs.vec2 = vec2;
var vec3 = _interopRequireWildcard(vec3$2);
var vec3_1 = cjs.vec3 = vec3;
var vec4 = _interopRequireWildcard(vec4$2);
vec4_1 = cjs.vec4 = vec4;
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== 'function')
        return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') {
        return { 'default': obj };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj['default'] = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}

//      
const layout$c = createLayout([
    {
        type: 'Float32',
        name: 'a_globe_pos',
        components: 3
    },
    {
        type: 'Float32',
        name: 'a_uv',
        components: 2
    }
]);
const {members: members$5, size: size$5, alignment: alignment$5} = layout$c;

//      
const posAttributesGlobeExt = createLayout([{
        name: 'a_pos_3',
        components: 3,
        type: 'Int16'
    }]);
var posAttributes = createLayout([{
        name: 'a_pos',
        type: 'Int16',
        components: 2
    }]);

var whootsJs = {exports: {}};

(function (module, exports) {
	(function (global, factory) {
	    factory(exports) ;
	}(this, function (exports) {
	    /**
	 * getURL
	 *
	 * @param    {String}  baseUrl  Base url of the WMS server
	 * @param    {String}  layer    Layer name
	 * @param    {Number}  x        Tile coordinate x
	 * @param    {Number}  y        Tile coordinate y
	 * @param    {Number}  z        Tile zoom
	 * @param    {Object}  [options]
	 * @param    {String}  [options.format='image/png']
	 * @param    {String}  [options.service='WMS']
	 * @param    {String}  [options.version='1.1.1']
	 * @param    {String}  [options.request='GetMap']
	 * @param    {String}  [options.srs='EPSG:3857']
	 * @param    {Number}  [options.width='256']
	 * @param    {Number}  [options.height='256']
	 * @returns  {String}  url
	 * @example
	 * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015';
	 * var layer = 'Natural2015';
	 * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19);
	 */
	    function getURL(baseUrl, layer, x, y, z, options) {
	        options = options || {};
	        var url = baseUrl + '?' + [
	            'bbox=' + getTileBBox(x, y, z),
	            'format=' + (options.format || 'image/png'),
	            'service=' + (options.service || 'WMS'),
	            'version=' + (options.version || '1.1.1'),
	            'request=' + (options.request || 'GetMap'),
	            'srs=' + (options.srs || 'EPSG:3857'),
	            'width=' + (options.width || 256),
	            'height=' + (options.height || 256),
	            'layers=' + layer
	        ].join('&');
	        return url;
	    }
	    /**
	 * getTileBBox
	 *
	 * @param    {Number}  x  Tile coordinate x
	 * @param    {Number}  y  Tile coordinate y
	 * @param    {Number}  z  Tile zoom
	 * @returns  {String}  String of the bounding box
	 */
	    function getTileBBox(x, y, z) {
	        // for Google/OSM tile scheme we need to alter the y
	        y = Math.pow(2, z) - y - 1;
	        var min = getMercCoords(x * 256, y * 256, z), max = getMercCoords((x + 1) * 256, (y + 1) * 256, z);
	        return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1];
	    }
	    /**
	 * getMercCoords
	 *
	 * @param    {Number}  x  Pixel coordinate x
	 * @param    {Number}  y  Pixel coordinate y
	 * @param    {Number}  z  Tile zoom
	 * @returns  {Array}   [x, y]
	 */
	    function getMercCoords(x, y, z) {
	        var resolution = 2 * Math.PI * 6378137 / 256 / Math.pow(2, z), merc_x = x * resolution - 2 * Math.PI * 6378137 / 2, merc_y = y * resolution - 2 * Math.PI * 6378137 / 2;
	        return [
	            merc_x,
	            merc_y
	        ];
	    }
	    exports.getURL = getURL;
	    exports.getTileBBox = getTileBBox;
	    exports.getMercCoords = getMercCoords;
	    Object.defineProperty(exports, '__esModule', { value: true });
	})); 
} (whootsJs, whootsJs.exports));

var whootsJsExports = whootsJs.exports;

//      
class CanonicalTileID {
    constructor(z, x, y) {
        this.z = z;
        this.x = x;
        this.y = y;
        this.key = calculateKey(0, z, z, x, y);
    }
    equals(id) {
        return this.z === id.z && this.x === id.x && this.y === id.y;
    }
    // given a list of urls, choose a url template and return a tile URL
    url(urls, scheme) {
        const bbox = whootsJsExports.getTileBBox(this.x, this.y, this.z);
        const quadkey = getQuadkey(this.z, this.x, this.y);
        return urls[(this.x + this.y) % urls.length].replace('{prefix}', (this.x % 16).toString(16) + (this.y % 16).toString(16)).replace(/{z}/g, String(this.z)).replace(/{x}/g, String(this.x)).replace(/{y}/g, String(scheme === 'tms' ? Math.pow(2, this.z) - this.y - 1 : this.y)).replace('{quadkey}', quadkey).replace('{bbox-epsg-3857}', bbox);
    }
    toString() {
        return `${ this.z }/${ this.x }/${ this.y }`;
    }
}
class UnwrappedTileID {
    constructor(wrap, canonical) {
        this.wrap = wrap;
        this.canonical = canonical;
        this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);
    }
}
class OverscaledTileID {
    constructor(overscaledZ, wrap, z, x, y) {
        this.overscaledZ = overscaledZ;
        this.wrap = wrap;
        this.canonical = new CanonicalTileID(z, +x, +y);
        this.key = wrap === 0 && overscaledZ === z ? this.canonical.key : calculateKey(wrap, overscaledZ, z, x, y);
    }
    equals(id) {
        return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical);
    }
    scaledTo(targetZ) {
        const zDifference = this.canonical.z - targetZ;
        if (targetZ > this.canonical.z) {
            return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);
        } else {
            return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
        }
    }
    /*
     * calculateScaledKey is an optimization:
     * when withWrap == true, implements the same as this.scaledTo(z).key,
     * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key.
     */
    calculateScaledKey(targetZ, withWrap = true) {
        if (this.overscaledZ === targetZ && withWrap)
            return this.key;
        if (targetZ > this.canonical.z) {
            return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);
        } else {
            const zDifference = this.canonical.z - targetZ;
            return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
        }
    }
    isChildOf(parent) {
        if (parent.wrap !== this.wrap) {
            // We can't be a child if we're in a different world copy
            return false;
        }
        const zDifference = this.canonical.z - parent.canonical.z;
        // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined.
        return parent.overscaledZ === 0 || parent.overscaledZ < this.overscaledZ && parent.canonical.z < this.canonical.z && parent.canonical.x === this.canonical.x >> zDifference && parent.canonical.y === this.canonical.y >> zDifference;
    }
    children(sourceMaxZoom) {
        if (this.overscaledZ >= sourceMaxZoom) {
            // return a single tile coord representing a an overscaled tile
            return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];
        }
        const z = this.canonical.z + 1;
        const x = this.canonical.x * 2;
        const y = this.canonical.y * 2;
        return [
            new OverscaledTileID(z, this.wrap, z, x, y),
            new OverscaledTileID(z, this.wrap, z, x + 1, y),
            new OverscaledTileID(z, this.wrap, z, x, y + 1),
            new OverscaledTileID(z, this.wrap, z, x + 1, y + 1)
        ];
    }
    isLessThan(rhs) {
        if (this.wrap < rhs.wrap)
            return true;
        if (this.wrap > rhs.wrap)
            return false;
        if (this.overscaledZ < rhs.overscaledZ)
            return true;
        if (this.overscaledZ > rhs.overscaledZ)
            return false;
        if (this.canonical.x < rhs.canonical.x)
            return true;
        if (this.canonical.x > rhs.canonical.x)
            return false;
        if (this.canonical.y < rhs.canonical.y)
            return true;
        return false;
    }
    wrapped() {
        return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);
    }
    unwrapTo(wrap) {
        return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y);
    }
    overscaleFactor() {
        return Math.pow(2, this.overscaledZ - this.canonical.z);
    }
    toUnwrapped() {
        return new UnwrappedTileID(this.wrap, this.canonical);
    }
    toString() {
        return `${ this.overscaledZ }/${ this.canonical.x }/${ this.canonical.y }`;
    }
}
function calculateKey(wrap, overscaledZ, z, x, y) {
    // only use 22 bits for x & y so that the key fits into MAX_SAFE_INTEGER
    const dim = 1 << Math.min(z, 22);
    let xy = dim * (y % dim) + x % dim;
    // zigzag-encode wrap if we have the room for it
    if (wrap && z < 22) {
        const bitsAvailable = 2 * (22 - z);
        xy += dim * dim * ((wrap < 0 ? -2 * wrap - 1 : 2 * wrap) % (1 << bitsAvailable));
    }
    // encode z into 5 bits (24 max) and overscaledZ into 4 bits (10 max)
    const key = (xy * 32 + z) * 16 + (overscaledZ - z);
    return key;
}
function getQuadkey(z, x, y) {
    let quadkey = '', mask;
    for (let i = z; i > 0; i--) {
        mask = 1 << i - 1;
        quadkey += (x & mask ? 1 : 0) + (y & mask ? 2 : 0);
    }
    return quadkey;
}
// For all four borders: 0 - left, 1, right, 2 - top, 3 - bottom
const neighborCoord = [
    coord => {
        let x = coord.canonical.x - 1;
        let w = coord.wrap;
        if (x < 0) {
            x = (1 << coord.canonical.z) - 1;
            w--;
        }
        return new OverscaledTileID(coord.overscaledZ, w, coord.canonical.z, x, coord.canonical.y);
    },
    coord => {
        let x = coord.canonical.x + 1;
        let w = coord.wrap;
        if (x === 1 << coord.canonical.z) {
            x = 0;
            w++;
        }
        return new OverscaledTileID(coord.overscaledZ, w, coord.canonical.z, x, coord.canonical.y);
    },
    coord => new OverscaledTileID(coord.overscaledZ, coord.wrap, coord.canonical.z, coord.canonical.x, (coord.canonical.y === 0 ? 1 << coord.canonical.z : coord.canonical.y) - 1),
    coord => new OverscaledTileID(coord.overscaledZ, coord.wrap, coord.canonical.z, coord.canonical.x, coord.canonical.y === (1 << coord.canonical.z) - 1 ? 0 : coord.canonical.y + 1)
];
register(CanonicalTileID, 'CanonicalTileID');
register(OverscaledTileID, 'OverscaledTileID', { omit: ['projMatrix'] });

//      
class Ray {
    constructor(pos_, dir_) {
        this.pos = pos_;
        this.dir = dir_;
    }
    intersectsPlane(pt, normal, out) {
        const D = vec3_1.dot(normal, this.dir);
        // ray is parallel to plane, so it misses
        if (Math.abs(D) < 0.000001) {
            return false;
        }
        const t = ((pt[0] - this.pos[0]) * normal[0] + (pt[1] - this.pos[1]) * normal[1] + (pt[2] - this.pos[2]) * normal[2]) / D;
        out[0] = this.pos[0] + this.dir[0] * t;
        out[1] = this.pos[1] + this.dir[1] * t;
        out[2] = this.pos[2] + this.dir[2] * t;
        return true;
    }
    closestPointOnSphere(center, r, out) {
        if (vec3_1.equals(this.pos, center) || r === 0) {
            out[0] = out[1] = out[2] = 0;
            return false;
        }
        const [dx, dy, dz] = this.dir;
        const px = this.pos[0] - center[0];
        const py = this.pos[1] - center[1];
        const pz = this.pos[2] - center[2];
        const a = dx * dx + dy * dy + dz * dz;
        const b = 2 * (px * dx + py * dy + pz * dz);
        const c = px * px + py * py + pz * pz - r * r;
        const d = b * b - 4 * a * c;
        if (d < 0) {
            // No intersection, find distance between closest points
            const t = Math.max(-b / 2, 0);
            const gx = px + dx * t;
            // point to globe
            const gy = py + dy * t;
            const gz = pz + dz * t;
            const glen = Math.hypot(gx, gy, gz);
            out[0] = gx * r / glen;
            out[1] = gy * r / glen;
            out[2] = gz * r / glen;
            return false;
        } else {
            const t = (-b - Math.sqrt(d)) / (2 * a);
            if (t < 0) {
                // Ray is pointing away from the sphere
                const plen = Math.hypot(px, py, pz);
                out[0] = px * r / plen;
                out[1] = py * r / plen;
                out[2] = pz * r / plen;
                return false;
            } else {
                out[0] = px + dx * t;
                out[1] = py + dy * t;
                out[2] = pz + dz * t;
                return true;
            }
        }
    }
}
class FrustumCorners {
    constructor(TL_, TR_, BR_, BL_, horizon_) {
        this.TL = TL_;
        this.TR = TR_;
        this.BR = BR_;
        this.BL = BL_;
        this.horizon = horizon_;
    }
    static fromInvProjectionMatrix(invProj, horizonFromTop, viewportHeight) {
        const TLClip = [
            -1,
            1,
            1
        ];
        const TRClip = [
            1,
            1,
            1
        ];
        const BRClip = [
            1,
            -1,
            1
        ];
        const BLClip = [
            -1,
            -1,
            1
        ];
        const TL = vec3_1.transformMat4(TLClip, TLClip, invProj);
        const TR = vec3_1.transformMat4(TRClip, TRClip, invProj);
        const BR = vec3_1.transformMat4(BRClip, BRClip, invProj);
        const BL = vec3_1.transformMat4(BLClip, BLClip, invProj);
        return new FrustumCorners(TL, TR, BR, BL, horizonFromTop / viewportHeight);
    }
}
function projectPoints(points, origin, axis) {
    let min = Infinity;
    let max = -Infinity;
    const vec = [];
    for (const point of points) {
        vec3_1.sub(vec, point, origin);
        const projection = vec3_1.dot(vec, axis);
        min = Math.min(min, projection);
        max = Math.max(max, projection);
    }
    return [
        min,
        max
    ];
}
function intersectsFrustum(frustum, aabbPoints) {
    let fullyInside = true;
    for (let p = 0; p < frustum.planes.length; p++) {
        const plane = frustum.planes[p];
        let pointsInside = 0;
        for (let i = 0; i < aabbPoints.length; i++) {
            pointsInside += vec3_1.dot(plane, aabbPoints[i]) + plane[3] >= 0;
        }
        if (pointsInside === 0)
            return 0;
        if (pointsInside !== aabbPoints.length)
            fullyInside = false;
    }
    return fullyInside ? 2 : 1;
}
function intersectsFrustumPrecise(frustum, aabbPoints) {
    for (const proj of frustum.projections) {
        const projectedAabb = projectPoints(aabbPoints, frustum.points[0], proj.axis);
        if (proj.projection[1] < projectedAabb[0] || proj.projection[0] > projectedAabb[1]) {
            return 0;
        }
    }
    return 1;
}
const NEAR_TL = 0;
const NEAR_TR = 1;
const NEAR_BR = 2;
const NEAR_BL = 3;
const FAR_TL = 4;
const FAR_TR = 5;
const FAR_BR = 6;
const FAR_BL = 7;
function pointsInsideOfPlane(points, plane) {
    let pointsInside = 0;
    const p = [
        0,
        0,
        0,
        0
    ];
    for (let i = 0; i < points.length; i++) {
        p[0] = points[i][0];
        p[1] = points[i][1];
        p[2] = points[i][2];
        p[3] = 1;
        if (vec4_1.dot(p, plane) >= 0) {
            pointsInside++;
        }
    }
    return pointsInside;
}
class Frustum {
    constructor(points_, planes_) {
        this.points = points_ || new Array(8).fill([
            0,
            0,
            0
        ]);
        this.planes = planes_ || new Array(6).fill([
            0,
            0,
            0,
            0
        ]);
        this.bounds = Aabb.fromPoints(this.points);
        this.projections = [];
        // Precompute a set of separating axis candidates for precise intersection tests.
        // These axes are computed as follows: (edges of aabb) x (edges of frustum)
        this.frustumEdges = [
            vec3_1.sub([], this.points[NEAR_BR], this.points[NEAR_BL]),
            vec3_1.sub([], this.points[NEAR_TL], this.points[NEAR_BL]),
            vec3_1.sub([], this.points[FAR_TL], this.points[NEAR_TL]),
            vec3_1.sub([], this.points[FAR_TR], this.points[NEAR_TR]),
            vec3_1.sub([], this.points[FAR_BR], this.points[NEAR_BR]),
            vec3_1.sub([], this.points[FAR_BL], this.points[NEAR_BL])
        ];
        for (const edge of this.frustumEdges) {
            // Cross product [1, 0, 0] x [a, b, c] == [0, -c, b]
            // Cross product [0, 1, 0] x [a, b, c] == [c, 0, -a]
            const axis0 = [
                0,
                -edge[2],
                edge[1]
            ];
            const axis1 = [
                edge[2],
                0,
                -edge[0]
            ];
            this.projections.push({
                axis: axis0,
                projection: projectPoints(this.points, this.points[0], axis0)
            });
            this.projections.push({
                axis: axis1,
                projection: projectPoints(this.points, this.points[0], axis1)
            });
        }
    }
    static fromInvProjectionMatrix(invProj, worldSize, zoom, zInMeters) {
        const clipSpaceCorners = [
            [
                -1,
                1,
                -1,
                1
            ],
            [
                1,
                1,
                -1,
                1
            ],
            [
                1,
                -1,
                -1,
                1
            ],
            [
                -1,
                -1,
                -1,
                1
            ],
            [
                -1,
                1,
                1,
                1
            ],
            [
                1,
                1,
                1,
                1
            ],
            [
                1,
                -1,
                1,
                1
            ],
            [
                -1,
                -1,
                1,
                1
            ]
        ];
        const scale = Math.pow(2, zoom);
        // Transform frustum corner points from clip space to tile space
        const frustumCoords = clipSpaceCorners.map(v => {
            const s = vec4_1.transformMat4([], v, invProj);
            const k = 1 / s[3] / worldSize * scale;
            // Z scale in meters.
            return vec4_1.mul(s, s, [
                k,
                k,
                zInMeters ? 1 / s[3] : k,
                k
            ]);
        });
        const frustumPlanePointIndices = [
            [
                NEAR_TL,
                NEAR_TR,
                NEAR_BR
            ],
            // near
            [
                FAR_BR,
                FAR_TR,
                FAR_TL
            ],
            // far
            [
                NEAR_TL,
                NEAR_BL,
                FAR_BL
            ],
            // left
            [
                NEAR_BR,
                NEAR_TR,
                FAR_TR
            ],
            // right
            [
                NEAR_BL,
                NEAR_BR,
                FAR_BR
            ],
            // bottom
            [
                NEAR_TL,
                FAR_TL,
                FAR_TR
            ]    // top
        ];
        const frustumPlanes = frustumPlanePointIndices.map(p => {
            const a = vec3_1.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);
            const b = vec3_1.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);
            const n = vec3_1.normalize([], vec3_1.cross([], a, b));
            const d = -vec3_1.dot(n, frustumCoords[p[1]]);
            return n.concat(d);
        });
        const frustumPoints = [];
        for (let i = 0; i < frustumCoords.length; i++) {
            frustumPoints.push([
                frustumCoords[i][0],
                frustumCoords[i][1],
                frustumCoords[i][2]
            ]);
        }
        return new Frustum(frustumPoints, frustumPlanes);
    }
    // Performs precise intersection test between the frustum and the provided convex hull.
    // The hull consits of vertices, faces (defined as planes) and a list of edges.
    // Intersection test is performed using separating axis theoreom.
    intersectsPrecise(vertices, faces, edges) {
        // Check if any of the provided faces defines a separating axis
        for (let i = 0; i < faces.length; i++) {
            if (!pointsInsideOfPlane(vertices, faces[i])) {
                return 0;
            }
        }
        // Check if any of the frustum planes defines a separating axis
        for (let i = 0; i < this.planes.length; i++) {
            if (!pointsInsideOfPlane(vertices, this.planes[i])) {
                return 0;
            }
        }
        for (const edge of edges) {
            for (const frustumEdge of this.frustumEdges) {
                const axis = vec3_1.cross([], edge, frustumEdge);
                const len = vec3_1.length(axis);
                if (len === 0) {
                    continue;
                }
                vec3_1.scale(axis, axis, 1 / len);
                const projA = projectPoints(this.points, this.points[0], axis);
                const projB = projectPoints(vertices, this.points[0], axis);
                if (projA[0] > projB[1] || projB[0] > projA[1]) {
                    return 0;
                }
            }
        }
        return 1;
    }
}
class Aabb {
    static fromPoints(points) {
        const min = [
            Infinity,
            Infinity,
            Infinity
        ];
        const max = [
            -Infinity,
            -Infinity,
            -Infinity
        ];
        for (const p of points) {
            vec3_1.min(min, min, p);
            vec3_1.max(max, max, p);
        }
        return new Aabb(min, max);
    }
    static fromTileIdAndHeight(id, minHeight, maxHeight) {
        const tiles = 1 << id.canonical.z;
        const x = id.canonical.x;
        const y = id.canonical.y;
        return new Aabb([
            x / tiles,
            y / tiles,
            minHeight
        ], [
            (x + 1) / tiles,
            (y + 1) / tiles,
            maxHeight
        ]);
    }
    static applyTransform(aabb, transform) {
        const corners = aabb.getCorners();
        for (let i = 0; i < corners.length; ++i) {
            vec3_1.transformMat4(corners[i], corners[i], transform);
        }
        return Aabb.fromPoints(corners);
    }
    static projectAabbCorners(aabb, transform) {
        const corners = aabb.getCorners();
        for (let i = 0; i < corners.length; ++i) {
            vec3_1.transformMat4(corners[i], corners[i], transform);
        }
        return corners;
    }
    constructor(min_, max_) {
        this.min = min_;
        this.max = max_;
        this.center = vec3_1.scale([], vec3_1.add([], this.min, this.max), 0.5);
    }
    quadrant(index) {
        const split = [
            index % 2 === 0,
            index < 2
        ];
        const qMin = vec3_1.clone(this.min);
        const qMax = vec3_1.clone(this.max);
        for (let axis = 0; axis < split.length; axis++) {
            qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];
            qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];
        }
        // Temporarily, elevation is constant, hence quadrant.max.z = this.max.z
        qMax[2] = this.max[2];
        return new Aabb(qMin, qMax);
    }
    distanceX(point) {
        const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);
        return pointOnAabb - point[0];
    }
    distanceY(point) {
        const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);
        return pointOnAabb - point[1];
    }
    distanceZ(point) {
        const pointOnAabb = Math.max(Math.min(this.max[2], point[2]), this.min[2]);
        return pointOnAabb - point[2];
    }
    getCorners() {
        const mn = this.min;
        const mx = this.max;
        return [
            [
                mn[0],
                mn[1],
                mn[2]
            ],
            [
                mx[0],
                mn[1],
                mn[2]
            ],
            [
                mx[0],
                mx[1],
                mn[2]
            ],
            [
                mn[0],
                mx[1],
                mn[2]
            ],
            [
                mn[0],
                mn[1],
                mx[2]
            ],
            [
                mx[0],
                mn[1],
                mx[2]
            ],
            [
                mx[0],
                mx[1],
                mx[2]
            ],
            [
                mn[0],
                mx[1],
                mx[2]
            ]
        ];
    }
    // Performs conservative intersection test using separating axis theorem.
    // Some accuracy is traded for better performance. False positive rate is < 1%.
    // Flat intersection test checks only x and y dimensions of the aabb.
    // Returns 0 if there's no intersection, 1 if shapes are intersecting and
    // 2 if the aabb if fully inside the frustum.
    intersects(frustum) {
        // Execute separating axis test between two convex objects to find intersections
        // Each frustum plane together with 3 major axes define the separating axes
        // This implementation is conservative as it's not checking all possible axes.
        // False positive rate is ~0.5% of all cases (see intersectsPrecise).
        if (!this.intersectsAabb(frustum.bounds)) {
            return 0;
        }
        return intersectsFrustum(frustum, this.getCorners());
    }
    intersectsFlat(frustum) {
        if (!this.intersectsAabb(frustum.bounds)) {
            return 0;
        }
        // Perform intersection test against flattened (z === 0) aabb
        const aabbPoints = [
            [
                this.min[0],
                this.min[1],
                0
            ],
            [
                this.max[0],
                this.min[1],
                0
            ],
            [
                this.max[0],
                this.max[1],
                0
            ],
            [
                this.min[0],
                this.max[1],
                0
            ]
        ];
        return intersectsFrustum(frustum, aabbPoints);
    }
    // Performs precise intersection test using separating axis theorem.
    // It is possible run only edge cases that were not covered in intersects().
    // Flat intersection test checks only x and y dimensions of the aabb.
    intersectsPrecise(frustum, edgeCasesOnly) {
        if (!edgeCasesOnly) {
            const intersects = this.intersects(frustum);
            if (!intersects) {
                return 0;
            }
        }
        return intersectsFrustumPrecise(frustum, this.getCorners());
    }
    intersectsPreciseFlat(frustum, edgeCasesOnly) {
        if (!edgeCasesOnly) {
            const intersects = this.intersectsFlat(frustum);
            if (!intersects) {
                return 0;
            }
        }
        // Perform intersection test against flattened (z === 0) aabb
        const aabbPoints = [
            [
                this.min[0],
                this.min[1],
                0
            ],
            [
                this.max[0],
                this.min[1],
                0
            ],
            [
                this.max[0],
                this.max[1],
                0
            ],
            [
                this.min[0],
                this.max[1],
                0
            ]
        ];
        return intersectsFrustumPrecise(frustum, aabbPoints);
    }
    intersectsAabb(aabb) {
        for (let axis = 0; axis < 3; ++axis) {
            if (this.min[axis] > aabb.max[axis] || aabb.min[axis] > this.max[axis]) {
                return false;
            }
        }
        return true;
    }
    intersectsAabbXY(aabb) {
        if (this.min[0] > aabb.max[0] || aabb.min[0] > this.max[0]) {
            return false;
        }
        if (this.min[1] > aabb.max[1] || aabb.min[1] > this.max[1]) {
            return false;
        }
        return true;
    }
    encapsulate(aabb) {
        for (let i = 0; i < 3; i++) {
            this.min[i] = Math.min(this.min[i], aabb.min[i]);
            this.max[i] = Math.max(this.max[i], aabb.max[i]);
        }
    }
    encapsulatePoint(point) {
        for (let i = 0; i < 3; i++) {
            this.min[i] = Math.min(this.min[i], point[i]);
            this.max[i] = Math.max(this.max[i], point[i]);
        }
    }
    closestPoint(point) {
        return [
            Math.max(Math.min(this.max[0], point[0]), this.min[0]),
            Math.max(Math.min(this.max[1], point[1]), this.min[1]),
            Math.max(Math.min(this.max[2], point[2]), this.min[2])
        ];
    }
}
register(Aabb, 'Aabb');

//      
const GLOBE_ZOOM_THRESHOLD_MIN = 5;
const GLOBE_ZOOM_THRESHOLD_MAX = 6;
// At low zoom levels the globe gets rendered so that the scale at this
// latitude matches it's scale in a mercator map. The choice of latitude is
// a bit arbitrary. Different choices will match mercator more closely in different
// views. 45 is a good enough choice because:
// - it's half way from the pole to the equator
// - matches most middle latitudes reasonably well
// - biases towards increasing size rather than decreasing
// - makes the globe slightly larger at very low zoom levels, where it already
//   covers less pixels than mercator (due to the curved surface)
//
//   Changing this value will change how large a globe is rendered and could affect
//   end users. This should only be done of the tradeoffs between change and improvement
//   are carefully considered.
const GLOBE_SCALE_MATCH_LATITUDE = 45;
const GLOBE_RADIUS = EXTENT / Math.PI / 2;
const GLOBE_NORMALIZATION_BIT_RANGE = 15;
const GLOBE_NORMALIZATION_MASK = (1 << GLOBE_NORMALIZATION_BIT_RANGE - 1) - 1;
const GLOBE_VERTEX_GRID_SIZE = 64;
const GLOBE_LATITUDINAL_GRID_LOD_TABLE = [
    GLOBE_VERTEX_GRID_SIZE,
    GLOBE_VERTEX_GRID_SIZE / 2,
    GLOBE_VERTEX_GRID_SIZE / 4
];
const TILE_SIZE = 512;
const GLOBE_MIN = -GLOBE_RADIUS;
const GLOBE_MAX = GLOBE_RADIUS;
const GLOBE_LOW_ZOOM_TILE_AABBS = [
    // z == 0
    new Aabb([
        GLOBE_MIN,
        GLOBE_MIN,
        GLOBE_MIN
    ], [
        GLOBE_MAX,
        GLOBE_MAX,
        GLOBE_MAX
    ]),
    // z == 1
    new Aabb([
        GLOBE_MIN,
        GLOBE_MIN,
        GLOBE_MIN
    ], [
        0,
        0,
        GLOBE_MAX
    ]),
    // x=0, y=0
    new Aabb([
        0,
        GLOBE_MIN,
        GLOBE_MIN
    ], [
        GLOBE_MAX,
        0,
        GLOBE_MAX
    ]),
    // x=1, y=0
    new Aabb([
        GLOBE_MIN,
        0,
        GLOBE_MIN
    ], [
        0,
        GLOBE_MAX,
        GLOBE_MAX
    ]),
    // x=0, y=1
    new Aabb([
        0,
        0,
        GLOBE_MIN
    ], [
        GLOBE_MAX,
        GLOBE_MAX,
        GLOBE_MAX
    ])    // x=1, y=1
];
function globeMetersToEcef(d) {
    return d * GLOBE_RADIUS / earthRadius;
}
function globePointCoordinate(tr, x, y, clampToHorizon = true) {
    const point0 = vec3_1.scale([], tr._camera.position, tr.worldSize);
    const point1 = [
        x,
        y,
        1,
        1
    ];
    vec4_1.transformMat4(point1, point1, tr.pixelMatrixInverse);
    vec4_1.scale(point1, point1, 1 / point1[3]);
    const p0p1 = vec3_1.sub([], point1, point0);
    const dir = vec3_1.normalize([], p0p1);
    // Find closest point on the sphere to the ray. This is a bit more involving operation
    // if the ray is not intersecting with the sphere, in which case we "clamp" the ray
    // to the surface of the sphere, i.e. find a tangent vector that originates from the camera position
    const m = tr.globeMatrix;
    const globeCenter = [
        m[12],
        m[13],
        m[14]
    ];
    const p0toCenter = vec3_1.sub([], globeCenter, point0);
    const p0toCenterDist = vec3_1.length(p0toCenter);
    const centerDir = vec3_1.normalize([], p0toCenter);
    const radius = tr.worldSize / (2 * Math.PI);
    const cosAngle = vec3_1.dot(centerDir, dir);
    const origoTangentAngle = Math.asin(radius / p0toCenterDist);
    const origoDirAngle = Math.acos(cosAngle);
    if (origoTangentAngle < origoDirAngle) {
        if (!clampToHorizon)
            return null;
        // Find the tangent vector by interpolating between camera-to-globe and camera-to-click vectors.
        // First we'll find a point P1 on the clicked ray that forms a right-angled triangle with the camera position
        // and the center of the globe. Angle of the tanget vector is then used as the interpolation factor
        const clampedP1 = [], origoToP1 = [];
        vec3_1.scale(clampedP1, dir, p0toCenterDist / cosAngle);
        vec3_1.normalize(origoToP1, vec3_1.sub(origoToP1, clampedP1, p0toCenter));
        vec3_1.normalize(dir, vec3_1.add(dir, p0toCenter, vec3_1.scale(dir, origoToP1, Math.tan(origoTangentAngle) * p0toCenterDist)));
    }
    const pointOnGlobe = [];
    const ray = new Ray(point0, dir);
    ray.closestPointOnSphere(globeCenter, radius, pointOnGlobe);
    // Transform coordinate axes to find lat & lng of the position
    const xa = vec3_1.normalize([], getColumn(m, 0));
    const ya = vec3_1.normalize([], getColumn(m, 1));
    const za = vec3_1.normalize([], getColumn(m, 2));
    const xp = vec3_1.dot(xa, pointOnGlobe);
    const yp = vec3_1.dot(ya, pointOnGlobe);
    const zp = vec3_1.dot(za, pointOnGlobe);
    const lat = radToDeg(Math.asin(-yp / radius));
    let lng = radToDeg(Math.atan2(xp, zp));
    // Check that the returned longitude angle is not wrapped
    lng = tr.center.lng + shortestAngle(tr.center.lng, lng);
    const mx = mercatorXfromLng(lng);
    const my = clamp(mercatorYfromLat(lat), 0, 1);
    return new MercatorCoordinate(mx, my);
}
class Arc {
    constructor(p0, p1, center) {
        this.a = vec3_1.sub([], p0, center);
        this.b = vec3_1.sub([], p1, center);
        this.center = center;
        const an = vec3_1.normalize([], this.a);
        const bn = vec3_1.normalize([], this.b);
        this.angle = Math.acos(vec3_1.dot(an, bn));
    }
}
function slerp(a, b, angle, t) {
    const sina = Math.sin(angle);
    return a * (Math.sin((1 - t) * angle) / sina) + b * (Math.sin(t * angle) / sina);
}
// Computes local extremum point of an arc on one of the dimensions (x, y or z),
// i.e. value of a point where d/dt*f(x,y,t) == 0
function localExtremum(arc, dim) {
    // d/dt*slerp(x,y,t) = 0
    // => t = (1/a)*atan(y/(x*sin(a))-1/tan(a)), x > 0
    // => t = (1/a)*(pi/2), x == 0
    if (arc.angle === 0) {
        return null;
    }
    let t;
    if (arc.a[dim] === 0) {
        t = 1 / arc.angle * 0.5 * Math.PI;
    } else {
        t = 1 / arc.angle * Math.atan(arc.b[dim] / arc.a[dim] / Math.sin(arc.angle) - 1 / Math.tan(arc.angle));
    }
    if (t < 0 || t > 1) {
        return null;
    }
    return slerp(arc.a[dim], arc.b[dim], arc.angle, clamp(t, 0, 1)) + arc.center[dim];
}
function globeTileBounds(id) {
    if (id.z <= 1) {
        return GLOBE_LOW_ZOOM_TILE_AABBS[id.z + id.y * 2 + id.x];
    }
    // After zoom 1 surface function is monotonic for all tile patches
    // => it is enough to project corner points
    const bounds = tileCornersToBounds(id);
    const corners = boundsToECEF(bounds);
    return Aabb.fromPoints(corners);
}
function interpolateVec3(from, to, phase) {
    vec3_1.scale(from, from, 1 - phase);
    return vec3_1.scaleAndAdd(from, from, to, phase);
}
// Similar to globeTileBounds() but accounts for globe to Mercator transition.
function transitionTileAABBinECEF(id, tr) {
    const phase = globeToMercatorTransition(tr.zoom);
    if (phase === 0) {
        return globeTileBounds(id);
    }
    const bounds = tileCornersToBounds(id);
    const corners = boundsToECEF(bounds);
    const w = mercatorXfromLng(bounds.getWest()) * tr.worldSize;
    const e = mercatorXfromLng(bounds.getEast()) * tr.worldSize;
    const n = mercatorYfromLat(bounds.getNorth()) * tr.worldSize;
    const s = mercatorYfromLat(bounds.getSouth()) * tr.worldSize;
    // Mercator bounds globeCorners in world/pixel space
    const nw = [
        w,
        n,
        0
    ];
    const ne = [
        e,
        n,
        0
    ];
    const sw = [
        w,
        s,
        0
    ];
    const se = [
        e,
        s,
        0
    ];
    // Transform Mercator globeCorners to ECEF
    const worldToECEFMatrix = mat4_1.invert([], tr.globeMatrix);
    vec3_1.transformMat4(nw, nw, worldToECEFMatrix);
    vec3_1.transformMat4(ne, ne, worldToECEFMatrix);
    vec3_1.transformMat4(sw, sw, worldToECEFMatrix);
    vec3_1.transformMat4(se, se, worldToECEFMatrix);
    // Interpolate Mercator corners and globe corners
    corners[0] = interpolateVec3(corners[0], sw, phase);
    corners[1] = interpolateVec3(corners[1], se, phase);
    corners[2] = interpolateVec3(corners[2], ne, phase);
    corners[3] = interpolateVec3(corners[3], nw, phase);
    return Aabb.fromPoints(corners);
}
function transformPoints(corners, globeMatrix, scale) {
    for (const corner of corners) {
        vec3_1.transformMat4(corner, corner, globeMatrix);
        vec3_1.scale(corner, corner, scale);
    }
}
// Returns AABB in world/camera space scaled by numTiles / tr.worldSize
// extendToPoles - extend tiles neighboring to north / south pole segments with the north/south pole point
function aabbForTileOnGlobe(tr, numTiles, tileId, extendToPoles) {
    const scale = numTiles / tr.worldSize;
    const m = tr.globeMatrix;
    if (tileId.z <= 1) {
        // Compute world/pixel space AABB that fully encapsulates
        // transformed corners of the ECEF AABB
        const corners = globeTileBounds(tileId).getCorners();
        transformPoints(corners, m, scale);
        return Aabb.fromPoints(corners);
    }
    // Find minimal aabb for a tile. Correct solution would be to compute bounding box that
    // fully encapsulates the curved patch that represents the tile on globes surface.
    // This can be simplified a bit as the globe transformation is constrained:
    //  1. Camera always faces the center point on the map
    //  2. Camera is always above (z-coordinate) all of the tiles
    //  3. Up direction of the coordinate space (pixel space) is always +z. This means that
    //     the "highest" point of the map is at the center.
    //  4. z-coordinate of any point in any tile descends as a function of the distance from the center
    // Simplified aabb is computed by first encapsulating 4 transformed corner points of the tile.
    // The resulting aabb is not complete yet as curved edges of the tile might span outside of the boundaries.
    // It is enough to extend the aabb to contain only the edge that's closest to the center point.
    const bounds = tileCornersToBounds(tileId, extendToPoles);
    const corners = boundsToECEF(bounds);
    // Transform the corners to world space
    transformPoints(corners, m, scale);
    const mx = Number.MAX_VALUE;
    const cornerMax = [
        -mx,
        -mx,
        -mx
    ];
    const cornerMin = [
        mx,
        mx,
        mx
    ];
    // Extend the aabb by including the center point. There are some corner cases where center point is inside the
    // tile but due to curvature aabb computed from corner points does not cover the curved area.
    if (bounds.contains(tr.center)) {
        for (const corner of corners) {
            vec3_1.min(cornerMin, cornerMin, corner);
            vec3_1.max(cornerMax, cornerMax, corner);
        }
        cornerMax[2] = 0;
        const point = tr.point;
        const center = [
            point.x * scale,
            point.y * scale,
            0
        ];
        vec3_1.min(cornerMin, cornerMin, center);
        vec3_1.max(cornerMax, cornerMax, center);
        return new Aabb(cornerMin, cornerMax);
    }
    // Compute arcs describing edges of the tile on the globe surface.
    // Vertical edges revolves around the globe origin whereas horizontal edges revolves around the y-axis.
    const arcCenter = [
        m[12] * scale,
        m[13] * scale,
        m[14] * scale
    ];
    const tileCenter = bounds.getCenter();
    const centerLat = clamp(tr.center.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
    const tileCenterLat = clamp(tileCenter.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
    const camX = mercatorXfromLng(tr.center.lng);
    const camY = mercatorYfromLat(centerLat);
    let dx = camX - mercatorXfromLng(tileCenter.lng);
    const dy = camY - mercatorYfromLat(tileCenterLat);
    // Shortest distance might be across the antimeridian
    if (dx > 0.5) {
        dx -= 1;
    } else if (dx < -0.5) {
        dx += 1;
    }
    // Here we determine the arc which is closest to the map center point.
    // Horizontal arcs origin = globe center
    // Vertical arcs origin = globe center + yAxis * shift.
    // Where `shift` is determined by latitude.
    let closestArcIdx = 0;
    if (Math.abs(dx) > Math.abs(dy)) {
        closestArcIdx = dx >= 0 ? 1 : 3;
    } else {
        closestArcIdx = dy >= 0 ? 0 : 2;
        const yAxis = [
            m[4] * scale,
            m[5] * scale,
            m[6] * scale
        ];
        const shift = -Math.sin(degToRad(dy >= 0 ? bounds.getSouth() : bounds.getNorth())) * GLOBE_RADIUS;
        vec3_1.scaleAndAdd(arcCenter, arcCenter, yAxis, shift);
    }
    const arcStart = corners[closestArcIdx];
    const arcEnd = corners[(closestArcIdx + 1) % 4];
    const closestArc = new Arc(arcStart, arcEnd, arcCenter);
    const arcExtremum = [
        localExtremum(closestArc, 0) || arcStart[0],
        localExtremum(closestArc, 1) || arcStart[1],
        localExtremum(closestArc, 2) || arcStart[2]
    ];
    const phase = globeToMercatorTransition(tr.zoom);
    if (phase > 0) {
        const mercatorCorners = mercatorTileCornersInCameraSpace(tileId, numTiles, tr._pixelsPerMercatorPixel, camX, camY);
        // Interpolate the four corners towards their world space location in mercator projection during transition.
        for (let i = 0; i < corners.length; i++) {
            interpolateVec3(corners[i], mercatorCorners[i], phase);
        }
        // Calculate the midpoint of the closest edge midpoint in Mercator
        const mercatorMidpoint = vec3_1.add([], mercatorCorners[closestArcIdx], mercatorCorners[(closestArcIdx + 1) % 4]);
        vec3_1.scale(mercatorMidpoint, mercatorMidpoint, 0.5);
        // Interpolate globe extremum toward Mercator midpoint
        interpolateVec3(arcExtremum, mercatorMidpoint, phase);
    }
    for (const corner of corners) {
        vec3_1.min(cornerMin, cornerMin, corner);
        vec3_1.max(cornerMax, cornerMax, corner);
    }
    // Reduce height of the aabb to match height of the closest arc. This reduces false positives
    // of tiles farther away from the center as they would otherwise intersect with far end
    // of the view frustum
    cornerMin[2] = Math.min(arcStart[2], arcEnd[2]);
    vec3_1.min(cornerMin, cornerMin, arcExtremum);
    vec3_1.max(cornerMax, cornerMax, arcExtremum);
    return new Aabb(cornerMin, cornerMax);
}
function tileCornersToBounds({x, y, z}, extendToPoles = false) {
    const s = 1 / (1 << z);
    const sw = new LngLat$1(lngFromMercatorX(x * s), y === (1 << z) - 1 && extendToPoles ? -90 : latFromMercatorY((y + 1) * s));
    const ne = new LngLat$1(lngFromMercatorX((x + 1) * s), y === 0 && extendToPoles ? 90 : latFromMercatorY(y * s));
    return new LngLatBounds(sw, ne);
}
function mercatorTileCornersInCameraSpace({x, y, z}, numTiles, mercatorScale, camX, camY) {
    const tileScale = 1 / (1 << z);
    // Values in Mercator coordinates (0 - 1)
    let w = x * tileScale;
    let e = w + tileScale;
    let n = y * tileScale;
    let s = n + tileScale;
    // // Ensure that the tile viewed is the nearest when across the antimeridian
    let wrap = 0;
    const tileCenterXFromCamera = (w + e) / 2 - camX;
    if (tileCenterXFromCamera > 0.5) {
        wrap = -1;
    } else if (tileCenterXFromCamera < -0.5) {
        wrap = 1;
    }
    camX *= numTiles;
    camY *= numTiles;
    //  Transform Mercator coordinates to points on the plane tangent to the globe at cameraCenter.
    w = ((w + wrap) * numTiles - camX) * mercatorScale + camX;
    e = ((e + wrap) * numTiles - camX) * mercatorScale + camX;
    n = (n * numTiles - camY) * mercatorScale + camY;
    s = (s * numTiles - camY) * mercatorScale + camY;
    return [
        [
            w,
            s,
            0
        ],
        [
            e,
            s,
            0
        ],
        [
            e,
            n,
            0
        ],
        [
            w,
            n,
            0
        ]
    ];
}
function boundsToECEF(bounds) {
    const ny = degToRad(bounds.getNorth());
    const sy = degToRad(bounds.getSouth());
    const cosN = Math.cos(ny);
    const cosS = Math.cos(sy);
    const sinN = Math.sin(ny);
    const sinS = Math.sin(sy);
    const w = bounds.getWest();
    const e = bounds.getEast();
    return [
        csLatLngToECEF(cosS, sinS, w),
        csLatLngToECEF(cosS, sinS, e),
        csLatLngToECEF(cosN, sinN, e),
        csLatLngToECEF(cosN, sinN, w)
    ];
}
function csLatLngToECEF(cosLat, sinLat, lng, radius = GLOBE_RADIUS) {
    lng = degToRad(lng);
    // Convert lat & lng to spherical representation. Use zoom=0 as a reference
    const sx = cosLat * Math.sin(lng) * radius;
    const sy = -sinLat * radius;
    const sz = cosLat * Math.cos(lng) * radius;
    return [
        sx,
        sy,
        sz
    ];
}
function ecefToLatLng([x, y, z]) {
    const radius = Math.hypot(x, y, z);
    const lng = Math.atan2(x, z);
    const lat = Math.PI * 0.5 - Math.acos(-y / radius);
    return new LngLat$1(radToDeg(lng), radToDeg(lat));
}
function latLngToECEF(lat, lng, radius) {
    return csLatLngToECEF(Math.cos(degToRad(lat)), Math.sin(degToRad(lat)), lng, radius);
}
function tileCoordToECEF(x, y, id, radius) {
    const tileCount = 1 << id.z;
    const mercatorX = (x / EXTENT + id.x) / tileCount;
    const mercatorY = (y / EXTENT + id.y) / tileCount;
    const lat = latFromMercatorY(mercatorY);
    const lng = lngFromMercatorX(mercatorX);
    const pos = latLngToECEF(lat, lng, radius);
    return pos;
}
function globeECEFOrigin(tileMatrix, id) {
    const origin = [
        0,
        0,
        0
    ];
    const bounds = globeTileBounds(id.canonical);
    const normalizationMatrix = globeNormalizeECEF(bounds);
    vec3_1.transformMat4(origin, origin, normalizationMatrix);
    vec3_1.transformMat4(origin, origin, tileMatrix);
    return origin;
}
function globeECEFNormalizationScale({min, max}) {
    return GLOBE_NORMALIZATION_MASK / Math.max(max[0] - min[0], max[1] - min[1], max[2] - min[2]);
}
// avoid redundant allocations by sharing the same typed array for normalization/denormalization matrices;
// we never use multiple instances of these at the same time, but this might change, so let's be careful here!
const tempMatrix = new Float64Array(16);
function globeNormalizeECEF(bounds) {
    const scale = globeECEFNormalizationScale(bounds);
    const m = mat4_1.fromScaling(tempMatrix, [
        scale,
        scale,
        scale
    ]);
    return mat4_1.translate(m, m, vec3_1.negate([], bounds.min));
}
function globeDenormalizeECEF(bounds) {
    const m = mat4_1.fromTranslation(tempMatrix, bounds.min);
    const scale = 1 / globeECEFNormalizationScale(bounds);
    return mat4_1.scale(m, m, [
        scale,
        scale,
        scale
    ]);
}
function globeECEFUnitsToPixelScale(worldSize) {
    const localRadius = EXTENT / (2 * Math.PI);
    const wsRadius = worldSize / (2 * Math.PI);
    return wsRadius / localRadius;
}
function globePixelsToTileUnits(zoom, id) {
    const ecefPerPixel = EXTENT / (TILE_SIZE * Math.pow(2, zoom));
    const normCoeff = globeECEFNormalizationScale(globeTileBounds(id));
    return ecefPerPixel * normCoeff;
}
function calculateGlobePosMatrix(x, y, worldSize, lng, lat) {
    // transform the globe from reference coordinate space to world space
    const scale = globeECEFUnitsToPixelScale(worldSize);
    const offset = [
        x,
        y,
        -worldSize / (2 * Math.PI)
    ];
    const m = mat4_1.identity(new Float64Array(16));
    mat4_1.translate(m, m, offset);
    mat4_1.scale(m, m, [
        scale,
        scale,
        scale
    ]);
    mat4_1.rotateX(m, m, degToRad(-lat));
    mat4_1.rotateY(m, m, degToRad(-lng));
    return m;
}
function calculateGlobeMatrix(tr) {
    const {x, y} = tr.point;
    const {lng, lat} = tr._center;
    return calculateGlobePosMatrix(x, y, tr.worldSize, lng, lat);
}
function calculateGlobeLabelMatrix(tr, id) {
    const {x, y} = tr.point;
    // Map aligned label space for globe view is the non-rotated globe itself in pixel coordinates.
    // Camera is moved closer towards the ground near poles as part of
    // compesanting the reprojection. This has to be compensated for the
    // map aligned label space. Whithout this logic map aligned symbols
    // would appear larger than intended.
    const m = calculateGlobePosMatrix(x, y, tr.worldSize / tr._pixelsPerMercatorPixel, 0, 0);
    return mat4_1.multiply(m, m, globeDenormalizeECEF(globeTileBounds(id)));
}
function calculateGlobeMercatorMatrix(tr) {
    const zScale = tr.pixelsPerMeter;
    const ws = zScale / mercatorZfromAltitude(1, tr.center.lat);
    const posMatrix = mat4_1.identity(new Float64Array(16));
    mat4_1.translate(posMatrix, posMatrix, [
        tr.point.x,
        tr.point.y,
        0
    ]);
    mat4_1.scale(posMatrix, posMatrix, [
        ws,
        ws,
        zScale
    ]);
    return Float32Array.from(posMatrix);
}
function globeToMercatorTransition(zoom) {
    return smoothstep(GLOBE_ZOOM_THRESHOLD_MIN, GLOBE_ZOOM_THRESHOLD_MAX, zoom);
}
function globePoleMatrixForTile(z, x, tr) {
    const poleMatrix = mat4_1.identity(new Float64Array(16));
    // Rotate the pole triangle fan to the correct location
    const numTiles = 1 << z;
    const xOffsetAngle = (x / numTiles - 0.5) * Math.PI * 2;
    mat4_1.rotateY(poleMatrix, tr.globeMatrix, xOffsetAngle);
    return Float32Array.from(poleMatrix);
}
function globeUseCustomAntiAliasing(painter, context, transform) {
    const transitionT = globeToMercatorTransition(transform.zoom);
    const useContextAA = painter.style.map._antialias;
    const disabled = context.extStandardDerivativesForceOff || painter.terrain && painter.terrain.exaggeration() > 0;
    return transitionT === 0 && !useContextAA && !disabled;
}
function getGridMatrix(id, bounds, latitudinalLod, worldSize) {
    const n = bounds.getNorth();
    const s = bounds.getSouth();
    const w = bounds.getWest();
    const e = bounds.getEast();
    // Construct transformation matrix for converting tile coordinates into LatLngs
    const tiles = 1 << id.z;
    const tileWidth = e - w;
    const tileHeight = n - s;
    const tileToLng = tileWidth / GLOBE_VERTEX_GRID_SIZE;
    const tileToLat = -tileHeight / GLOBE_LATITUDINAL_GRID_LOD_TABLE[latitudinalLod];
    const matrix = [
        0,
        tileToLng,
        0,
        tileToLat,
        0,
        0,
        n,
        w,
        0
    ];
    if (id.z > 0) {
        // Add slight padding to patch seams between tiles.
        // This is done by extruding vertices by a fixed amount. Pixel padding
        // is first converted to degrees and then to tile units before being
        // applied to the final transformation matrix.
        const pixelPadding = 0.5;
        const padding = pixelPadding * 360 / worldSize;
        const xScale = padding / tileWidth + 1;
        const yScale = padding / tileHeight + 1;
        const padMatrix = [
            xScale,
            0,
            0,
            0,
            yScale,
            0,
            -0.5 * padding / tileToLng,
            0.5 * padding / tileToLat,
            1
        ];
        mat3_1.multiply(matrix, matrix, padMatrix);
    }
    // Embed additional variables to the last row of the matrix
    matrix[2] = tiles;
    matrix[5] = id.x;
    matrix[8] = id.y;
    return matrix;
}
function getLatitudinalLod(lat) {
    const UPPER_LATITUDE = MAX_MERCATOR_LATITUDE - 5;
    lat = clamp(lat, -UPPER_LATITUDE, UPPER_LATITUDE) / UPPER_LATITUDE * 90;
    // const t = Math.pow(1.0 - Math.cos(degToRad(lat)), 2);
    const t = Math.pow(Math.abs(Math.sin(degToRad(lat))), 3);
    const lod = Math.round(t * (GLOBE_LATITUDINAL_GRID_LOD_TABLE.length - 1));
    return lod;
}
function globeCenterToScreenPoint(tr) {
    const pos = [
        0,
        0,
        0
    ];
    const matrix = mat4_1.identity(new Float64Array(16));
    mat4_1.multiply(matrix, tr.pixelMatrix, tr.globeMatrix);
    vec3_1.transformMat4(pos, pos, matrix);
    return new Point$2(pos[0], pos[1]);
}
function cameraPositionInECEF(tr) {
    // Here "center" is the center of the globe. We refer to transform._center
    // (the surface of the map on the center of the screen) as "pivot" to avoid confusion.
    const centerToPivot = latLngToECEF(tr._center.lat, tr._center.lng);
    // Set axis to East-West line tangent to sphere at pivot
    const south = vec3_1.fromValues(0, 1, 0);
    let axis = vec3_1.cross([], south, centerToPivot);
    // Rotate axis around pivot by bearing
    const rotation = mat4_1.fromRotation([], -tr.angle, centerToPivot);
    axis = vec3_1.transformMat4(axis, axis, rotation);
    // Rotate camera around axis by pitch
    mat4_1.fromRotation(rotation, -tr._pitch, axis);
    const pivotToCamera = vec3_1.normalize([], centerToPivot);
    vec3_1.scale(pivotToCamera, pivotToCamera, globeMetersToEcef(tr.cameraToCenterDistance / tr.pixelsPerMeter));
    vec3_1.transformMat4(pivotToCamera, pivotToCamera, rotation);
    return vec3_1.add([], centerToPivot, pivotToCamera);
}
// Return the angle of the normal vector at a point on the globe relative to the camera.
// i.e. how much to tilt map-aligned markers.
function globeTiltAtLngLat(tr, lngLat) {
    const centerToPoint = latLngToECEF(lngLat.lat, lngLat.lng);
    const centerToCamera = cameraPositionInECEF(tr);
    const pointToCamera = vec3_1.subtract([], centerToCamera, centerToPoint);
    return vec3_1.angle(pointToCamera, centerToPoint);
}
function isLngLatBehindGlobe(tr, lngLat) {
    // We consider 1% past the horizon not occluded, this allows popups to be dragged around the globe edge without fading.
    return globeTiltAtLngLat(tr, lngLat) > Math.PI / 2 * 1.01;
}
/**
 * Check if poles are visible inside the current viewport
 *
 * @param {Transform} transform The current map transform.
 * @returns {[boolean, boolean]} A tuple of booleans [northInViewport, southInViewport]
 */
function polesInViewport(tr) {
    // Create matrix from ECEF to screen coordinates
    const ecefToScreenMatrix = mat4_1.identity(new Float64Array(16));
    mat4_1.multiply(ecefToScreenMatrix, tr.pixelMatrix, tr.globeMatrix);
    const north = [
        0,
        GLOBE_MIN,
        0
    ];
    const south = [
        0,
        GLOBE_MAX,
        0
    ];
    // Translate the poles from ECEF to screen coordinates
    vec3_1.transformMat4(north, north, ecefToScreenMatrix);
    vec3_1.transformMat4(south, south, ecefToScreenMatrix);
    // Check if the poles are inside the viewport and not behind the globe surface
    const northInViewport = north[0] > 0 && north[0] <= tr.width && north[1] > 0 && north[1] <= tr.height && !isLngLatBehindGlobe(tr, new LngLat$1(tr.center.lat, 90));
    const southInViewport = south[0] > 0 && south[0] <= tr.width && south[1] > 0 && south[1] <= tr.height && !isLngLatBehindGlobe(tr, new LngLat$1(tr.center.lat, -90));
    return [
        northInViewport,
        southInViewport
    ];
}
const POLE_RAD = degToRad(85);
const POLE_COS = Math.cos(POLE_RAD);
const POLE_SIN = Math.sin(POLE_RAD);
// Generate terrain grid with embedded skirts
const EMBED_SKIRTS = true;
class GlobeSharedBuffers {
    constructor(context) {
        this._createGrid(context);
        this._createPoles(context);
    }
    destroy() {
        this._poleIndexBuffer.destroy();
        this._gridBuffer.destroy();
        this._gridIndexBuffer.destroy();
        this._poleNorthVertexBuffer.destroy();
        this._poleSouthVertexBuffer.destroy();
        for (const segments of this._poleSegments)
            segments.destroy();
        for (const segments of this._gridSegments) {
            segments.withSkirts.destroy();
            segments.withoutSkirts.destroy();
        }
    }
    // Generate terrain grid vertices and indices for all LOD's
    //
    // Grid vertices memory layout:
    //
    //          First line Skirt
    //          ┌───────────────┐
    //          │┌─────────────┐│
    // Left     ││┼┼┼┼┼┼┼┼┼┼┼┼┼││ Right
    // Border   ││┼┼┼┼┼┼┼┼┼┼┼┼┼││ Border
    // Skirt    │├─────────────┤│ Skirt
    //          ││  Main Grid  ││
    //          │├─────────────┤│
    //          ││┼┼┼┼┼┼┼┼┼┼┼┼┼││
    //          ││┼┼┼┼┼┼┼┼┼┼┼┼┼││
    //          │└─────────────┘│
    //          ├───────────────┤
    //          ├───────────────┤
    //          └───────────────┘
    //      Bottom Skirt = Number of LOD's
    //
    _fillGridMeshWithLods(longitudinalCellsCount, latitudinalLods) {
        const vertices = new StructArrayLayout2i4();
        const indices = new StructArrayLayout3ui6();
        const segments = [];
        const xVertices = longitudinalCellsCount + 1 + 2 * (1 );
        const yVerticesHighLodNoStrip = latitudinalLods[0] + 1;
        const yVerticesHighLodWithStrip = latitudinalLods[0] + 1 + (1 + latitudinalLods.length );
        // Index adjustment, used to make strip (x, y) vertex input attribute data
        // to match same data on ordinary grid edges
        const prepareVertex = (x, y, isSkirt) => {
            let adjustedX = ((() => {
                if (x === xVertices - 1) {
                    return x - 2;
                } else if (x === 0) {
                    return x;
                } else {
                    return x - 1;
                }
            })());
            // Skirt factor is introduces as an offset to the .x coordinate, similar to how it's done for mercator grids
            const skirtOffset = 24575;
            adjustedX += isSkirt ? skirtOffset : 0;
            return [
                adjustedX,
                y
            ];
        };
        // Add first horizontal strip if present
        {
            for (let x = 0; x < xVertices; ++x) {
                vertices.emplaceBack(...prepareVertex(x, 0, true));
            }
        }
        // Add main grid part with vertices strips embedded
        for (let y = 0; y < yVerticesHighLodNoStrip; ++y) {
            for (let x = 0; x < xVertices; ++x) {
                const isSideBorder = x === 0 || x === xVertices - 1;
                vertices.emplaceBack(...prepareVertex(x, y, isSideBorder && EMBED_SKIRTS));
            }
        }
        // Add bottom strips for each LOD
        {
            for (let lodIdx = 0; lodIdx < latitudinalLods.length; ++lodIdx) {
                const lastYRowForLod = latitudinalLods[lodIdx];
                for (let x = 0; x < xVertices; ++x) {
                    vertices.emplaceBack(...prepareVertex(x, lastYRowForLod, true));
                }
            }
        }
        // Fill triangles
        for (let lodIdx = 0; lodIdx < latitudinalLods.length; ++lodIdx) {
            const indexOffset = indices.length;
            const yVerticesLod = latitudinalLods[lodIdx] + 1 + 2 * (1 );
            const skirtsOnlyIndices = new StructArrayLayout3ui6();
            for (let y = 0; y < yVerticesLod - 1; y++) {
                const isLastLine = y === yVerticesLod - 2;
                const offsetToNextRow = isLastLine && EMBED_SKIRTS ? xVertices * (yVerticesHighLodWithStrip - latitudinalLods.length + lodIdx - y) : xVertices;
                for (let x = 0; x < xVertices - 1; x++) {
                    const idx = y * xVertices + x;
                    const isSkirt = (y === 0 || isLastLine || x === 0 || x === xVertices - 2);
                    if (isSkirt) {
                        skirtsOnlyIndices.emplaceBack(idx + 1, idx, idx + offsetToNextRow);
                        skirtsOnlyIndices.emplaceBack(idx + offsetToNextRow, idx + offsetToNextRow + 1, idx + 1);
                    } else {
                        indices.emplaceBack(idx + 1, idx, idx + offsetToNextRow);
                        indices.emplaceBack(idx + offsetToNextRow, idx + offsetToNextRow + 1, idx + 1);
                    }
                }
            }
            // Segments grid only
            const withoutSkirts = SegmentVector.simpleSegment(0, indexOffset, vertices.length, indices.length - indexOffset);
            for (let i = 0; i < skirtsOnlyIndices.uint16.length; i += 3) {
                indices.emplaceBack(skirtsOnlyIndices.uint16[i], skirtsOnlyIndices.uint16[i + 1], skirtsOnlyIndices.uint16[i + 2]);
            }
            // Segments grid + skirts only
            const withSkirts = SegmentVector.simpleSegment(0, indexOffset, vertices.length, indices.length - indexOffset);
            segments.push({
                withoutSkirts,
                withSkirts
            });
        }
        return {
            vertices,
            indices,
            segments
        };
    }
    _createGrid(context) {
        const gridWithLods = this._fillGridMeshWithLods(GLOBE_VERTEX_GRID_SIZE, GLOBE_LATITUDINAL_GRID_LOD_TABLE);
        this._gridSegments = gridWithLods.segments;
        this._gridBuffer = context.createVertexBuffer(gridWithLods.vertices, posAttributes.members);
        this._gridIndexBuffer = context.createIndexBuffer(gridWithLods.indices, true);
    }
    _createPoles(context) {
        const poleIndices = new StructArrayLayout3ui6();
        for (let i = 0; i <= GLOBE_VERTEX_GRID_SIZE; i++) {
            poleIndices.emplaceBack(0, i + 1, i + 2);
        }
        this._poleIndexBuffer = context.createIndexBuffer(poleIndices, true);
        const northVertices = new StructArrayLayout5f20();
        const southVertices = new StructArrayLayout5f20();
        const texturedNorthVertices = new StructArrayLayout5f20();
        const texturedSouthVertices = new StructArrayLayout5f20();
        const polePrimitives = GLOBE_VERTEX_GRID_SIZE;
        const poleVertices = GLOBE_VERTEX_GRID_SIZE + 2;
        this._poleSegments = [];
        for (let zoom = 0, offset = 0; zoom < GLOBE_ZOOM_THRESHOLD_MIN; zoom++) {
            const tiles = 1 << zoom;
            const endAngle = 360 / tiles;
            northVertices.emplaceBack(0, -GLOBE_RADIUS, 0, 0.5, 0);
            // place the tip
            southVertices.emplaceBack(0, -GLOBE_RADIUS, 0, 0.5, 1);
            texturedNorthVertices.emplaceBack(0, -GLOBE_RADIUS, 0, 0.5, 0.5);
            texturedSouthVertices.emplaceBack(0, -GLOBE_RADIUS, 0, 0.5, 0.5);
            for (let i = 0; i <= GLOBE_VERTEX_GRID_SIZE; i++) {
                let uvX = i / GLOBE_VERTEX_GRID_SIZE;
                let uvY = 0;
                const angle = number(0, endAngle, uvX);
                const [gx, gy, gz] = csLatLngToECEF(POLE_COS, POLE_SIN, angle, GLOBE_RADIUS);
                northVertices.emplaceBack(gx, gy, gz, uvX, uvY);
                southVertices.emplaceBack(gx, gy, gz, uvX, 1 - uvY);
                const rad = degToRad(angle);
                uvX = 0.5 + 0.5 * Math.sin(rad);
                uvY = 0.5 + 0.5 * Math.cos(rad);
                texturedNorthVertices.emplaceBack(gx, gy, gz, uvX, uvY);
                texturedSouthVertices.emplaceBack(gx, gy, gz, uvX, 1 - uvY);
            }
            this._poleSegments.push(SegmentVector.simpleSegment(offset, 0, poleVertices, polePrimitives));
            offset += poleVertices;
        }
        this._poleNorthVertexBuffer = context.createVertexBuffer(northVertices, members$5, false);
        this._poleSouthVertexBuffer = context.createVertexBuffer(southVertices, members$5, false);
        this._texturedPoleNorthVertexBuffer = context.createVertexBuffer(texturedNorthVertices, members$5, false);
        this._texturedPoleSouthVertexBuffer = context.createVertexBuffer(texturedSouthVertices, members$5, false);
    }
    getGridBuffers(latitudinalLod, withSkirts) {
        return [
            this._gridBuffer,
            this._gridIndexBuffer,
            withSkirts ? this._gridSegments[latitudinalLod].withSkirts : this._gridSegments[latitudinalLod].withoutSkirts
        ];
    }
    getPoleBuffers(z, textured) {
        return [
            textured ? this._texturedPoleNorthVertexBuffer : this._poleNorthVertexBuffer,
            textured ? this._texturedPoleSouthVertexBuffer : this._poleSouthVertexBuffer,
            this._poleIndexBuffer,
            this._poleSegments[z]
        ];
    }
}

//      
/*
* Approximate radius of the earth in meters.
* Uses the WGS-84 approximation. The radius at the equator is ~6378137 and at the poles is ~6356752. https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84
* 6371008.8 is one published "average radius" see https://en.wikipedia.org/wiki/Earth_radius#Mean_radius, or ftp://athena.fsv.cvut.cz/ZFG/grs80-Moritz.pdf p.4
*/
const earthRadius = 6371008.8;
/*
 * The average circumference of the earth in meters.
 */
const earthCircumference = 2 * Math.PI * earthRadius;
/**
 * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.
 * These coordinates use longitude, latitude coordinate order (as opposed to latitude, longitude)
 * to match the [GeoJSON specification](https://datatracker.ietf.org/doc/html/rfc7946#section-4),
 * which is equivalent to the OGC:CRS84 coordinate reference system.
 *
 * Note that any Mapbox GL method that accepts a `LngLat` object as an argument or option
 * can also accept an `Array` of two numbers and will perform an implicit conversion.
 * This flexible type is documented as {@link LngLatLike}.
 *
 * @param {number} lng Longitude, measured in degrees.
 * @param {number} lat Latitude, measured in degrees.
 * @example
 * const ll = new mapboxgl.LngLat(-123.9749, 40.7736);
 * console.log(ll.lng); // = -123.9749
 * @see [Example: Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)
 * @see [Example: Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)
 * @see [Example: Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
 * @see [Example: Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)
 */
class LngLat {
    constructor(lng, lat) {
        if (isNaN(lng) || isNaN(lat)) {
            throw new Error(`Invalid LngLat object: (${ lng }, ${ lat })`);
        }
        this.lng = +lng;
        this.lat = +lat;
        if (this.lat > 90 || this.lat < -90) {
            throw new Error('Invalid LngLat latitude value: must be between -90 and 90');
        }
    }
    /**
     * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180).
     *
     * @returns {LngLat} The wrapped `LngLat` object.
     * @example
     * const ll = new mapboxgl.LngLat(286.0251, 40.7736);
     * const wrapped = ll.wrap();
     * console.log(wrapped.lng); // = -73.9749
     */
    wrap() {
        return new LngLat(wrap$1(this.lng, -180, 180), this.lat);
    }
    /**
     * Returns the coordinates represented as an array of two numbers.
     *
     * @returns {Array<number>} The coordinates represeted as an array of longitude and latitude.
     * @example
     * const ll = new mapboxgl.LngLat(-73.9749, 40.7736);
     * ll.toArray(); // = [-73.9749, 40.7736]
     */
    toArray() {
        return [
            this.lng,
            this.lat
        ];
    }
    /**
     * Returns the coordinates represent as a string.
     *
     * @returns {string} The coordinates represented as a string of the format `'LngLat(lng, lat)'`.
     * @example
     * const ll = new mapboxgl.LngLat(-73.9749, 40.7736);
     * ll.toString(); // = "LngLat(-73.9749, 40.7736)"
     */
    toString() {
        return `LngLat(${ this.lng }, ${ this.lat })`;
    }
    /**
     * Returns the approximate distance between a pair of coordinates in meters.
     * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159).
     *
     * @param {LngLat} lngLat Coordinates to compute the distance to.
     * @returns {number} Distance in meters between the two coordinates.
     * @example
     * const newYork = new mapboxgl.LngLat(-74.0060, 40.7128);
     * const losAngeles = new mapboxgl.LngLat(-118.2437, 34.0522);
     * newYork.distanceTo(losAngeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km
     */
    distanceTo(lngLat) {
        const rad = Math.PI / 180;
        const lat1 = this.lat * rad;
        const lat2 = lngLat.lat * rad;
        const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad);
        const maxMeters = earthRadius * Math.acos(Math.min(a, 1));
        return maxMeters;
    }
    /**
     * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`.
     *
     * @param {number} [radius=0] Distance in meters from the coordinates to extend the bounds.
     * @returns {LngLatBounds} A new `LngLatBounds` object representing the coordinates extended by the `radius`.
     * @example
     * const ll = new mapboxgl.LngLat(-73.9749, 40.7736);
     * ll.toBounds(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]
     */
    toBounds(radius = 0) {
        const earthCircumferenceInMetersAtEquator = 40075017;
        const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator, lngAccuracy = latAccuracy / Math.cos(Math.PI / 180 * this.lat);
        return new LngLatBounds(new LngLat(this.lng - lngAccuracy, this.lat - latAccuracy), new LngLat(this.lng + lngAccuracy, this.lat + latAccuracy));
    }
    toEcef(altitude) {
        const altInEcef = globeMetersToEcef(altitude);
        const radius = GLOBE_RADIUS + altInEcef;
        return latLngToECEF(this.lat, this.lng, radius);
    }
    /**
     * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties
     * to a `LngLat` object.
     *
     * If a `LngLat` object is passed in, the function returns it unchanged.
     *
     * @param {LngLatLike} input An array of two numbers or object to convert, or a `LngLat` object to return.
     * @returns {LngLat} A new `LngLat` object, if a conversion occurred, or the original `LngLat` object.
     * @example
     * const arr = [-73.9749, 40.7736];
     * const ll = mapboxgl.LngLat.convert(arr);
     * console.log(ll);   // = LngLat {lng: -73.9749, lat: 40.7736}
     */
    static convert(input) {
        if (input instanceof LngLat) {
            return input;
        }
        if (Array.isArray(input) && (input.length === 2 || input.length === 3)) {
            return new LngLat(Number(input[0]), Number(input[1]));
        }
        if (!Array.isArray(input) && typeof input === 'object' && input !== null) {
            return new LngLat(// flow can't refine this to have one of lng or lat, so we have to cast to any
            Number('lng' in input ? input.lng : input.lon), Number(input.lat));
        }
        throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]');
    }
}
/**
 * A {@link LngLat} object, an array of two numbers representing longitude and latitude,
 * or an object with `lng` and `lat` or `lon` and `lat` properties.
 *
 * @typedef {LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number]} LngLatLike
 * @example
 * const v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
 * const v2 = [-122.420679, 37.772537];
 * const v3 = {lon: -122.420679, lat: 37.772537};
 */
var LngLat$1 = LngLat;

//      
const DEFAULT_MIN_ZOOM$1 = 0;
const DEFAULT_MAX_ZOOM$1 = 25.5;
/*
 * The circumference at a line of latitude in meters.
 */
function circumferenceAtLatitude(latitude) {
    return earthCircumference * Math.cos(latitude * Math.PI / 180);
}
function mercatorXfromLng(lng) {
    return (180 + lng) / 360;
}
function mercatorYfromLat(lat) {
    return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
}
function mercatorZfromAltitude(altitude, lat) {
    return altitude / circumferenceAtLatitude(lat);
}
function lngFromMercatorX(x) {
    return x * 360 - 180;
}
function latFromMercatorY(y) {
    const y2 = 180 - y * 360;
    return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;
}
function altitudeFromMercatorZ(z, y) {
    return z * circumferenceAtLatitude(latFromMercatorY(y));
}
const MAX_MERCATOR_LATITUDE = 85.051129;
function getLatitudeScale(lat) {
    return Math.cos(degToRad(clamp(lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE)));
}
function getMetersPerPixelAtLatitude(lat, zoom) {
    const constrainedZoom = clamp(zoom, DEFAULT_MIN_ZOOM$1, DEFAULT_MAX_ZOOM$1);
    const constrainedScale = Math.pow(2, constrainedZoom);
    return getLatitudeScale(lat) * earthCircumference / (constrainedScale * 512);
}
/**
 * Determine the Mercator scale factor for a given latitude, see
 * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor
 *
 * At the equator the scale factor will be 1, which increases at higher latitudes.
 *
 * @param {number} lat Latitude
 * @returns {number} scale factor
 * @private
 */
function mercatorScale(lat) {
    return 1 / Math.cos(lat * Math.PI / 180);
}
function tileToMeter(canonical, tileYCoordinate = 0) {
    const circumferenceAtEquator = 40075017;
    const mercatorY = (canonical.y + tileYCoordinate / EXTENT) / (1 << canonical.z);
    const exp = Math.exp(Math.PI * (1 - 2 * mercatorY));
    // simplify cos(2 * atan(e) - PI/2) from mercator_coordinate.js, remove trigonometrics.
    return circumferenceAtEquator * 2 * exp / (exp * exp + 1) / EXTENT / (1 << canonical.z);
}
/**
 * A `MercatorCoordinate` object represents a projected three dimensional position.
 *
 * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units:
 * - the size of 1 unit is the width of the projected world instead of the "mercator meter"
 * - the origin of the coordinate space is at the north-west corner instead of the middle.
 *
 * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and
 * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with
 * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think
 * of the coordinate space as the `0/0/0` tile with an extent of `1`.
 *
 * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube.
 *
 * @param {number} x The x component of the position.
 * @param {number} y The y component of the position.
 * @param {number} z The z component of the position.
 * @example
 * const nullIsland = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);
 *
 * @see [Example: Add a custom style layer](https://www.mapbox.com/mapbox-gl-js/example/custom-style-layer/)
 */
class MercatorCoordinate {
    constructor(x, y, z = 0) {
        this.x = +x;
        this.y = +y;
        this.z = +z;
    }
    /**
     * Project a `LngLat` to a `MercatorCoordinate`.
     *
     * @param {LngLatLike} lngLatLike The location to project.
     * @param {number} altitude The altitude in meters of the position.
     * @returns {MercatorCoordinate} The projected mercator coordinate.
     * @example
     * const coord = mapboxgl.MercatorCoordinate.fromLngLat({lng: 0, lat: 0}, 0);
     * console.log(coord); // MercatorCoordinate(0.5, 0.5, 0)
     */
    static fromLngLat(lngLatLike, altitude = 0) {
        const lngLat = LngLat$1.convert(lngLatLike);
        return new MercatorCoordinate(mercatorXfromLng(lngLat.lng), mercatorYfromLat(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat));
    }
    /**
     * Returns the `LngLat` for the coordinate.
     *
     * @returns {LngLat} The `LngLat` object.
     * @example
     * const coord = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);
     * const lngLat = coord.toLngLat(); // LngLat(0, 0)
     */
    toLngLat() {
        return new LngLat$1(lngFromMercatorX(this.x), latFromMercatorY(this.y));
    }
    /**
     * Returns the altitude in meters of the coordinate.
     *
     * @returns {number} The altitude in meters.
     * @example
     * const coord = new mapboxgl.MercatorCoordinate(0, 0, 0.02);
     * coord.toAltitude(); // 6914.281956295339
     */
    toAltitude() {
        return altitudeFromMercatorZ(this.z, this.y);
    }
    /**
     * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude.
     *
     * For coordinates in real world units using meters, this naturally provides the scale
     * to transform into `MercatorCoordinate`s.
     *
     * @returns {number} Distance of 1 meter in `MercatorCoordinate` units.
     * @example
     * // Calculate a new MercatorCoordinate that is 150 meters west of the other coord.
     * const coord = new mapboxgl.MercatorCoordinate(0.5, 0.25, 0);
     * const offsetInMeters = 150;
     * const offsetInMercatorCoordinateUnits = offsetInMeters * coord.meterInMercatorCoordinateUnits();
     * const westCoord = new mapboxgl.MercatorCoordinate(coord.x - offsetInMercatorCoordinateUnits, coord.y, coord.z);
     */
    meterInMercatorCoordinateUnits() {
        // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude
        return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y));
    }
}

//      
function pointToLineDist(px, py, ax, ay, bx, by) {
    const dx = ax - bx;
    const dy = ay - by;
    return Math.abs((ay - py) * dx - (ax - px) * dy) / Math.hypot(dx, dy);
}
function addResampled(resampled, mx0, my0, mx2, my2, start, end, reproject, tolerance) {
    const mx1 = (mx0 + mx2) / 2;
    const my1 = (my0 + my2) / 2;
    const mid = new Point$2(mx1, my1);
    reproject(mid);
    const err = pointToLineDist(mid.x, mid.y, start.x, start.y, end.x, end.y);
    // if reprojected midPoint is too far from geometric midpoint, recurse into two halves
    if (err >= tolerance) {
        // we're very unlikely to hit max call stack exceeded here,
        // but we might want to safeguard against it in the future
        addResampled(resampled, mx0, my0, mx1, my1, start, mid, reproject, tolerance);
        addResampled(resampled, mx1, my1, mx2, my2, mid, end, reproject, tolerance);
    } else {
        // otherwise, just add the point
        resampled.push(end);
    }
}
// reproject and resample a line, adding point where necessary for lines that become curves;
// note that this operation is mutable (modifying original points) for performance
function resample$1(line, reproject, tolerance) {
    let prev = line[0];
    let mx0 = prev.x;
    let my0 = prev.y;
    reproject(prev);
    const resampled = [prev];
    for (let i = 1; i < line.length; i++) {
        const point = line[i];
        const {x, y} = point;
        reproject(point);
        addResampled(resampled, mx0, my0, x, y, prev, point, reproject, tolerance);
        mx0 = x;
        my0 = y;
        prev = point;
    }
    return resampled;
}
function addResampledPred(resampled, a, b, pred) {
    const split = pred(a, b);
    // if the predicate condition is met, recurse into two halves
    if (split) {
        const mid = a.add(b)._mult(0.5);
        addResampledPred(resampled, a, mid, pred);
        addResampledPred(resampled, mid, b, pred);
    } else {
        resampled.push(b);
    }
}
function resamplePred(line, predicate) {
    let prev = line[0];
    const resampled = [prev];
    for (let i = 1; i < line.length; i++) {
        const point = line[i];
        addResampledPred(resampled, prev, point, predicate);
        prev = point;
    }
    return resampled;
}

//      
// These bounds define the minimum and maximum supported coordinate values.
// While visible coordinates are within [0, EXTENT], tiles may theoretically
// contain coordinates within [-Infinity, Infinity]. Our range is limited by the
// number of bits used to represent the coordinate.
const BITS = 15;
const MAX = Math.pow(2, BITS - 1) - 1;
const MIN = -MAX - 1;
function preparePoint(point, scale) {
    const x = Math.round(point.x * scale);
    const y = Math.round(point.y * scale);
    point.x = clamp(x, MIN, MAX);
    point.y = clamp(y, MIN, MAX);
    if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) {
        // warn when exceeding allowed extent except for the 1-px-off case
        // https://github.com/mapbox/mapbox-gl-js/issues/8992
        warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');
    }
    return point;
}
// a subset of VectorTileGeometry
/**
 * Loads a geometry from a VectorTileFeature and scales it to the common extent
 * used internally.
 * @param {VectorTileFeature} feature
 * @private
 */
function loadGeometry(feature, canonical, tileTransform) {
    const geometry = feature.loadGeometry();
    const extent = feature.extent;
    const extentScale = EXTENT / extent;
    if (canonical && tileTransform && tileTransform.projection.isReprojectedInTileSpace) {
        const z2 = 1 << canonical.z;
        const {scale, x, y, projection} = tileTransform;
        const reproject = p => {
            const lng = lngFromMercatorX((canonical.x + p.x / extent) / z2);
            const lat = latFromMercatorY((canonical.y + p.y / extent) / z2);
            const p2 = projection.project(lng, lat);
            p.x = (p2.x * scale - x) * extent;
            p.y = (p2.y * scale - y) * extent;
        };
        for (let i = 0; i < geometry.length; i++) {
            if (feature.type !== 1) {
                geometry[i] = resample$1(geometry[i], reproject, 1);    // resample lines and polygons
            } else {
                // points
                const line = [];
                for (const p of geometry[i]) {
                    // filter out point features outside tile boundaries now; it'd be harder to do later
                    // when the coords are reprojected and no longer axis-aligned; ideally this would happen
                    // or not depending on how the geometry is used, but we forego the complexity for now
                    if (p.x < 0 || p.x >= extent || p.y < 0 || p.y >= extent)
                        continue;
                    reproject(p);
                    line.push(p);
                }
                geometry[i] = line;
            }
        }
    }
    for (const line of geometry) {
        for (const p of line) {
            preparePoint(p, extentScale);
        }
    }
    return geometry;
}

//      
/**
 * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which
 * will be loaded based on necessity.
 * @param {VectorTileFeature} feature
 * @param {boolean} needGeometry
 * @private
 */
function toEvaluationFeature(feature, needGeometry) {
    return {
        type: feature.type,
        id: feature.id,
        properties: feature.properties,
        geometry: needGeometry ? loadGeometry(feature) : []
    };
}

//      
function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {
    layoutVertexArray.emplaceBack(x * 2 + (extrudeX + 1) / 2, y * 2 + (extrudeY + 1) / 2);
}
function addGlobeExtVertex$1(vertexArray, pos, normal) {
    const encode = 1 << 14;
    vertexArray.emplaceBack(pos.x, pos.y, pos.z, normal[0] * encode, normal[1] * encode, normal[2] * encode);
}
/**
 * Circles are represented by two triangles.
 *
 * Each corner has a pos that is the center of the circle and an extrusion
 * vector that is where it points.
 * @private
 */
class CircleBucket {
    constructor(options) {
        this.zoom = options.zoom;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.hasPattern = false;
        this.projection = options.projection;
        this.layoutVertexArray = new StructArrayLayout2i4();
        this.indexArray = new StructArrayLayout3ui6();
        this.segments = new SegmentVector();
        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
    }
    populate(features, options, canonical, tileTransform) {
        const styleLayer = this.layers[0];
        const bucketFeatures = [];
        let circleSortKey = null;
        // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access
        if (styleLayer.type === 'circle') {
            circleSortKey = styleLayer.layout.get('circle-sort-key');
        }
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            // $FlowFixMe[method-unbinding]
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const sortKey = circleSortKey ? circleSortKey.evaluate(evaluationFeature, {}, canonical) : undefined;
            const bucketFeature = {
                id,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),
                patterns: {},
                sortKey
            };
            bucketFeatures.push(bucketFeature);
        }
        if (circleSortKey) {
            bucketFeatures.sort((a, b) => {
                // a.sortKey is always a number when in use
                return a.sortKey - b.sortKey;
            });
        }
        let globeProjection = null;
        if (tileTransform.projection.name === 'globe') {
            // Extend vertex attributes if the globe projection is enabled
            this.globeExtVertexArray = new StructArrayLayout6i12();
            globeProjection = tileTransform.projection;
        }
        for (const bucketFeature of bucketFeatures) {
            const {geometry, index, sourceLayerIndex} = bucketFeature;
            const feature = features[index].feature;
            this.addFeature(bucketFeature, geometry, index, options.availableImages, canonical, globeProjection, options.brightness);
            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);
        }
    }
    update(states, vtLayer, availableImages, imagePositions, brightness) {
        const withStateUpdates = Object.keys(states).length !== 0;
        if (withStateUpdates && !this.stateDependentLayers.length)
            return;
        const layers = withStateUpdates ? this.stateDependentLayers : this.layers;
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
    }
    isEmpty() {
        return this.layoutVertexArray.length === 0;
    }
    uploadPending() {
        return !this.uploaded || this.programConfigurations.needsUpload;
    }
    upload(context) {
        if (!this.uploaded) {
            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, circleAttributes.members);
            this.indexBuffer = context.createIndexBuffer(this.indexArray);
            if (this.globeExtVertexArray) {
                this.globeExtVertexBuffer = context.createVertexBuffer(this.globeExtVertexArray, circleGlobeAttributesExt.members);
            }
        }
        this.programConfigurations.upload(context);
        this.uploaded = true;
    }
    destroy() {
        if (!this.layoutVertexBuffer)
            return;
        this.layoutVertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.programConfigurations.destroy();
        this.segments.destroy();
        if (this.globeExtVertexBuffer) {
            this.globeExtVertexBuffer.destroy();
        }
    }
    addFeature(feature, geometry, index, availableImages, canonical, projection, brightness) {
        for (const ring of geometry) {
            for (const point of ring) {
                const x = point.x;
                const y = point.y;
                // Do not include points that are outside the tile boundaries.
                if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT)
                    continue;
                // this geometry will be of the Point type, and we'll derive
                // two triangles from it.
                //
                // ┌─────────┐
                // │ 3     2 │
                // │         │
                // │ 0     1 │
                // └─────────┘
                if (projection) {
                    const projectedPoint = projection.projectTilePoint(x, y, canonical);
                    const normal = projection.upVector(canonical, x, y);
                    const array = this.globeExtVertexArray;
                    addGlobeExtVertex$1(array, projectedPoint, normal);
                    addGlobeExtVertex$1(array, projectedPoint, normal);
                    addGlobeExtVertex$1(array, projectedPoint, normal);
                    addGlobeExtVertex$1(array, projectedPoint, normal);
                }
                const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey);
                const index = segment.vertexLength;
                addCircleVertex(this.layoutVertexArray, x, y, -1, -1);
                addCircleVertex(this.layoutVertexArray, x, y, 1, -1);
                addCircleVertex(this.layoutVertexArray, x, y, 1, 1);
                addCircleVertex(this.layoutVertexArray, x, y, -1, 1);
                this.indexArray.emplaceBack(index, index + 1, index + 2);
                this.indexArray.emplaceBack(index, index + 2, index + 3);
                segment.vertexLength += 4;
                segment.primitiveLength += 2;
            }
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, availableImages, canonical, brightness);
    }
}
register(CircleBucket, 'CircleBucket', { omit: ['layers'] });

//      
function polygonIntersectsPolygon(polygonA, polygonB) {
    for (let i = 0; i < polygonA.length; i++) {
        if (polygonContainsPoint(polygonB, polygonA[i]))
            return true;
    }
    for (let i = 0; i < polygonB.length; i++) {
        if (polygonContainsPoint(polygonA, polygonB[i]))
            return true;
    }
    if (lineIntersectsLine(polygonA, polygonB))
        return true;
    return false;
}
function polygonIntersectsBufferedPoint(polygon, point, radius) {
    if (polygonContainsPoint(polygon, point))
        return true;
    if (pointIntersectsBufferedLine(point, polygon, radius))
        return true;
    return false;
}
function polygonIntersectsMultiPolygon(polygon, multiPolygon) {
    if (polygon.length === 1) {
        return multiPolygonContainsPoint(multiPolygon, polygon[0]);
    }
    for (let m = 0; m < multiPolygon.length; m++) {
        const ring = multiPolygon[m];
        for (let n = 0; n < ring.length; n++) {
            if (polygonContainsPoint(polygon, ring[n]))
                return true;
        }
    }
    for (let i = 0; i < polygon.length; i++) {
        if (multiPolygonContainsPoint(multiPolygon, polygon[i]))
            return true;
    }
    for (let k = 0; k < multiPolygon.length; k++) {
        if (lineIntersectsLine(polygon, multiPolygon[k]))
            return true;
    }
    return false;
}
function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) {
    for (let i = 0; i < multiLine.length; i++) {
        const line = multiLine[i];
        if (polygon.length >= 3) {
            for (let k = 0; k < line.length; k++) {
                if (polygonContainsPoint(polygon, line[k]))
                    return true;
            }
        }
        if (lineIntersectsBufferedLine(polygon, line, radius))
            return true;
    }
    return false;
}
function lineIntersectsBufferedLine(lineA, lineB, radius) {
    if (lineA.length > 1) {
        if (lineIntersectsLine(lineA, lineB))
            return true;
        // Check whether any point in either line is within radius of the other line
        for (let j = 0; j < lineB.length; j++) {
            if (pointIntersectsBufferedLine(lineB[j], lineA, radius))
                return true;
        }
    }
    for (let k = 0; k < lineA.length; k++) {
        if (pointIntersectsBufferedLine(lineA[k], lineB, radius))
            return true;
    }
    return false;
}
function lineIntersectsLine(lineA, lineB) {
    if (lineA.length === 0 || lineB.length === 0)
        return false;
    for (let i = 0; i < lineA.length - 1; i++) {
        const a0 = lineA[i];
        const a1 = lineA[i + 1];
        for (let j = 0; j < lineB.length - 1; j++) {
            const b0 = lineB[j];
            const b1 = lineB[j + 1];
            if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1))
                return true;
        }
    }
    return false;
}
function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) {
    return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1);
}
function pointIntersectsBufferedLine(p, line, radius) {
    const radiusSquared = radius * radius;
    if (line.length === 1)
        return p.distSqr(line[0]) < radiusSquared;
    for (let i = 1; i < line.length; i++) {
        // Find line segments that have a distance <= radius^2 to p
        // In that case, we treat the line as "containing point p".
        const v = line[i - 1], w = line[i];
        if (distToSegmentSquared(p, v, w) < radiusSquared)
            return true;
    }
    return false;
}
// Code from http://stackoverflow.com/a/1501725/331379.
function distToSegmentSquared(p, v, w) {
    const l2 = v.distSqr(w);
    if (l2 === 0)
        return p.distSqr(v);
    const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
    if (t < 0)
        return p.distSqr(v);
    if (t > 1)
        return p.distSqr(w);
    return p.distSqr(w.sub(v)._mult(t)._add(v));
}
// point in polygon ray casting algorithm
function multiPolygonContainsPoint(rings, p) {
    let c = false, ring, p1, p2;
    for (let k = 0; k < rings.length; k++) {
        ring = rings[k];
        for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
            p1 = ring[i];
            p2 = ring[j];
            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) {
                c = !c;
            }
        }
    }
    return c;
}
function polygonContainsPoint(ring, p) {
    let c = false;
    for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
        const p1 = ring[i];
        const p2 = ring[j];
        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) {
            c = !c;
        }
    }
    return c;
}
function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) {
    for (const p of ring) {
        if (boxX1 <= p.x && boxY1 <= p.y && boxX2 >= p.x && boxY2 >= p.y)
            return true;
    }
    const corners = [
        new Point$2(boxX1, boxY1),
        new Point$2(boxX1, boxY2),
        new Point$2(boxX2, boxY2),
        new Point$2(boxX2, boxY1)
    ];
    if (ring.length > 2) {
        for (const corner of corners) {
            if (polygonContainsPoint(ring, corner))
                return true;
        }
    }
    for (let i = 0; i < ring.length - 1; i++) {
        const p1 = ring[i];
        const p2 = ring[i + 1];
        if (edgeIntersectsBox(p1, p2, corners))
            return true;
    }
    return false;
}
function edgeIntersectsBox(e1, e2, corners) {
    const tl = corners[0];
    const br = corners[2];
    // the edge and box do not intersect in either the x or y dimensions
    if (e1.x < tl.x && e2.x < tl.x || e1.x > br.x && e2.x > br.x || e1.y < tl.y && e2.y < tl.y || e1.y > br.y && e2.y > br.y)
        return false;
    // check if all corners of the box are on the same side of the edge
    const dir = isCounterClockwise(e1, e2, corners[0]);
    return dir !== isCounterClockwise(e1, e2, corners[1]) || dir !== isCounterClockwise(e1, e2, corners[2]) || dir !== isCounterClockwise(e1, e2, corners[3]);
}
// Checks whether the triangle [p0, p1, p2] is on the left side of the edge [a, b].
function triangleLeftSideOfEdge(a, b, p0, p1, p2, padding) {
    let nx = b.y - a.y;
    let ny = a.x - b.x;
    padding = padding || 0;
    if (padding) {
        const nLenSq = nx * nx + ny * ny;
        if (nLenSq === 0) {
            return true;
        }
        const len = Math.sqrt(nLenSq);
        nx /= len;
        ny /= len;
    }
    if ((p0.x - a.x) * nx + (p0.y - a.y) * ny - padding < 0) {
        return false;
    } else if ((p1.x - a.x) * nx + (p1.y - a.y) * ny - padding < 0) {
        return false;
    } else if ((p2.x - a.x) * nx + (p2.y - a.y) * ny - padding < 0) {
        return false;
    }
    return true;
}
function triangleIntersectsTriangle(a0, b0, c0, a1, b1, c1, padding) {
    // Triangles are not intersecting if even one separating axis can be found
    if (triangleLeftSideOfEdge(a0, b0, a1, b1, c1, padding)) {
        return false;
    } else if (triangleLeftSideOfEdge(b0, c0, a1, b1, c1, padding)) {
        return false;
    } else if (triangleLeftSideOfEdge(c0, a0, a1, b1, c1, padding)) {
        return false;
    } else if (triangleLeftSideOfEdge(a1, b1, a0, b0, c0, padding)) {
        return false;
    } else if (triangleLeftSideOfEdge(b1, c1, a0, b0, c0, padding)) {
        return false;
    } else if (triangleLeftSideOfEdge(c1, a1, a0, b0, c0, padding)) {
        return false;
    }
    return true;
}

//      
function getMaximumPaintValue(property, layer, bucket) {
    const value = layer.paint.get(property).value;
    if (value.kind === 'constant') {
        return value.value;
    } else {
        return bucket.programConfigurations.get(layer.id).getMaxValue(property);
    }
}
function translateDistance(translate) {
    return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]);
}
function translate(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) {
    if (!translate[0] && !translate[1]) {
        return queryGeometry;
    }
    const pt = Point$2.convert(translate)._mult(pixelsToTileUnits);
    if (translateAnchor === 'viewport') {
        pt._rotate(-bearing);
    }
    const translated = [];
    for (let i = 0; i < queryGeometry.length; i++) {
        const point = queryGeometry[i];
        translated.push(point.sub(pt));
    }
    return translated;
}
function tilespaceTranslate(translate, translateAnchor, bearing, pixelsToTileUnits) {
    const pt = Point$2.convert(translate)._mult(pixelsToTileUnits);
    if (translateAnchor === 'viewport') {
        pt._rotate(-bearing);
    }
    return pt;
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$b = new Properties({
    'circle-sort-key': new DataDrivenProperty(spec['layout_circle']['circle-sort-key']),
    'visibility': new DataConstantProperty(spec['layout_circle']['visibility'])
});
const paint$b = new Properties({
    'circle-radius': new DataDrivenProperty(spec['paint_circle']['circle-radius']),
    'circle-color': new DataDrivenProperty(spec['paint_circle']['circle-color']),
    'circle-blur': new DataDrivenProperty(spec['paint_circle']['circle-blur']),
    'circle-opacity': new DataDrivenProperty(spec['paint_circle']['circle-opacity']),
    'circle-translate': new DataConstantProperty(spec['paint_circle']['circle-translate']),
    'circle-translate-anchor': new DataConstantProperty(spec['paint_circle']['circle-translate-anchor']),
    'circle-pitch-scale': new DataConstantProperty(spec['paint_circle']['circle-pitch-scale']),
    'circle-pitch-alignment': new DataConstantProperty(spec['paint_circle']['circle-pitch-alignment']),
    'circle-stroke-width': new DataDrivenProperty(spec['paint_circle']['circle-stroke-width']),
    'circle-stroke-color': new DataDrivenProperty(spec['paint_circle']['circle-stroke-color']),
    'circle-stroke-opacity': new DataDrivenProperty(spec['paint_circle']['circle-stroke-opacity']),
    'circle-emissive-strength': new DataConstantProperty(spec['paint_circle']['circle-emissive-strength'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$f = {
    paint: paint$b,
    layout: layout$b
};

//      
const circleUniforms = context => ({
    'u_camera_to_center_distance': new Uniform1f(context),
    'u_extrude_scale': new UniformMatrix2f(context),
    'u_device_pixel_ratio': new Uniform1f(context),
    'u_matrix': new UniformMatrix4f(context),
    'u_inv_rot_matrix': new UniformMatrix4f(context),
    'u_merc_center': new Uniform2f(context),
    'u_tile_id': new Uniform3f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_up_dir': new Uniform3f(context),
    'u_emissive_strength': new Uniform1f(context)
});
const identityMatrix$3 = mat4_1.create();
const circleUniformValues = (painter, coord, tile, invMatrix, mercatorCenter, layer) => {
    const transform = painter.transform;
    const isGlobe = transform.projection.name === 'globe';
    let extrudeScale;
    if (layer.paint.get('circle-pitch-alignment') === 'map') {
        if (isGlobe) {
            const s = globePixelsToTileUnits(transform.zoom, coord.canonical) * transform._pixelsPerMercatorPixel;
            extrudeScale = Float32Array.from([
                s,
                0,
                0,
                s
            ]);
        } else {
            extrudeScale = transform.calculatePixelsToTileUnitsMatrix(tile);
        }
    } else {
        extrudeScale = new Float32Array([
            transform.pixelsToGLUnits[0],
            0,
            0,
            transform.pixelsToGLUnits[1]
        ]);
    }
    const values = {
        'u_camera_to_center_distance': painter.transform.getCameraToCenterDistance(transform.projection),
        'u_matrix': painter.translatePosMatrix(coord.projMatrix, tile, layer.paint.get('circle-translate'), layer.paint.get('circle-translate-anchor')),
        'u_device_pixel_ratio': exported$1.devicePixelRatio,
        'u_extrude_scale': extrudeScale,
        'u_inv_rot_matrix': identityMatrix$3,
        'u_merc_center': [
            0,
            0
        ],
        'u_tile_id': [
            0,
            0,
            0
        ],
        'u_zoom_transition': 0,
        'u_up_dir': [
            0,
            0,
            0
        ],
        'u_emissive_strength': layer.paint.get('circle-emissive-strength')
    };
    if (isGlobe) {
        values['u_inv_rot_matrix'] = invMatrix;
        values['u_merc_center'] = mercatorCenter;
        values['u_tile_id'] = [
            coord.canonical.x,
            coord.canonical.y,
            1 << coord.canonical.z
        ];
        values['u_zoom_transition'] = globeToMercatorTransition(transform.zoom);
        const x = mercatorCenter[0] * EXTENT;
        const y = mercatorCenter[1] * EXTENT;
        values['u_up_dir'] = transform.projection.upVector(new CanonicalTileID(0, 0, 0), x, y);
    }
    return values;
};
const circleDefinesValues = layer => {
    const values = [];
    if (layer.paint.get('circle-pitch-alignment') === 'map')
        values.push('PITCH_WITH_MAP');
    if (layer.paint.get('circle-pitch-scale') === 'map')
        values.push('SCALE_WITH_MAP');
    return values;
};

//      
class CircleStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$f, options);
    }
    createBucket(parameters) {
        return new CircleBucket(parameters);
    }
    // $FlowFixMe[method-unbinding]
    queryRadius(bucket) {
        const circleBucket = bucket;
        return getMaximumPaintValue('circle-radius', this, circleBucket) + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + translateDistance(this.paint.get('circle-translate'));
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelPosMatrix, elevationHelper) {
        const translation = tilespaceTranslate(this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), transform.angle, queryGeometry.pixelToTileUnitsFactor);
        const size = this.paint.get('circle-radius').evaluate(feature, featureState) + this.paint.get('circle-stroke-width').evaluate(feature, featureState);
        return queryIntersectsCircle(queryGeometry, geometry, transform, pixelPosMatrix, elevationHelper, this.paint.get('circle-pitch-alignment') === 'map', this.paint.get('circle-pitch-scale') === 'map', translation, size);
    }
    getProgramIds() {
        return ['circle'];
    }
    getDefaultProgramParams(_, zoom) {
        const definesValues = circleDefinesValues(this);
        return {
            config: new ProgramConfiguration(this, zoom),
            defines: definesValues,
            overrideFog: false
        };
    }
}
function queryIntersectsCircle(queryGeometry, geometry, transform, pixelPosMatrix, elevationHelper, alignWithMap, scaleWithMap, translation, size) {
    if (alignWithMap && queryGeometry.queryGeometry.isAboveHorizon)
        return false;
    // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile
    // // Otherwise, compare geometry in the plane of the viewport
    // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance
    // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance
    if (alignWithMap)
        size *= queryGeometry.pixelToTileUnitsFactor;
    const tileId = queryGeometry.tileID.canonical;
    const elevationScale = transform.projection.upVectorScale(tileId, transform.center.lat, transform.worldSize).metersToTile;
    for (const ring of geometry) {
        for (const point of ring) {
            const translatedPoint = point.add(translation);
            const z = elevationHelper && transform.elevation ? transform.elevation.exaggeration() * elevationHelper.getElevationAt(translatedPoint.x, translatedPoint.y, true) : 0;
            // Reproject tile coordinate to the local coordinate space used by the projection
            const reproj = transform.projection.projectTilePoint(translatedPoint.x, translatedPoint.y, tileId);
            if (z > 0) {
                const dir = transform.projection.upVector(tileId, translatedPoint.x, translatedPoint.y);
                reproj.x += dir[0] * elevationScale * z;
                reproj.y += dir[1] * elevationScale * z;
                reproj.z += dir[2] * elevationScale * z;
            }
            const transformedPoint = alignWithMap ? translatedPoint : projectPoint(reproj.x, reproj.y, reproj.z, pixelPosMatrix);
            const transformedPolygon = alignWithMap ? queryGeometry.tilespaceRays.map(r => intersectAtHeight(r, z)) : queryGeometry.queryGeometry.screenGeometry;
            const projectedCenter = vec4_1.transformMat4([], [
                reproj.x,
                reproj.y,
                reproj.z,
                1
            ], pixelPosMatrix);
            if (!scaleWithMap && alignWithMap) {
                size *= projectedCenter[3] / transform.cameraToCenterDistance;
            } else if (scaleWithMap && !alignWithMap) {
                size *= transform.cameraToCenterDistance / projectedCenter[3];
            }
            if (alignWithMap) {
                // Apply extra scaling to cover different pixelPerMeter ratios at different latitudes
                const lat = latFromMercatorY((point.y / EXTENT + tileId.y) / (1 << tileId.z));
                const scale = transform.projection.pixelsPerMeter(lat, 1) / mercatorZfromAltitude(1, lat);
                size /= scale;
            }
            if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, size))
                return true;
        }
    }
    return false;
}
function projectPoint(x, y, z, pixelPosMatrix) {
    const point = vec4_1.transformMat4([], [
        x,
        y,
        z,
        1
    ], pixelPosMatrix);
    return new Point$2(point[0] / point[3], point[1] / point[3]);
}
const origin = vec3_1.fromValues(0, 0, 0);
const up = vec3_1.fromValues(0, 0, 1);
function intersectAtHeight(r, z) {
    const intersectionPt = vec3_1.create();
    origin[2] = z;
    r.intersectsPlane(origin, up, intersectionPt);
    return new Point$2(intersectionPt[0], intersectionPt[1]);
}

//      
class HeatmapBucket extends CircleBucket {
}
register(HeatmapBucket, 'HeatmapBucket', { omit: ['layers'] });

function createImage(image, {width, height}, channels, data) {
    if (!data) {
        data = new Uint8Array(width * height * channels);
    } else if (data instanceof Uint8ClampedArray) {
        data = new Uint8Array(data.buffer);
    } else if (data.length !== width * height * channels) {
        throw new RangeError('mismatched image size');
    }
    image.width = width;
    image.height = height;
    image.data = data;
    return image;
}
function resizeImage(image, newImage, channels) {
    const {width, height} = newImage;
    if (width === image.width && height === image.height) {
        return;
    }
    copyImage(image, newImage, {
        x: 0,
        y: 0
    }, {
        x: 0,
        y: 0
    }, {
        width: Math.min(image.width, width),
        height: Math.min(image.height, height)
    }, channels);
    image.width = width;
    image.height = height;
    image.data = newImage.data;
}
function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) {
    if (size.width === 0 || size.height === 0) {
        return dstImg;
    }
    if (size.width > srcImg.width || size.height > srcImg.height || srcPt.x > srcImg.width - size.width || srcPt.y > srcImg.height - size.height) {
        throw new RangeError('out of range source coordinates for image copy');
    }
    if (size.width > dstImg.width || size.height > dstImg.height || dstPt.x > dstImg.width - size.width || dstPt.y > dstImg.height - size.height) {
        throw new RangeError('out of range destination coordinates for image copy');
    }
    const srcData = srcImg.data;
    const dstData = dstImg.data;
    for (let y = 0; y < size.height; y++) {
        const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels;
        const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels;
        for (let i = 0; i < size.width * channels; i++) {
            dstData[dstOffset + i] = srcData[srcOffset + i];
        }
    }
    return dstImg;
}
class AlphaImage {
    constructor(size, data) {
        createImage(this, size, 1, data);
    }
    resize(size) {
        resizeImage(this, new AlphaImage(size), 1);
    }
    clone() {
        return new AlphaImage({
            width: this.width,
            height: this.height
        }, new Uint8Array(this.data));
    }
    static copy(srcImg, dstImg, srcPt, dstPt, size) {
        copyImage(srcImg, dstImg, srcPt, dstPt, size, 1);
    }
}
// Not premultiplied, because ImageData is not premultiplied.
// UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture.
class RGBAImage {
    // data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not
    // support Uint8ClampedArray in all browsers
    constructor(size, data) {
        createImage(this, size, 4, data);
    }
    resize(size) {
        resizeImage(this, new RGBAImage(size), 4);
    }
    replace(data, copy) {
        if (copy) {
            this.data.set(data);
        } else if (data instanceof Uint8ClampedArray) {
            this.data = new Uint8Array(data.buffer);
        } else {
            this.data = data;
        }
    }
    clone() {
        return new RGBAImage({
            width: this.width,
            height: this.height
        }, new Uint8Array(this.data));
    }
    static copy(srcImg, dstImg, srcPt, dstPt, size) {
        copyImage(srcImg, dstImg, srcPt, dstPt, size, 4);
    }
}
class Float32Image {
    constructor(size, data) {
        this.width = size.width;
        this.height = size.height;
        if (data instanceof Uint8Array) {
            this.data = new Float32Array(data.buffer);
        } else {
            this.data = data;
        }
    }
}
register(AlphaImage, 'AlphaImage');
register(RGBAImage, 'RGBAImage');

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$a = new Properties({ 'visibility': new DataConstantProperty(spec['layout_heatmap']['visibility']) });
const paint$a = new Properties({
    'heatmap-radius': new DataDrivenProperty(spec['paint_heatmap']['heatmap-radius']),
    'heatmap-weight': new DataDrivenProperty(spec['paint_heatmap']['heatmap-weight']),
    'heatmap-intensity': new DataConstantProperty(spec['paint_heatmap']['heatmap-intensity']),
    'heatmap-color': new ColorRampProperty(spec['paint_heatmap']['heatmap-color']),
    'heatmap-opacity': new DataConstantProperty(spec['paint_heatmap']['heatmap-opacity'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$e = {
    paint: paint$a,
    layout: layout$a
};

//      
/**
 * Given an expression that should evaluate to a color ramp,
 * return a RGBA image representing that ramp expression.
 *
 * @private
 */
function renderColorRamp(params) {
    const evaluationGlobals = {};
    const width = params.resolution || 256;
    const height = params.clips ? params.clips.length : 1;
    const image = params.image || new RGBAImage({
        width,
        height
    });
    const renderPixel = (stride, index, progress) => {
        evaluationGlobals[params.evaluationKey] = progress;
        const pxColor = params.expression.evaluate(evaluationGlobals);
        if (!pxColor)
            return;
        // the colors are being unpremultiplied because Color uses
        // premultiplied values, and the Texture class expects unpremultiplied ones
        image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a);
        image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a);
        image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a);
        image.data[stride + index + 3] = Math.floor(pxColor.a * 255);
    };
    if (!params.clips) {
        for (let i = 0, j = 0; i < width; i++, j += 4) {
            const progress = i / (width - 1);
            renderPixel(0, j, progress);
        }
    } else {
        for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) {
            for (let i = 0, j = 0; i < width; i++, j += 4) {
                // Remap progress between clips
                const progress = i / (width - 1);
                const {start, end} = params.clips[clip];
                const evaluationProgress = start * (1 - progress) + end * progress;
                renderPixel(stride, j, evaluationProgress);
            }
        }
    }
    return image;
}

//      
class HeatmapStyleLayer extends StyleLayer {
    createBucket(parameters) {
        return new HeatmapBucket(parameters);
    }
    constructor(layer, options) {
        super(layer, properties$e, options);
        // make sure color ramp texture is generated for default heatmap color too
        this._updateColorRamp();
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'heatmap-color') {
            this._updateColorRamp();
        }
    }
    _updateColorRamp() {
        const expression = this._transitionablePaint._values['heatmap-color'].value.expression;
        this.colorRamp = renderColorRamp({
            expression,
            evaluationKey: 'heatmapDensity',
            image: this.colorRamp
        });
        this.colorRampTexture = null;
    }
    resize() {
        if (this.heatmapFbo) {
            this.heatmapFbo.destroy();
            this.heatmapFbo = null;
        }
    }
    // $FlowFixMe[method-unbinding]
    queryRadius(bucket) {
        return getMaximumPaintValue('heatmap-radius', this, bucket);
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelPosMatrix, elevationHelper) {
        const size = this.paint.get('heatmap-radius').evaluate(feature, featureState);
        return queryIntersectsCircle(queryGeometry, geometry, transform, pixelPosMatrix, elevationHelper, true, true, new Point$2(0, 0), size);
    }
    hasOffscreenPass() {
        return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none';
    }
    getProgramIds() {
        return [
            'heatmap',
            'heatmapTexture'
        ];
    }
    getDefaultProgramParams(name, zoom) {
        if (name === 'heatmap') {
            return {
                config: new ProgramConfiguration(this, zoom),
                overrideFog: false
            };
        }
        return {};
    }
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$9 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_hillshade']['visibility']) });
const paint$9 = new Properties({
    'hillshade-illumination-direction': new DataConstantProperty(spec['paint_hillshade']['hillshade-illumination-direction']),
    'hillshade-illumination-anchor': new DataConstantProperty(spec['paint_hillshade']['hillshade-illumination-anchor']),
    'hillshade-exaggeration': new DataConstantProperty(spec['paint_hillshade']['hillshade-exaggeration']),
    'hillshade-shadow-color': new DataConstantProperty(spec['paint_hillshade']['hillshade-shadow-color']),
    'hillshade-highlight-color': new DataConstantProperty(spec['paint_hillshade']['hillshade-highlight-color']),
    'hillshade-accent-color': new DataConstantProperty(spec['paint_hillshade']['hillshade-accent-color']),
    'hillshade-emissive-strength': new DataConstantProperty(spec['paint_hillshade']['hillshade-emissive-strength'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$d = {
    paint: paint$9,
    layout: layout$9
};

//      
class HillshadeStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$d, options);
    }
    hasOffscreenPass() {
        return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none';
    }
    getProgramIds() {
        return [
            'hillshade',
            'hillshadePrepare'
        ];
    }
    // eslint-disable-next-line no-unused-vars
    getDefaultProgramParams(name, zoom) {
        return { overrideFog: false };
    }
}

//      
const layout$8 = createLayout([{
        name: 'a_pos',
        components: 2,
        type: 'Int16'
    }], 4);
const {members: members$4, size: size$4, alignment: alignment$4} = layout$8;

var earcut$2 = {exports: {}};

earcut$2.exports = earcut;
earcut$2.exports.default = earcut;
function earcut(data, holeIndices, dim) {
    dim = dim || 2;
    var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
    if (!outerNode || outerNode.next === outerNode.prev)
        return triangles;
    var minX, minY, maxX, maxY, x, y, invSize;
    if (hasHoles)
        outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
    // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
    if (data.length > 80 * dim) {
        minX = maxX = data[0];
        minY = maxY = data[1];
        for (var i = dim; i < outerLen; i += dim) {
            x = data[i];
            y = data[i + 1];
            if (x < minX)
                minX = x;
            if (y < minY)
                minY = y;
            if (x > maxX)
                maxX = x;
            if (y > maxY)
                maxY = y;
        }
        // minX, minY and invSize are later used to transform coords into integers for z-order calculation
        invSize = Math.max(maxX - minX, maxY - minY);
        invSize = invSize !== 0 ? 32767 / invSize : 0;
    }
    earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
    return triangles;
}
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
    var i, last;
    if (clockwise === signedArea$1(data, start, end, dim) > 0) {
        for (i = start; i < end; i += dim)
            last = insertNode(i, data[i], data[i + 1], last);
    } else {
        for (i = end - dim; i >= start; i -= dim)
            last = insertNode(i, data[i], data[i + 1], last);
    }
    if (last && equals(last, last.next)) {
        removeNode(last);
        last = last.next;
    }
    return last;
}
// eliminate colinear or duplicate points
function filterPoints(start, end) {
    if (!start)
        return start;
    if (!end)
        end = start;
    var p = start, again;
    do {
        again = false;
        if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
            removeNode(p);
            p = end = p.prev;
            if (p === p.next)
                break;
            again = true;
        } else {
            p = p.next;
        }
    } while (again || p !== end);
    return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
    if (!ear)
        return;
    // interlink polygon nodes in z-order
    if (!pass && invSize)
        indexCurve(ear, minX, minY, invSize);
    var stop = ear, prev, next;
    // iterate through ears, slicing them one by one
    while (ear.prev !== ear.next) {
        prev = ear.prev;
        next = ear.next;
        if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
            // cut off the triangle
            triangles.push(prev.i / dim | 0);
            triangles.push(ear.i / dim | 0);
            triangles.push(next.i / dim | 0);
            removeNode(ear);
            // skipping the next vertex leads to less sliver triangles
            ear = next.next;
            stop = next.next;
            continue;
        }
        ear = next;
        // if we looped through the whole remaining polygon and can't find any more ears
        if (ear === stop) {
            // try filtering points and slicing again
            if (!pass) {
                earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);    // if this didn't work, try curing all small self-intersections locally
            } else if (pass === 1) {
                ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
                earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);    // as a last resort, try splitting the remaining polygon into two
            } else if (pass === 2) {
                splitEarcut(ear, triangles, dim, minX, minY, invSize);
            }
            break;
        }
    }
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
    var a = ear.prev, b = ear, c = ear.next;
    if (area(a, b, c) >= 0)
        return false;
    // reflex, can't be an ear
    // now make sure we don't have other points inside the potential ear
    var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
    // triangle bbox; min & max are calculated like this for speed
    var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
    var p = c.next;
    while (p !== a) {
        if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0)
            return false;
        p = p.next;
    }
    return true;
}
function isEarHashed(ear, minX, minY, invSize) {
    var a = ear.prev, b = ear, c = ear.next;
    if (area(a, b, c) >= 0)
        return false;
    // reflex, can't be an ear
    var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
    // triangle bbox; min & max are calculated like this for speed
    var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
    // z-order range for the current triangle bbox;
    var minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize);
    var p = ear.prevZ, n = ear.nextZ;
    // look for points inside the triangle in both directions
    while (p && p.z >= minZ && n && n.z <= maxZ) {
        if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0)
            return false;
        p = p.prevZ;
        if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0)
            return false;
        n = n.nextZ;
    }
    // look for remaining points in decreasing z-order
    while (p && p.z >= minZ) {
        if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0)
            return false;
        p = p.prevZ;
    }
    // look for remaining points in increasing z-order
    while (n && n.z <= maxZ) {
        if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0)
            return false;
        n = n.nextZ;
    }
    return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
    var p = start;
    do {
        var a = p.prev, b = p.next.next;
        if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
            triangles.push(a.i / dim | 0);
            triangles.push(p.i / dim | 0);
            triangles.push(b.i / dim | 0);
            // remove two nodes involved
            removeNode(p);
            removeNode(p.next);
            p = start = b;
        }
        p = p.next;
    } while (p !== start);
    return filterPoints(p);
}
// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
    // look for a valid diagonal that divides the polygon into two
    var a = start;
    do {
        var b = a.next.next;
        while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
                // split the polygon in two by the diagonal
                var c = splitPolygon(a, b);
                // filter colinear points around the cuts
                a = filterPoints(a, a.next);
                c = filterPoints(c, c.next);
                // run earcut on each half
                earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
                earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
                return;
            }
            b = b.next;
        }
        a = a.next;
    } while (a !== start);
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
    var queue = [], i, len, start, end, list;
    for (i = 0, len = holeIndices.length; i < len; i++) {
        start = holeIndices[i] * dim;
        end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        list = linkedList(data, start, end, dim, false);
        if (list === list.next)
            list.steiner = true;
        queue.push(getLeftmost(list));
    }
    queue.sort(compareX);
    // process holes from left to right
    for (i = 0; i < queue.length; i++) {
        outerNode = eliminateHole(queue[i], outerNode);
    }
    return outerNode;
}
function compareX(a, b) {
    return a.x - b.x;
}
// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole, outerNode) {
    var bridge = findHoleBridge(hole, outerNode);
    if (!bridge) {
        return outerNode;
    }
    var bridgeReverse = splitPolygon(bridge, hole);
    // filter collinear points around the cuts
    filterPoints(bridgeReverse, bridgeReverse.next);
    return filterPoints(bridge, bridge.next);
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
    var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
    // find a segment intersected by a ray from the hole's leftmost point to the left;
    // segment's endpoint with lesser x will be potential connection point
    do {
        if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
            var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
            if (x <= hx && x > qx) {
                qx = x;
                m = p.x < p.next.x ? p : p.next;
                if (x === hx)
                    return m;    // hole touches outer segment; pick leftmost endpoint
            }
        }
        p = p.next;
    } while (p !== outerNode);
    if (!m)
        return null;
    // look for points inside the triangle of hole point, segment intersection and endpoint;
    // if there are no points found, we have a valid connection;
    // otherwise choose the point of the minimum angle with the ray as connection point
    var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
    p = m;
    do {
        if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
            tan = Math.abs(hy - p.y) / (hx - p.x);
            // tangential
            if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
                m = p;
                tanMin = tan;
            }
        }
        p = p.next;
    } while (p !== stop);
    return m;
}
// whether sector in vertex m contains sector in vertex p in the same coordinates
function sectorContainsSector(m, p) {
    return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
}
// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, invSize) {
    var p = start;
    do {
        if (p.z === 0)
            p.z = zOrder(p.x, p.y, minX, minY, invSize);
        p.prevZ = p.prev;
        p.nextZ = p.next;
        p = p.next;
    } while (p !== start);
    p.prevZ.nextZ = null;
    p.prevZ = null;
    sortLinked(p);
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
    var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
    do {
        p = list;
        list = null;
        tail = null;
        numMerges = 0;
        while (p) {
            numMerges++;
            q = p;
            pSize = 0;
            for (i = 0; i < inSize; i++) {
                pSize++;
                q = q.nextZ;
                if (!q)
                    break;
            }
            qSize = inSize;
            while (pSize > 0 || qSize > 0 && q) {
                if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                    e = p;
                    p = p.nextZ;
                    pSize--;
                } else {
                    e = q;
                    q = q.nextZ;
                    qSize--;
                }
                if (tail)
                    tail.nextZ = e;
                else
                    list = e;
                e.prevZ = tail;
                tail = e;
            }
            p = q;
        }
        tail.nextZ = null;
        inSize *= 2;
    } while (numMerges > 1);
    return list;
}
// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder(x, y, minX, minY, invSize) {
    // coords are transformed into non-negative 15-bit integer range
    x = (x - minX) * invSize | 0;
    y = (y - minY) * invSize | 0;
    x = (x | x << 8) & 16711935;
    x = (x | x << 4) & 252645135;
    x = (x | x << 2) & 858993459;
    x = (x | x << 1) & 1431655765;
    y = (y | y << 8) & 16711935;
    y = (y | y << 4) & 252645135;
    y = (y | y << 2) & 858993459;
    y = (y | y << 1) & 1431655765;
    return x | y << 1;
}
// find the leftmost node of a polygon ring
function getLeftmost(start) {
    var p = start, leftmost = start;
    do {
        if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y)
            leftmost = p;
        p = p.next;
    } while (p !== start);
    return leftmost;
}
// check if a point lies within a convex triangle
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
    return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py);
}
// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a, b) {
    return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
    equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0);    // special zero-length case
}
// signed area of a triangle
function area(p, q, r) {
    return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}
// check if two points are equal
function equals(p1, p2) {
    return p1.x === p2.x && p1.y === p2.y;
}
// check if two segments intersect
function intersects(p1, q1, p2, q2) {
    var o1 = sign(area(p1, q1, p2));
    var o2 = sign(area(p1, q1, q2));
    var o3 = sign(area(p2, q2, p1));
    var o4 = sign(area(p2, q2, q1));
    if (o1 !== o2 && o3 !== o4)
        return true;
    // general case
    if (o1 === 0 && onSegment(p1, p2, q1))
        return true;
    // p1, q1 and p2 are collinear and p2 lies on p1q1
    if (o2 === 0 && onSegment(p1, q2, q1))
        return true;
    // p1, q1 and q2 are collinear and q2 lies on p1q1
    if (o3 === 0 && onSegment(p2, p1, q2))
        return true;
    // p2, q2 and p1 are collinear and p1 lies on p2q2
    if (o4 === 0 && onSegment(p2, q1, q2))
        return true;
    // p2, q2 and q1 are collinear and q1 lies on p2q2
    return false;
}
// for collinear points p, q, r, check if point q lies on segment pr
function onSegment(p, q, r) {
    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);
}
function sign(num) {
    return num > 0 ? 1 : num < 0 ? -1 : 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
    var p = a;
    do {
        if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b))
            return true;
        p = p.next;
    } while (p !== a);
    return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
    return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
    var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
    do {
        if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)
            inside = !inside;
        p = p.next;
    } while (p !== a);
    return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
    var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
    a.next = b;
    b.prev = a;
    a2.next = an;
    an.prev = a2;
    b2.next = a2;
    a2.prev = b2;
    bp.next = b2;
    b2.prev = bp;
    return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
    var p = new Node(i, x, y);
    if (!last) {
        p.prev = p;
        p.next = p;
    } else {
        p.next = last.next;
        p.prev = last;
        last.next.prev = p;
        last.next = p;
    }
    return p;
}
function removeNode(p) {
    p.next.prev = p.prev;
    p.prev.next = p.next;
    if (p.prevZ)
        p.prevZ.nextZ = p.nextZ;
    if (p.nextZ)
        p.nextZ.prevZ = p.prevZ;
}
function Node(i, x, y) {
    // vertex index in coordinates array
    this.i = i;
    // vertex coordinates
    this.x = x;
    this.y = y;
    // previous and next vertex nodes in a polygon ring
    this.prev = null;
    this.next = null;
    // z-order curve value
    this.z = 0;
    // previous and next nodes in z-order
    this.prevZ = null;
    this.nextZ = null;
    // indicates whether this is a steiner point
    this.steiner = false;
}
// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
    var hasHoles = holeIndices && holeIndices.length;
    var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
    var polygonArea = Math.abs(signedArea$1(data, 0, outerLen, dim));
    if (hasHoles) {
        for (var i = 0, len = holeIndices.length; i < len; i++) {
            var start = holeIndices[i] * dim;
            var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
            polygonArea -= Math.abs(signedArea$1(data, start, end, dim));
        }
    }
    var trianglesArea = 0;
    for (i = 0; i < triangles.length; i += 3) {
        var a = triangles[i] * dim;
        var b = triangles[i + 1] * dim;
        var c = triangles[i + 2] * dim;
        trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
    }
    return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
};
function signedArea$1(data, start, end, dim) {
    var sum = 0;
    for (var i = start, j = end - dim; i < end; i += dim) {
        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
        j = i;
    }
    return sum;
}
// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
    var dim = data[0][0].length, result = {
            vertices: [],
            holes: [],
            dimensions: dim
        }, holeIndex = 0;
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].length; j++) {
            for (var d = 0; d < dim; d++)
                result.vertices.push(data[i][j][d]);
        }
        if (i > 0) {
            holeIndex += data[i - 1].length;
            result.holes.push(holeIndex);
        }
    }
    return result;
};

var earcutExports = earcut$2.exports;
var earcut$1 = /*@__PURE__*/getDefaultExportFromCjs(earcutExports);

//      
// classifies an array of rings into polygons with outer rings and holes
function classifyRings$1(rings, maxRings) {
    const len = rings.length;
    if (len <= 1)
        return [rings];
    const polygons = [];
    let polygon, ccw;
    for (let i = 0; i < len; i++) {
        const area = calculateSignedArea$1(rings[i]);
        if (area === 0)
            continue;
        rings[i].area = Math.abs(area);
        if (ccw === undefined)
            ccw = area < 0;
        if (ccw === area < 0) {
            if (polygon)
                polygons.push(polygon);
            polygon = [rings[i]];
        } else {
            polygon.push(rings[i]);
        }
    }
    if (polygon)
        polygons.push(polygon);
    // Earcut performance degrades with the # of rings in a polygon. For this
    // reason, we limit strip out all but the `maxRings` largest rings.
    if (maxRings > 1) {
        for (let j = 0; j < polygons.length; j++) {
            if (polygons[j].length <= maxRings)
                continue;
            quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas);
            polygons[j] = polygons[j].slice(0, maxRings);
        }
    }
    return polygons;
}
function compareAreas(a, b) {
    return b.area - a.area;
}

//      
function hasPattern(type, layers, options) {
    const patterns = options.patternDependencies;
    let hasPattern = false;
    for (const layer of layers) {
        const patternProperty = layer.paint.get(`${ type }-pattern`);
        if (!patternProperty.isConstant()) {
            hasPattern = true;
        }
        const constantPattern = patternProperty.constantOr(null);
        if (constantPattern) {
            hasPattern = true;
            patterns[constantPattern] = true;
        }
    }
    return hasPattern;
}
function addPatternDependencies(type, layers, patternFeature, zoom, options) {
    const patterns = options.patternDependencies;
    for (const layer of layers) {
        const patternProperty = layer.paint.get(`${ type }-pattern`);
        const patternPropertyValue = patternProperty.value;
        if (patternPropertyValue.kind !== 'constant') {
            let pattern = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages);
            pattern = pattern && pattern.name ? pattern.name : pattern;
            // add to patternDependencies
            patterns[pattern] = true;
            // save for layout
            patternFeature.patterns[layer.id] = pattern;
        }
    }
    return patternFeature;
}

//      
const EARCUT_MAX_RINGS$1 = 500;
class FillBucket {
    constructor(options) {
        this.zoom = options.zoom;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.hasPattern = false;
        this.patternFeatures = [];
        this.layoutVertexArray = new StructArrayLayout2i4();
        this.indexArray = new StructArrayLayout3ui6();
        this.indexArray2 = new StructArrayLayout2ui4();
        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
        this.segments = new SegmentVector();
        this.segments2 = new SegmentVector();
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.projection = options.projection;
    }
    populate(features, options, canonical, tileTransform) {
        this.hasPattern = hasPattern('fill', this.layers, options);
        const fillSortKey = this.layers[0].layout.get('fill-sort-key');
        const bucketFeatures = [];
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            // $FlowFixMe[method-unbinding]
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const sortKey = fillSortKey ? fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : undefined;
            const bucketFeature = {
                id,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),
                patterns: {},
                sortKey
            };
            bucketFeatures.push(bucketFeature);
        }
        if (fillSortKey) {
            bucketFeatures.sort((a, b) => {
                // a.sortKey is always a number when in use
                return a.sortKey - b.sortKey;
            });
        }
        for (const bucketFeature of bucketFeatures) {
            const {geometry, index, sourceLayerIndex} = bucketFeature;
            if (this.hasPattern) {
                const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options);
                // pattern features are added only once the pattern is loaded into the image atlas
                // so are stored during populate until later updated with positions by tile worker in addFeatures
                this.patternFeatures.push(patternFeature);
            } else {
                this.addFeature(bucketFeature, geometry, index, canonical, {}, options.availableImages, options.brightness);
            }
            const feature = features[index].feature;
            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);
        }
    }
    update(states, vtLayer, availableImages, imagePositions, brightness) {
        const withStateUpdates = Object.keys(states).length !== 0;
        if (withStateUpdates && !this.stateDependentLayers.length)
            return;
        const layers = withStateUpdates ? this.stateDependentLayers : this.layers;
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
    }
    addFeatures(options, canonical, imagePositions, availableImages, _, brightness) {
        for (const feature of this.patternFeatures) {
            this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions, availableImages, brightness);
        }
    }
    isEmpty() {
        return this.layoutVertexArray.length === 0;
    }
    uploadPending() {
        return !this.uploaded || this.programConfigurations.needsUpload;
    }
    upload(context) {
        if (!this.uploaded) {
            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$4);
            this.indexBuffer = context.createIndexBuffer(this.indexArray);
            this.indexBuffer2 = context.createIndexBuffer(this.indexArray2);
        }
        this.programConfigurations.upload(context);
        this.uploaded = true;
    }
    destroy() {
        if (!this.layoutVertexBuffer)
            return;
        this.layoutVertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.indexBuffer2.destroy();
        this.programConfigurations.destroy();
        this.segments.destroy();
        this.segments2.destroy();
    }
    addFeature(feature, geometry, index, canonical, imagePositions, availableImages = [], brightness) {
        for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) {
            let numVertices = 0;
            for (const ring of polygon) {
                numVertices += ring.length;
            }
            const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);
            const triangleIndex = triangleSegment.vertexLength;
            const flattened = [];
            const holeIndices = [];
            for (const ring of polygon) {
                if (ring.length === 0) {
                    continue;
                }
                if (ring !== polygon[0]) {
                    holeIndices.push(flattened.length / 2);
                }
                const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2);
                const lineIndex = lineSegment.vertexLength;
                this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y);
                this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex);
                flattened.push(ring[0].x);
                flattened.push(ring[0].y);
                for (let i = 1; i < ring.length; i++) {
                    this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y);
                    this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i);
                    flattened.push(ring[i].x);
                    flattened.push(ring[i].y);
                }
                lineSegment.vertexLength += ring.length;
                lineSegment.primitiveLength += ring.length;
            }
            const indices = earcut$1(flattened, holeIndices);
            for (let i = 0; i < indices.length; i += 3) {
                this.indexArray.emplaceBack(triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2]);
            }
            triangleSegment.vertexLength += numVertices;
            triangleSegment.primitiveLength += indices.length / 3;
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical, brightness);
    }
}
register(FillBucket, 'FillBucket', {
    omit: [
        'layers',
        'patternFeatures'
    ]
});

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$7 = new Properties({
    'fill-sort-key': new DataDrivenProperty(spec['layout_fill']['fill-sort-key']),
    'visibility': new DataConstantProperty(spec['layout_fill']['visibility'])
});
const paint$8 = new Properties({
    'fill-antialias': new DataConstantProperty(spec['paint_fill']['fill-antialias']),
    'fill-opacity': new DataDrivenProperty(spec['paint_fill']['fill-opacity']),
    'fill-color': new DataDrivenProperty(spec['paint_fill']['fill-color']),
    'fill-outline-color': new DataDrivenProperty(spec['paint_fill']['fill-outline-color']),
    'fill-translate': new DataConstantProperty(spec['paint_fill']['fill-translate']),
    'fill-translate-anchor': new DataConstantProperty(spec['paint_fill']['fill-translate-anchor']),
    'fill-pattern': new DataDrivenProperty(spec['paint_fill']['fill-pattern']),
    'fill-emissive-strength': new DataConstantProperty(spec['paint_fill']['fill-emissive-strength'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$c = {
    paint: paint$8,
    layout: layout$7
};

//      
class FillStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$c, options);
    }
    getProgramIds() {
        const pattern = this.paint.get('fill-pattern');
        const image = pattern && pattern.constantOr(1);
        const ids = [image ? 'fillPattern' : 'fill'];
        if (this.paint.get('fill-antialias')) {
            ids.push(image && !this.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline');
        }
        return ids;
    }
    getDefaultProgramParams(name, zoom) {
        return {
            config: new ProgramConfiguration(this, zoom),
            overrideFog: false
        };
    }
    recalculate(parameters, availableImages) {
        super.recalculate(parameters, availableImages);
        const outlineColor = this.paint._values['fill-outline-color'];
        if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) {
            this.paint._values['fill-outline-color'] = this.paint._values['fill-color'];
        }
    }
    createBucket(parameters) {
        return new FillBucket(parameters);
    }
    // $FlowFixMe[method-unbinding]
    queryRadius() {
        return translateDistance(this.paint.get('fill-translate'));
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform) {
        if (queryGeometry.queryGeometry.isAboveHorizon)
            return false;
        const translatedPolygon = translate(queryGeometry.tilespaceGeometry, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), transform.angle, queryGeometry.pixelToTileUnitsFactor);
        return polygonIntersectsMultiPolygon(translatedPolygon, geometry);
    }
    isTileClipped() {
        return true;
    }
}

//      
const fillExtrusionAttributes = createLayout([{
        name: 'a_pos_normal_ed',
        components: 4,
        type: 'Int16'
    }]);
const fillExtrusionGroundAttributes = createLayout([
    {
        name: 'a_pos_end',
        components: 4,
        type: 'Int16'
    },
    {
        name: 'a_angular_offset_factor',
        components: 1,
        type: 'Int16'
    }
]);
const centroidAttributes = createLayout([{
        name: 'a_centroid_pos',
        components: 2,
        type: 'Uint16'
    }]);
const hiddenByLandmarkAttributes = createLayout([{
        name: 'a_hidden_by_landmark',
        components: 1,
        type: 'Uint8'
    }]);
const fillExtrusionAttributesExt = createLayout([
    {
        name: 'a_pos_3',
        components: 3,
        type: 'Int16'
    },
    {
        name: 'a_pos_normal_3',
        components: 3,
        type: 'Int16'
    }
]);
const {members: members$3, size: size$3, alignment: alignment$3} = fillExtrusionAttributes;

var vectorTile = {};

var Point = pointGeometry;
var vectortilefeature = VectorTileFeature$2;
function VectorTileFeature$2(pbf, end, extent, keys, values) {
    // Public
    this.properties = {};
    this.extent = extent;
    this.type = 0;
    // Private
    this._pbf = pbf;
    this._geometry = -1;
    this._keys = keys;
    this._values = values;
    pbf.readFields(readFeature, this, end);
}
function readFeature(tag, feature, pbf) {
    if (tag == 1)
        feature.id = pbf.readVarint();
    else if (tag == 2)
        readTag(pbf, feature);
    else if (tag == 3)
        feature.type = pbf.readVarint();
    else if (tag == 4)
        feature._geometry = pbf.pos;
}
function readTag(pbf, feature) {
    var end = pbf.readVarint() + pbf.pos;
    while (pbf.pos < end) {
        var key = feature._keys[pbf.readVarint()], value = feature._values[pbf.readVarint()];
        feature.properties[key] = value;
    }
}
VectorTileFeature$2.types = [
    'Unknown',
    'Point',
    'LineString',
    'Polygon'
];
VectorTileFeature$2.prototype.loadGeometry = function () {
    var pbf = this._pbf;
    pbf.pos = this._geometry;
    var end = pbf.readVarint() + pbf.pos, cmd = 1, length = 0, x = 0, y = 0, lines = [], line;
    while (pbf.pos < end) {
        if (length <= 0) {
            var cmdLen = pbf.readVarint();
            cmd = cmdLen & 7;
            length = cmdLen >> 3;
        }
        length--;
        if (cmd === 1 || cmd === 2) {
            x += pbf.readSVarint();
            y += pbf.readSVarint();
            if (cmd === 1) {
                // moveTo
                if (line)
                    lines.push(line);
                line = [];
            }
            line.push(new Point(x, y));
        } else if (cmd === 7) {
            // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90
            if (line) {
                line.push(line[0].clone());    // closePolygon
            }
        } else {
            throw new Error('unknown command ' + cmd);
        }
    }
    if (line)
        lines.push(line);
    return lines;
};
VectorTileFeature$2.prototype.bbox = function () {
    var pbf = this._pbf;
    pbf.pos = this._geometry;
    var end = pbf.readVarint() + pbf.pos, cmd = 1, length = 0, x = 0, y = 0, x1 = Infinity, x2 = -Infinity, y1 = Infinity, y2 = -Infinity;
    while (pbf.pos < end) {
        if (length <= 0) {
            var cmdLen = pbf.readVarint();
            cmd = cmdLen & 7;
            length = cmdLen >> 3;
        }
        length--;
        if (cmd === 1 || cmd === 2) {
            x += pbf.readSVarint();
            y += pbf.readSVarint();
            if (x < x1)
                x1 = x;
            if (x > x2)
                x2 = x;
            if (y < y1)
                y1 = y;
            if (y > y2)
                y2 = y;
        } else if (cmd !== 7) {
            throw new Error('unknown command ' + cmd);
        }
    }
    return [
        x1,
        y1,
        x2,
        y2
    ];
};
VectorTileFeature$2.prototype.toGeoJSON = function (x, y, z) {
    var size = this.extent * Math.pow(2, z), x0 = this.extent * x, y0 = this.extent * y, coords = this.loadGeometry(), type = VectorTileFeature$2.types[this.type], i, j;
    function project(line) {
        for (var j = 0; j < line.length; j++) {
            var p = line[j], y2 = 180 - (p.y + y0) * 360 / size;
            line[j] = [
                (p.x + x0) * 360 / size - 180,
                360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90
            ];
        }
    }
    switch (this.type) {
    case 1:
        var points = [];
        for (i = 0; i < coords.length; i++) {
            points[i] = coords[i][0];
        }
        coords = points;
        project(coords);
        break;
    case 2:
        for (i = 0; i < coords.length; i++) {
            project(coords[i]);
        }
        break;
    case 3:
        coords = classifyRings(coords);
        for (i = 0; i < coords.length; i++) {
            for (j = 0; j < coords[i].length; j++) {
                project(coords[i][j]);
            }
        }
        break;
    }
    if (coords.length === 1) {
        coords = coords[0];
    } else {
        type = 'Multi' + type;
    }
    var result = {
        type: 'Feature',
        geometry: {
            type: type,
            coordinates: coords
        },
        properties: this.properties
    };
    if ('id' in this) {
        result.id = this.id;
    }
    return result;
};
// classifies an array of rings into polygons with outer rings and holes
function classifyRings(rings) {
    var len = rings.length;
    if (len <= 1)
        return [rings];
    var polygons = [], polygon, ccw;
    for (var i = 0; i < len; i++) {
        var area = signedArea(rings[i]);
        if (area === 0)
            continue;
        if (ccw === undefined)
            ccw = area < 0;
        if (ccw === area < 0) {
            if (polygon)
                polygons.push(polygon);
            polygon = [rings[i]];
        } else {
            polygon.push(rings[i]);
        }
    }
    if (polygon)
        polygons.push(polygon);
    return polygons;
}
function signedArea(ring) {
    var sum = 0;
    for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {
        p1 = ring[i];
        p2 = ring[j];
        sum += (p2.x - p1.x) * (p1.y + p2.y);
    }
    return sum;
}

var VectorTileFeature$1 = vectortilefeature;
var vectortilelayer = VectorTileLayer$1;
function VectorTileLayer$1(pbf, end) {
    // Public
    this.version = 1;
    this.name = null;
    this.extent = 4096;
    this.length = 0;
    // Private
    this._pbf = pbf;
    this._keys = [];
    this._values = [];
    this._features = [];
    pbf.readFields(readLayer, this, end);
    this.length = this._features.length;
}
function readLayer(tag, layer, pbf) {
    if (tag === 15)
        layer.version = pbf.readVarint();
    else if (tag === 1)
        layer.name = pbf.readString();
    else if (tag === 5)
        layer.extent = pbf.readVarint();
    else if (tag === 2)
        layer._features.push(pbf.pos);
    else if (tag === 3)
        layer._keys.push(pbf.readString());
    else if (tag === 4)
        layer._values.push(readValueMessage(pbf));
}
function readValueMessage(pbf) {
    var value = null, end = pbf.readVarint() + pbf.pos;
    while (pbf.pos < end) {
        var tag = pbf.readVarint() >> 3;
        value = tag === 1 ? pbf.readString() : tag === 2 ? pbf.readFloat() : tag === 3 ? pbf.readDouble() : tag === 4 ? pbf.readVarint64() : tag === 5 ? pbf.readVarint() : tag === 6 ? pbf.readSVarint() : tag === 7 ? pbf.readBoolean() : null;
    }
    return value;
}
// return feature `i` from this layer as a `VectorTileFeature`
VectorTileLayer$1.prototype.feature = function (i) {
    if (i < 0 || i >= this._features.length)
        throw new Error('feature index out of bounds');
    this._pbf.pos = this._features[i];
    var end = this._pbf.readVarint() + this._pbf.pos;
    return new VectorTileFeature$1(this._pbf, end, this.extent, this._keys, this._values);
};

var VectorTileLayer = vectortilelayer;
var vectortile = VectorTile$1;
function VectorTile$1(pbf, end) {
    this.layers = pbf.readFields(readTile, {}, end);
}
function readTile(tag, layers, pbf) {
    if (tag === 3) {
        var layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);
        if (layer.length)
            layers[layer.name] = layer;
    }
}

var VectorTile = vectorTile.VectorTile = vectortile;
var VectorTileFeature = vectorTile.VectorTileFeature = vectortilefeature;
vectorTile.VectorTileLayer = vectortilelayer;

function clipPolygon(polygons, clipAxis1, clipAxis2, axis) {
    const intersectX = (ring, ax, ay, bx, by, x) => {
        ring.push(new Point$2(x, ay + (by - ay) * ((x - ax) / (bx - ax))));
    };
    const intersectY = (ring, ax, ay, bx, by, y) => {
        ring.push(new Point$2(ax + (bx - ax) * ((y - ay) / (by - ay)), y));
    };
    const polygonsClipped = [];
    const intersect = axis === 0 ? intersectX : intersectY;
    for (const polygon of polygons) {
        const polygonClipped = [];
        for (const ring of polygon) {
            if (ring.length <= 2) {
                continue;
            }
            const clipped = [];
            for (let i = 0; i < ring.length - 1; i++) {
                const ax = ring[i].x;
                const ay = ring[i].y;
                const bx = ring[i + 1].x;
                const by = ring[i + 1].y;
                const a = axis === 0 ? ax : ay;
                const b = axis === 0 ? bx : by;
                if (a < clipAxis1) {
                    if (b > clipAxis1) {
                        intersect(clipped, ax, ay, bx, by, clipAxis1);
                    }
                } else if (a > clipAxis2) {
                    if (b < clipAxis2) {
                        intersect(clipped, ax, ay, bx, by, clipAxis2);
                    }
                } else {
                    clipped.push(ring[i]);
                }
                if (b < clipAxis1 && a >= clipAxis1) {
                    intersect(clipped, ax, ay, bx, by, clipAxis1);
                }
                if (b > clipAxis2 && a <= clipAxis2) {
                    intersect(clipped, ax, ay, bx, by, clipAxis2);
                }
            }
            let last = ring[ring.length - 1];
            const a = axis === 0 ? last.x : last.y;
            if (a >= clipAxis1 && a <= clipAxis2) {
                clipped.push(last);
            }
            if (clipped.length) {
                last = clipped[clipped.length - 1];
                if (clipped[0].x !== last.x || clipped[0].y !== last.y) {
                    clipped.push(clipped[0]);
                }
                polygonClipped.push(clipped);
            }
        }
        if (polygonClipped.length) {
            polygonsClipped.push(polygonClipped);
        }
    }
    return polygonsClipped;
}
function subdividePolygons(polygons, bounds, gridSizeX, gridSizeY, padding = 0, splitFn) {
    const outPolygons = [];
    if (!polygons.length || !gridSizeX || !gridSizeY) {
        return outPolygons;
    }
    const addResult = (clipped, bounds) => {
        for (const polygon of clipped) {
            outPolygons.push({
                polygon,
                bounds
            });
        }
    };
    const hSplits = Math.ceil(Math.log2(gridSizeX));
    const vSplits = Math.ceil(Math.log2(gridSizeY));
    const initialSplits = hSplits - vSplits;
    const splits = [];
    for (let i = 0; i < Math.abs(initialSplits); i++) {
        splits.push(initialSplits > 0 ? 0 : 1);
    }
    for (let i = 0; i < Math.min(hSplits, vSplits); i++) {
        splits.push(0);
        // x
        splits.push(1);    // y
    }
    let split = polygons;
    split = clipPolygon(split, bounds[0].y - padding, bounds[1].y + padding, 1);
    split = clipPolygon(split, bounds[0].x - padding, bounds[1].x + padding, 0);
    if (!split.length) {
        return outPolygons;
    }
    const stack = [];
    if (splits.length) {
        stack.push({
            polygons: split,
            bounds,
            depth: 0
        });
    } else {
        addResult(split, bounds);
    }
    while (stack.length) {
        const frame = stack.pop();
        const depth = frame.depth;
        const axis = splits[depth];
        const bboxMin = frame.bounds[0];
        const bboxMax = frame.bounds[1];
        const splitMin = axis === 0 ? bboxMin.x : bboxMin.y;
        const splitMax = axis === 0 ? bboxMax.x : bboxMax.y;
        const splitMid = splitFn ? splitFn(axis, splitMin, splitMax) : 0.5 * (splitMin + splitMax);
        const lclip = clipPolygon(frame.polygons, splitMin - padding, splitMid + padding, axis);
        const rclip = clipPolygon(frame.polygons, splitMid - padding, splitMax + padding, axis);
        if (lclip.length) {
            const bbMaxX = axis === 0 ? splitMid : bboxMax.x;
            const bbMaxY = axis === 1 ? splitMid : bboxMax.y;
            const bbMax = new Point$2(bbMaxX, bbMaxY);
            const lclipBounds = [
                bboxMin,
                bbMax
            ];
            if (splits.length > depth + 1) {
                stack.push({
                    polygons: lclip,
                    bounds: lclipBounds,
                    depth: depth + 1
                });
            } else {
                addResult(lclip, lclipBounds);
            }
        }
        if (rclip.length) {
            const bbMinX = axis === 0 ? splitMid : bboxMin.x;
            const bbMinY = axis === 1 ? splitMid : bboxMin.y;
            const bbMin = new Point$2(bbMinX, bbMinY);
            const rclipBounds = [
                bbMin,
                bboxMax
            ];
            if (splits.length > depth + 1) {
                stack.push({
                    polygons: rclip,
                    bounds: rclipBounds,
                    depth: depth + 1
                });
            } else {
                addResult(rclip, rclipBounds);
            }
        }
    }
    return outPolygons;
}

//      
/**
 * The `Bucket` interface is the single point of knowledge about turning vector
 * tiles into WebGL buffers.
 *
 * `Bucket` is an abstract interface. An implementation exists for each style layer type.
 * Create a bucket via the `StyleLayer#createBucket` method.
 *
 * The concrete bucket types, using layout options from the style layer,
 * transform feature geometries into vertex and index data for use by the
 * vertex shader.  They also (via `ProgramConfiguration`) use feature
 * properties and the zoom level to populate the attributes needed for
 * data-driven styling.
 *
 * Buckets are designed to be built on a worker thread and then serialized and
 * transferred back to the main thread for rendering.  On the worker side, a
 * bucket's vertex, index, and attribute data is stored in `bucket.arrays:
 * ArrayGroup`.  When a bucket's data is serialized and sent back to the main
 * thread, is gets deserialized (using `new Bucket(serializedBucketData)`, with
 * the array data now stored in `bucket.buffers: BufferGroup`.  BufferGroups
 * hold the same data as ArrayGroups, but are tuned for consumption by WebGL.
 *
 * @private
 */
function deserialize(input, style) {
    const output = {};
    // Guard against the case where the map's style has been set to null while
    // this bucket has been parsing.
    if (!style)
        return output;
    for (const bucket of input) {
        const layers = bucket.layerIds.map(id => style.getLayer(id)).filter(Boolean);
        if (layers.length === 0) {
            continue;
        }
        // look up StyleLayer objects from layer ids (since we don't
        // want to waste time serializing/copying them from the worker)
        bucket.layers = layers;
        if (bucket.stateDependentLayerIds) {
            bucket.stateDependentLayers = bucket.stateDependentLayerIds.map(lId => layers.filter(l => l.id === lId)[0]);
        }
        for (const layer of layers) {
            output[layer.fqid] = bucket;
        }
    }
    return output;
}

class DictionaryCoder {
    constructor(strings) {
        this._stringToNumber = {};
        this._numberToString = [];
        for (let i = 0; i < strings.length; i++) {
            const string = strings[i];
            this._stringToNumber[string] = i;
            this._numberToString[i] = string;
        }
    }
    encode(string) {
        return this._stringToNumber[string];
    }
    decode(n) {
        return this._numberToString[n];
    }
}

var ieee754$1 = {};

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */

ieee754$1.read = function (buffer, offset, isLE, mLen, nBytes) {
    var e, m;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var nBits = -7;
    var i = isLE ? nBytes - 1 : 0;
    var d = isLE ? -1 : 1;
    var s = buffer[offset + i];
    i += d;
    e = s & (1 << -nBits) - 1;
    s >>= -nBits;
    nBits += eLen;
    for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
    }
    m = e & (1 << -nBits) - 1;
    e >>= -nBits;
    nBits += mLen;
    for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
    }
    if (e === 0) {
        e = 1 - eBias;
    } else if (e === eMax) {
        return m ? NaN : (s ? -1 : 1) * Infinity;
    } else {
        m = m + Math.pow(2, mLen);
        e = e - eBias;
    }
    return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
ieee754$1.write = function (buffer, value, offset, isLE, mLen, nBytes) {
    var e, m, c;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
    var i = isLE ? 0 : nBytes - 1;
    var d = isLE ? 1 : -1;
    var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
    value = Math.abs(value);
    if (isNaN(value) || value === Infinity) {
        m = isNaN(value) ? 1 : 0;
        e = eMax;
    } else {
        e = Math.floor(Math.log(value) / Math.LN2);
        if (value * (c = Math.pow(2, -e)) < 1) {
            e--;
            c *= 2;
        }
        if (e + eBias >= 1) {
            value += rt / c;
        } else {
            value += rt * Math.pow(2, 1 - eBias);
        }
        if (value * c >= 2) {
            e++;
            c /= 2;
        }
        if (e + eBias >= eMax) {
            m = 0;
            e = eMax;
        } else if (e + eBias >= 1) {
            m = (value * c - 1) * Math.pow(2, mLen);
            e = e + eBias;
        } else {
            m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
            e = 0;
        }
    }
    for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
    }
    e = e << mLen | m;
    eLen += mLen;
    for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
    }
    buffer[offset + i - d] |= s * 128;
};

var pbf = Pbf;
var ieee754 = ieee754$1;
function Pbf(buf) {
    this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
    this.pos = 0;
    this.type = 0;
    this.length = this.buf.length;
}
Pbf.Varint = 0;
// varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
Pbf.Fixed64 = 1;
// 64-bit: double, fixed64, sfixed64
Pbf.Bytes = 2;
// length-delimited: string, bytes, embedded messages, packed repeated fields
Pbf.Fixed32 = 5;
// 32-bit: float, fixed32, sfixed32
var SHIFT_LEFT_32 = (1 << 16) * (1 << 16), SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
// Threshold chosen based on both benchmarking and knowledge about browser string
// data structures (which currently switch structure types at 12 bytes or more)
var TEXT_DECODER_MIN_LENGTH = 12;
var utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf8');
Pbf.prototype = {
    destroy: function () {
        this.buf = null;
    },
    // === READING =================================================================
    readFields: function (readField, result, end) {
        end = end || this.length;
        while (this.pos < end) {
            var val = this.readVarint(), tag = val >> 3, startPos = this.pos;
            this.type = val & 7;
            readField(tag, result, this);
            if (this.pos === startPos)
                this.skip(val);
        }
        return result;
    },
    readMessage: function (readField, result) {
        return this.readFields(readField, result, this.readVarint() + this.pos);
    },
    readFixed32: function () {
        var val = readUInt32(this.buf, this.pos);
        this.pos += 4;
        return val;
    },
    readSFixed32: function () {
        var val = readInt32(this.buf, this.pos);
        this.pos += 4;
        return val;
    },
    // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
    readFixed64: function () {
        var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
        this.pos += 8;
        return val;
    },
    readSFixed64: function () {
        var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
        this.pos += 8;
        return val;
    },
    readFloat: function () {
        var val = ieee754.read(this.buf, this.pos, true, 23, 4);
        this.pos += 4;
        return val;
    },
    readDouble: function () {
        var val = ieee754.read(this.buf, this.pos, true, 52, 8);
        this.pos += 8;
        return val;
    },
    readVarint: function (isSigned) {
        var buf = this.buf, val, b;
        b = buf[this.pos++];
        val = b & 127;
        if (b < 128)
            return val;
        b = buf[this.pos++];
        val |= (b & 127) << 7;
        if (b < 128)
            return val;
        b = buf[this.pos++];
        val |= (b & 127) << 14;
        if (b < 128)
            return val;
        b = buf[this.pos++];
        val |= (b & 127) << 21;
        if (b < 128)
            return val;
        b = buf[this.pos];
        val |= (b & 15) << 28;
        return readVarintRemainder(val, isSigned, this);
    },
    readVarint64: function () {
        // for compatibility with v2.0.1
        return this.readVarint(true);
    },
    readSVarint: function () {
        var num = this.readVarint();
        return num % 2 === 1 ? (num + 1) / -2 : num / 2;    // zigzag encoding
    },
    readBoolean: function () {
        return Boolean(this.readVarint());
    },
    readString: function () {
        var end = this.readVarint() + this.pos;
        var pos = this.pos;
        this.pos = end;
        if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {
            // longer strings are fast with the built-in browser TextDecoder API
            return readUtf8TextDecoder(this.buf, pos, end);
        }
        // short strings are fast with our custom implementation
        return readUtf8(this.buf, pos, end);
    },
    readBytes: function () {
        var end = this.readVarint() + this.pos, buffer = this.buf.subarray(this.pos, end);
        this.pos = end;
        return buffer;
    },
    // verbose for performance reasons; doesn't affect gzipped size
    readPackedVarint: function (arr, isSigned) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readVarint(isSigned));
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readVarint(isSigned));
        return arr;
    },
    readPackedSVarint: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readSVarint());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readSVarint());
        return arr;
    },
    readPackedBoolean: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readBoolean());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readBoolean());
        return arr;
    },
    readPackedFloat: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readFloat());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readFloat());
        return arr;
    },
    readPackedDouble: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readDouble());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readDouble());
        return arr;
    },
    readPackedFixed32: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readFixed32());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readFixed32());
        return arr;
    },
    readPackedSFixed32: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readSFixed32());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readSFixed32());
        return arr;
    },
    readPackedFixed64: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readFixed64());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readFixed64());
        return arr;
    },
    readPackedSFixed64: function (arr) {
        if (this.type !== Pbf.Bytes)
            return arr.push(this.readSFixed64());
        var end = readPackedEnd(this);
        arr = arr || [];
        while (this.pos < end)
            arr.push(this.readSFixed64());
        return arr;
    },
    skip: function (val) {
        var type = val & 7;
        if (type === Pbf.Varint)
            while (this.buf[this.pos++] > 127) {
            }
        else if (type === Pbf.Bytes)
            this.pos = this.readVarint() + this.pos;
        else if (type === Pbf.Fixed32)
            this.pos += 4;
        else if (type === Pbf.Fixed64)
            this.pos += 8;
        else
            throw new Error('Unimplemented type: ' + type);
    },
    // === WRITING =================================================================
    writeTag: function (tag, type) {
        this.writeVarint(tag << 3 | type);
    },
    realloc: function (min) {
        var length = this.length || 16;
        while (length < this.pos + min)
            length *= 2;
        if (length !== this.length) {
            var buf = new Uint8Array(length);
            buf.set(this.buf);
            this.buf = buf;
            this.length = length;
        }
    },
    finish: function () {
        this.length = this.pos;
        this.pos = 0;
        return this.buf.subarray(0, this.length);
    },
    writeFixed32: function (val) {
        this.realloc(4);
        writeInt32(this.buf, val, this.pos);
        this.pos += 4;
    },
    writeSFixed32: function (val) {
        this.realloc(4);
        writeInt32(this.buf, val, this.pos);
        this.pos += 4;
    },
    writeFixed64: function (val) {
        this.realloc(8);
        writeInt32(this.buf, val & -1, this.pos);
        writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
        this.pos += 8;
    },
    writeSFixed64: function (val) {
        this.realloc(8);
        writeInt32(this.buf, val & -1, this.pos);
        writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
        this.pos += 8;
    },
    writeVarint: function (val) {
        val = +val || 0;
        if (val > 268435455 || val < 0) {
            writeBigVarint(val, this);
            return;
        }
        this.realloc(4);
        this.buf[this.pos++] = val & 127 | (val > 127 ? 128 : 0);
        if (val <= 127)
            return;
        this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0);
        if (val <= 127)
            return;
        this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0);
        if (val <= 127)
            return;
        this.buf[this.pos++] = val >>> 7 & 127;
    },
    writeSVarint: function (val) {
        this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
    },
    writeBoolean: function (val) {
        this.writeVarint(Boolean(val));
    },
    writeString: function (str) {
        str = String(str);
        this.realloc(str.length * 4);
        this.pos++;
        // reserve 1 byte for short string length
        var startPos = this.pos;
        // write the string directly to the buffer and see how much was written
        this.pos = writeUtf8(this.buf, str, this.pos);
        var len = this.pos - startPos;
        if (len >= 128)
            makeRoomForExtraLength(startPos, len, this);
        // finally, write the message length in the reserved place and restore the position
        this.pos = startPos - 1;
        this.writeVarint(len);
        this.pos += len;
    },
    writeFloat: function (val) {
        this.realloc(4);
        ieee754.write(this.buf, val, this.pos, true, 23, 4);
        this.pos += 4;
    },
    writeDouble: function (val) {
        this.realloc(8);
        ieee754.write(this.buf, val, this.pos, true, 52, 8);
        this.pos += 8;
    },
    writeBytes: function (buffer) {
        var len = buffer.length;
        this.writeVarint(len);
        this.realloc(len);
        for (var i = 0; i < len; i++)
            this.buf[this.pos++] = buffer[i];
    },
    writeRawMessage: function (fn, obj) {
        this.pos++;
        // reserve 1 byte for short message length
        // write the message directly to the buffer and see how much was written
        var startPos = this.pos;
        fn(obj, this);
        var len = this.pos - startPos;
        if (len >= 128)
            makeRoomForExtraLength(startPos, len, this);
        // finally, write the message length in the reserved place and restore the position
        this.pos = startPos - 1;
        this.writeVarint(len);
        this.pos += len;
    },
    writeMessage: function (tag, fn, obj) {
        this.writeTag(tag, Pbf.Bytes);
        this.writeRawMessage(fn, obj);
    },
    writePackedVarint: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedVarint, arr);
    },
    writePackedSVarint: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedSVarint, arr);
    },
    writePackedBoolean: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedBoolean, arr);
    },
    writePackedFloat: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedFloat, arr);
    },
    writePackedDouble: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedDouble, arr);
    },
    writePackedFixed32: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedFixed32, arr);
    },
    writePackedSFixed32: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedSFixed32, arr);
    },
    writePackedFixed64: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedFixed64, arr);
    },
    writePackedSFixed64: function (tag, arr) {
        if (arr.length)
            this.writeMessage(tag, writePackedSFixed64, arr);
    },
    writeBytesField: function (tag, buffer) {
        this.writeTag(tag, Pbf.Bytes);
        this.writeBytes(buffer);
    },
    writeFixed32Field: function (tag, val) {
        this.writeTag(tag, Pbf.Fixed32);
        this.writeFixed32(val);
    },
    writeSFixed32Field: function (tag, val) {
        this.writeTag(tag, Pbf.Fixed32);
        this.writeSFixed32(val);
    },
    writeFixed64Field: function (tag, val) {
        this.writeTag(tag, Pbf.Fixed64);
        this.writeFixed64(val);
    },
    writeSFixed64Field: function (tag, val) {
        this.writeTag(tag, Pbf.Fixed64);
        this.writeSFixed64(val);
    },
    writeVarintField: function (tag, val) {
        this.writeTag(tag, Pbf.Varint);
        this.writeVarint(val);
    },
    writeSVarintField: function (tag, val) {
        this.writeTag(tag, Pbf.Varint);
        this.writeSVarint(val);
    },
    writeStringField: function (tag, str) {
        this.writeTag(tag, Pbf.Bytes);
        this.writeString(str);
    },
    writeFloatField: function (tag, val) {
        this.writeTag(tag, Pbf.Fixed32);
        this.writeFloat(val);
    },
    writeDoubleField: function (tag, val) {
        this.writeTag(tag, Pbf.Fixed64);
        this.writeDouble(val);
    },
    writeBooleanField: function (tag, val) {
        this.writeVarintField(tag, Boolean(val));
    }
};
function readVarintRemainder(l, s, p) {
    var buf = p.buf, h, b;
    b = buf[p.pos++];
    h = (b & 112) >> 4;
    if (b < 128)
        return toNum(l, h, s);
    b = buf[p.pos++];
    h |= (b & 127) << 3;
    if (b < 128)
        return toNum(l, h, s);
    b = buf[p.pos++];
    h |= (b & 127) << 10;
    if (b < 128)
        return toNum(l, h, s);
    b = buf[p.pos++];
    h |= (b & 127) << 17;
    if (b < 128)
        return toNum(l, h, s);
    b = buf[p.pos++];
    h |= (b & 127) << 24;
    if (b < 128)
        return toNum(l, h, s);
    b = buf[p.pos++];
    h |= (b & 1) << 31;
    if (b < 128)
        return toNum(l, h, s);
    throw new Error('Expected varint not more than 10 bytes');
}
function readPackedEnd(pbf) {
    return pbf.type === Pbf.Bytes ? pbf.readVarint() + pbf.pos : pbf.pos + 1;
}
function toNum(low, high, isSigned) {
    if (isSigned) {
        return high * 4294967296 + (low >>> 0);
    }
    return (high >>> 0) * 4294967296 + (low >>> 0);
}
function writeBigVarint(val, pbf) {
    var low, high;
    if (val >= 0) {
        low = val % 4294967296 | 0;
        high = val / 4294967296 | 0;
    } else {
        low = ~(-val % 4294967296);
        high = ~(-val / 4294967296);
        if (low ^ 4294967295) {
            low = low + 1 | 0;
        } else {
            low = 0;
            high = high + 1 | 0;
        }
    }
    if (val >= 18446744073709552000 || val < -18446744073709552000) {
        throw new Error('Given varint doesn\'t fit into 10 bytes');
    }
    pbf.realloc(10);
    writeBigVarintLow(low, high, pbf);
    writeBigVarintHigh(high, pbf);
}
function writeBigVarintLow(low, high, pbf) {
    pbf.buf[pbf.pos++] = low & 127 | 128;
    low >>>= 7;
    pbf.buf[pbf.pos++] = low & 127 | 128;
    low >>>= 7;
    pbf.buf[pbf.pos++] = low & 127 | 128;
    low >>>= 7;
    pbf.buf[pbf.pos++] = low & 127 | 128;
    low >>>= 7;
    pbf.buf[pbf.pos] = low & 127;
}
function writeBigVarintHigh(high, pbf) {
    var lsb = (high & 7) << 4;
    pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 128 : 0);
    if (!high)
        return;
    pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
    if (!high)
        return;
    pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
    if (!high)
        return;
    pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
    if (!high)
        return;
    pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
    if (!high)
        return;
    pbf.buf[pbf.pos++] = high & 127;
}
function makeRoomForExtraLength(startPos, len, pbf) {
    var extraLen = len <= 16383 ? 1 : len <= 2097151 ? 2 : len <= 268435455 ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));
    // if 1 byte isn't enough for encoding message length, shift the data to the right
    pbf.realloc(extraLen);
    for (var i = pbf.pos - 1; i >= startPos; i--)
        pbf.buf[i + extraLen] = pbf.buf[i];
}
function writePackedVarint(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeVarint(arr[i]);
}
function writePackedSVarint(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeSVarint(arr[i]);
}
function writePackedFloat(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeFloat(arr[i]);
}
function writePackedDouble(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeDouble(arr[i]);
}
function writePackedBoolean(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeBoolean(arr[i]);
}
function writePackedFixed32(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeFixed32(arr[i]);
}
function writePackedSFixed32(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeSFixed32(arr[i]);
}
function writePackedFixed64(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeFixed64(arr[i]);
}
function writePackedSFixed64(arr, pbf) {
    for (var i = 0; i < arr.length; i++)
        pbf.writeSFixed64(arr[i]);
}
// Buffer code below from https://github.com/feross/buffer, MIT-licensed
function readUInt32(buf, pos) {
    return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + buf[pos + 3] * 16777216;
}
function writeInt32(buf, val, pos) {
    buf[pos] = val;
    buf[pos + 1] = val >>> 8;
    buf[pos + 2] = val >>> 16;
    buf[pos + 3] = val >>> 24;
}
function readInt32(buf, pos) {
    return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + (buf[pos + 3] << 24);
}
function readUtf8(buf, pos, end) {
    var str = '';
    var i = pos;
    while (i < end) {
        var b0 = buf[i];
        var c = null;
        // codepoint
        var bytesPerSequence = b0 > 239 ? 4 : b0 > 223 ? 3 : b0 > 191 ? 2 : 1;
        if (i + bytesPerSequence > end)
            break;
        var b1, b2, b3;
        if (bytesPerSequence === 1) {
            if (b0 < 128) {
                c = b0;
            }
        } else if (bytesPerSequence === 2) {
            b1 = buf[i + 1];
            if ((b1 & 192) === 128) {
                c = (b0 & 31) << 6 | b1 & 63;
                if (c <= 127) {
                    c = null;
                }
            }
        } else if (bytesPerSequence === 3) {
            b1 = buf[i + 1];
            b2 = buf[i + 2];
            if ((b1 & 192) === 128 && (b2 & 192) === 128) {
                c = (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63;
                if (c <= 2047 || c >= 55296 && c <= 57343) {
                    c = null;
                }
            }
        } else if (bytesPerSequence === 4) {
            b1 = buf[i + 1];
            b2 = buf[i + 2];
            b3 = buf[i + 3];
            if ((b1 & 192) === 128 && (b2 & 192) === 128 && (b3 & 192) === 128) {
                c = (b0 & 15) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63;
                if (c <= 65535 || c >= 1114112) {
                    c = null;
                }
            }
        }
        if (c === null) {
            c = 65533;
            bytesPerSequence = 1;
        } else if (c > 65535) {
            c -= 65536;
            str += String.fromCharCode(c >>> 10 & 1023 | 55296);
            c = 56320 | c & 1023;
        }
        str += String.fromCharCode(c);
        i += bytesPerSequence;
    }
    return str;
}
function readUtf8TextDecoder(buf, pos, end) {
    return utf8TextDecoder.decode(buf.subarray(pos, end));
}
function writeUtf8(buf, str, pos) {
    for (var i = 0, c, lead; i < str.length; i++) {
        c = str.charCodeAt(i);
        // code point
        if (c > 55295 && c < 57344) {
            if (lead) {
                if (c < 56320) {
                    buf[pos++] = 239;
                    buf[pos++] = 191;
                    buf[pos++] = 189;
                    lead = c;
                    continue;
                } else {
                    c = lead - 55296 << 10 | c - 56320 | 65536;
                    lead = null;
                }
            } else {
                if (c > 56319 || i + 1 === str.length) {
                    buf[pos++] = 239;
                    buf[pos++] = 191;
                    buf[pos++] = 189;
                } else {
                    lead = c;
                }
                continue;
            }
        } else if (lead) {
            buf[pos++] = 239;
            buf[pos++] = 191;
            buf[pos++] = 189;
            lead = null;
        }
        if (c < 128) {
            buf[pos++] = c;
        } else {
            if (c < 2048) {
                buf[pos++] = c >> 6 | 192;
            } else {
                if (c < 65536) {
                    buf[pos++] = c >> 12 | 224;
                } else {
                    buf[pos++] = c >> 18 | 240;
                    buf[pos++] = c >> 12 & 63 | 128;
                }
                buf[pos++] = c >> 6 & 63 | 128;
            }
            buf[pos++] = c & 63 | 128;
        }
    }
    return pos;
}

var Protobuf = /*@__PURE__*/getDefaultExportFromCjs(pbf);

//      
// we augment GeoJSON with custom properties in query*Features results
const customProps = [
    'tile',
    'layer',
    'source',
    'sourceLayer',
    'state'
];
class Feature {
    constructor(vectorTileFeature, z, x, y, id) {
        this.type = 'Feature';
        this._vectorTileFeature = vectorTileFeature;
        this._z = z;
        this._x = x;
        this._y = y;
        this.properties = vectorTileFeature.properties;
        this.id = id;
    }
    get geometry() {
        if (this._geometry === undefined) {
            this._geometry = this._vectorTileFeature.toGeoJSON(this._x, this._y, this._z).geometry;
        }
        return this._geometry;
    }
    set geometry(g) {
        this._geometry = g;
    }
    toJSON() {
        const json = {
            type: 'Feature',
            state: undefined,
            geometry: this.geometry,
            properties: this.properties
        };
        if (this.id !== undefined)
            json.id = this.id;
        for (const key of customProps) {
            // Flow doesn't support indexed access for classes https://github.com/facebook/flow/issues/1323
            if (this[key] !== undefined)
                json[key] = this[key];
        }
        return json;
    }
}

//      
/**
 * SourceFeatureState manages the state and pending changes
 * to features in a source, separated by source layer.
 * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)
 * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's
 * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.
 * In deletedStates, all null's denote complete removal of state at that scope
 * @private
*/
class SourceFeatureState {
    constructor() {
        this.state = {};
        this.stateChanges = {};
        this.deletedStates = {};
    }
    updateState(sourceLayer, featureId, newState) {
        const feature = String(featureId);
        this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};
        this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};
        extend$1(this.stateChanges[sourceLayer][feature], newState);
        if (this.deletedStates[sourceLayer] === null) {
            this.deletedStates[sourceLayer] = {};
            for (const ft in this.state[sourceLayer]) {
                if (ft !== feature)
                    this.deletedStates[sourceLayer][ft] = null;
            }
        } else {
            const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null;
            if (featureDeletionQueued) {
                this.deletedStates[sourceLayer][feature] = {};
                for (const prop in this.state[sourceLayer][feature]) {
                    if (!newState[prop])
                        this.deletedStates[sourceLayer][feature][prop] = null;
                }
            } else {
                for (const key in newState) {
                    const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null;
                    if (deletionInQueue)
                        delete this.deletedStates[sourceLayer][feature][key];
                }
            }
        }
    }
    removeFeatureState(sourceLayer, featureId, key) {
        const sourceLayerDeleted = this.deletedStates[sourceLayer] === null;
        if (sourceLayerDeleted)
            return;
        const feature = String(featureId);
        this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {};
        if (key && featureId !== undefined) {
            if (this.deletedStates[sourceLayer][feature] !== null) {
                this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};
                this.deletedStates[sourceLayer][feature][key] = null;
            }
        } else if (featureId !== undefined) {
            const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature];
            if (updateInQueue) {
                this.deletedStates[sourceLayer][feature] = {};
                for (key in this.stateChanges[sourceLayer][feature])
                    this.deletedStates[sourceLayer][feature][key] = null;
            } else {
                this.deletedStates[sourceLayer][feature] = null;
            }
        } else {
            this.deletedStates[sourceLayer] = null;
        }
    }
    getState(sourceLayer, featureId) {
        const feature = String(featureId);
        const base = this.state[sourceLayer] || {};
        const changes = this.stateChanges[sourceLayer] || {};
        const reconciledState = extend$1({}, base[feature], changes[feature]);
        //return empty object if the whole source layer is awaiting deletion
        if (this.deletedStates[sourceLayer] === null)
            return {};
        else if (this.deletedStates[sourceLayer]) {
            const featureDeletions = this.deletedStates[sourceLayer][featureId];
            if (featureDeletions === null)
                return {};
            for (const prop in featureDeletions)
                delete reconciledState[prop];
        }
        return reconciledState;
    }
    initializeTileState(tile, painter) {
        tile.setFeatureState(this.state, painter);
    }
    coalesceChanges(tiles, painter) {
        //track changes with full state objects, but only for features that got modified
        const featuresChanged = {};
        for (const sourceLayer in this.stateChanges) {
            this.state[sourceLayer] = this.state[sourceLayer] || {};
            const layerStates = {};
            for (const feature in this.stateChanges[sourceLayer]) {
                if (!this.state[sourceLayer][feature])
                    this.state[sourceLayer][feature] = {};
                extend$1(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);
                layerStates[feature] = this.state[sourceLayer][feature];
            }
            featuresChanged[sourceLayer] = layerStates;
        }
        for (const sourceLayer in this.deletedStates) {
            this.state[sourceLayer] = this.state[sourceLayer] || {};
            const layerStates = {};
            if (this.deletedStates[sourceLayer] === null) {
                for (const ft in this.state[sourceLayer]) {
                    layerStates[ft] = {};
                    this.state[sourceLayer][ft] = {};
                }
            } else {
                for (const feature in this.deletedStates[sourceLayer]) {
                    const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null;
                    if (deleteWholeFeatureState)
                        this.state[sourceLayer][feature] = {};
                    else if (this.state[sourceLayer][feature]) {
                        for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) {
                            delete this.state[sourceLayer][feature][key];
                        }
                    }
                    layerStates[feature] = this.state[sourceLayer][feature];
                }
            }
            featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {};
            extend$1(featuresChanged[sourceLayer], layerStates);
        }
        this.stateChanges = {};
        this.deletedStates = {};
        if (Object.keys(featuresChanged).length === 0)
            return;
        for (const id in tiles) {
            const tile = tiles[id];
            tile.setFeatureState(featuresChanged, painter);
        }
    }
}

//      
class MipLevel {
    constructor(size_) {
        this.size = size_;
        this.minimums = [];
        this.maximums = [];
        this.leaves = [];
    }
    getElevation(x, y) {
        const idx = this.toIdx(x, y);
        return {
            min: this.minimums[idx],
            max: this.maximums[idx]
        };
    }
    isLeaf(x, y) {
        return this.leaves[this.toIdx(x, y)];
    }
    toIdx(x, y) {
        return y * this.size + x;
    }
}
function aabbRayIntersect(min, max, pos, dir) {
    let tMin = 0;
    let tMax = Number.MAX_VALUE;
    const epsilon = 1e-15;
    for (let i = 0; i < 3; i++) {
        if (Math.abs(dir[i]) < epsilon) {
            // Parallel ray
            if (pos[i] < min[i] || pos[i] > max[i])
                return null;
        } else {
            const ood = 1 / dir[i];
            let t1 = (min[i] - pos[i]) * ood;
            let t2 = (max[i] - pos[i]) * ood;
            if (t1 > t2) {
                const temp = t1;
                t1 = t2;
                t2 = temp;
            }
            if (t1 > tMin)
                tMin = t1;
            if (t2 < tMax)
                tMax = t2;
            if (tMin > tMax)
                return null;
        }
    }
    return tMin;
}
function triangleRayIntersect(ax, ay, az, bx, by, bz, cx, cy, cz, pos, dir) {
    // Compute barycentric coordinates u and v to find the intersection
    const abX = bx - ax;
    const abY = by - ay;
    const abZ = bz - az;
    const acX = cx - ax;
    const acY = cy - ay;
    const acZ = cz - az;
    // pvec = cross(dir, a), det = dot(ab, pvec)
    const pvecX = dir[1] * acZ - dir[2] * acY;
    const pvecY = dir[2] * acX - dir[0] * acZ;
    const pvecZ = dir[0] * acY - dir[1] * acX;
    const det = abX * pvecX + abY * pvecY + abZ * pvecZ;
    if (Math.abs(det) < 1e-15)
        return null;
    const invDet = 1 / det;
    const tvecX = pos[0] - ax;
    const tvecY = pos[1] - ay;
    const tvecZ = pos[2] - az;
    const u = (tvecX * pvecX + tvecY * pvecY + tvecZ * pvecZ) * invDet;
    if (u < 0 || u > 1)
        return null;
    // qvec = cross(tvec, ab)
    const qvecX = tvecY * abZ - tvecZ * abY;
    const qvecY = tvecZ * abX - tvecX * abZ;
    const qvecZ = tvecX * abY - tvecY * abX;
    const v = (dir[0] * qvecX + dir[1] * qvecY + dir[2] * qvecZ) * invDet;
    if (v < 0 || u + v > 1)
        return null;
    return (acX * qvecX + acY * qvecY + acZ * qvecZ) * invDet;
}
function frac(v, lo, hi) {
    return (v - lo) / (hi - lo);
}
function decodeBounds(x, y, depth, boundsMinx, boundsMiny, boundsMaxx, boundsMaxy, outMin, outMax) {
    const scale = 1 << depth;
    const rangex = boundsMaxx - boundsMinx;
    const rangey = boundsMaxy - boundsMiny;
    const minX = (x + 0) / scale * rangex + boundsMinx;
    const maxX = (x + 1) / scale * rangex + boundsMinx;
    const minY = (y + 0) / scale * rangey + boundsMiny;
    const maxY = (y + 1) / scale * rangey + boundsMiny;
    outMin[0] = minX;
    outMin[1] = minY;
    outMax[0] = maxX;
    outMax[1] = maxY;
}
// A small padding value is used with bounding boxes to extend the bottom below sea level
const aabbSkirtPadding = 100;
// A sparse min max quad tree for performing accelerated queries against dem elevation data.
// Each tree node stores the minimum and maximum elevation of its children nodes and a flag whether the node is a leaf.
// Node data is stored in non-interleaved arrays where the root is at index 0.
class DemMinMaxQuadTree {
    constructor(dem_) {
        this.maximums = [];
        this.minimums = [];
        this.leaves = [];
        this.childOffsets = [];
        this.nodeCount = 0;
        this.dem = dem_;
        // Precompute the order of 4 sibling nodes in the memory. Top-left, top-right, bottom-left, bottom-right
        this._siblingOffset = [
            [
                0,
                0
            ],
            [
                1,
                0
            ],
            [
                0,
                1
            ],
            [
                1,
                1
            ]
        ];
        if (!this.dem)
            return;
        const mips = buildDemMipmap(this.dem);
        const maxLvl = mips.length - 1;
        // Create the root node
        const rootMip = mips[maxLvl];
        const min = rootMip.minimums;
        const max = rootMip.maximums;
        const leaves = rootMip.leaves;
        this._addNode(min[0], max[0], leaves[0]);
        // Construct the rest of the tree recursively
        this._construct(mips, 0, 0, maxLvl, 0);
    }
    // Performs raycast against the tree root only. Min and max coordinates defines the size of the root node
    raycastRoot(minx, miny, maxx, maxy, p, d, exaggeration = 1) {
        const min = [
            minx,
            miny,
            -aabbSkirtPadding
        ];
        const max = [
            maxx,
            maxy,
            this.maximums[0] * exaggeration
        ];
        return aabbRayIntersect(min, max, p, d);
    }
    raycast(rootMinx, rootMiny, rootMaxx, rootMaxy, p, d, exaggeration = 1) {
        if (!this.nodeCount)
            return null;
        const t = this.raycastRoot(rootMinx, rootMiny, rootMaxx, rootMaxy, p, d, exaggeration);
        if (t == null)
            return null;
        const tHits = [];
        const sortedHits = [];
        const boundsMin = [];
        const boundsMax = [];
        const stack = [{
                idx: 0,
                t,
                nodex: 0,
                nodey: 0,
                depth: 0
            }];
        // Traverse the tree until something is hit or the ray escapes
        while (stack.length > 0) {
            const {idx, t, nodex, nodey, depth} = stack.pop();
            if (this.leaves[idx]) {
                // Create 2 triangles to approximate the surface plane for more precise tests
                decodeBounds(nodex, nodey, depth, rootMinx, rootMiny, rootMaxx, rootMaxy, boundsMin, boundsMax);
                const scale = 1 << depth;
                const minxUv = (nodex + 0) / scale;
                const maxxUv = (nodex + 1) / scale;
                const minyUv = (nodey + 0) / scale;
                const maxyUv = (nodey + 1) / scale;
                // 4 corner points A, B, C and D defines the (quad) area covered by this node
                const az = sampleElevation(minxUv, minyUv, this.dem) * exaggeration;
                const bz = sampleElevation(maxxUv, minyUv, this.dem) * exaggeration;
                const cz = sampleElevation(maxxUv, maxyUv, this.dem) * exaggeration;
                const dz = sampleElevation(minxUv, maxyUv, this.dem) * exaggeration;
                const t0 = triangleRayIntersect(boundsMin[0], boundsMin[1], az, // A
                boundsMax[0], boundsMin[1], bz, // B
                boundsMax[0], boundsMax[1], cz, // C
                p, d);
                const t1 = triangleRayIntersect(boundsMax[0], boundsMax[1], cz, boundsMin[0], boundsMax[1], dz, boundsMin[0], boundsMin[1], az, p, d);
                const tMin = Math.min(t0 !== null ? t0 : Number.MAX_VALUE, t1 !== null ? t1 : Number.MAX_VALUE);
                // The ray might go below the two surface triangles but hit one of the sides.
                // This covers the case of skirt geometry between two dem tiles of different zoom level
                if (tMin === Number.MAX_VALUE) {
                    const hitPos = vec3_1.scaleAndAdd([], p, d, t);
                    const fracx = frac(hitPos[0], boundsMin[0], boundsMax[0]);
                    const fracy = frac(hitPos[1], boundsMin[1], boundsMax[1]);
                    if (bilinearLerp(az, bz, dz, cz, fracx, fracy) >= hitPos[2])
                        return t;
                } else {
                    return tMin;
                }
                continue;
            }
            // Perform intersection tests agains each of the 4 child nodes and store results from closest to furthest.
            let hitCount = 0;
            for (let i = 0; i < this._siblingOffset.length; i++) {
                const childNodeX = (nodex << 1) + this._siblingOffset[i][0];
                const childNodeY = (nodey << 1) + this._siblingOffset[i][1];
                // Decode node aabb from the morton code
                decodeBounds(childNodeX, childNodeY, depth + 1, rootMinx, rootMiny, rootMaxx, rootMaxy, boundsMin, boundsMax);
                boundsMin[2] = -aabbSkirtPadding;
                boundsMax[2] = this.maximums[this.childOffsets[idx] + i] * exaggeration;
                const result = aabbRayIntersect(boundsMin, boundsMax, p, d);
                if (result != null) {
                    // Build the result list from furthest to closest hit.
                    // The order will be inversed when building the stack
                    const tHit = result;
                    tHits[i] = tHit;
                    let added = false;
                    for (let j = 0; j < hitCount && !added; j++) {
                        if (tHit >= tHits[sortedHits[j]]) {
                            sortedHits.splice(j, 0, i);
                            added = true;
                        }
                    }
                    if (!added)
                        sortedHits[hitCount] = i;
                    hitCount++;
                }
            }
            // Continue recursion from closest to furthest
            for (let i = 0; i < hitCount; i++) {
                const hitIdx = sortedHits[i];
                stack.push({
                    idx: this.childOffsets[idx] + hitIdx,
                    t: tHits[hitIdx],
                    nodex: (nodex << 1) + this._siblingOffset[hitIdx][0],
                    nodey: (nodey << 1) + this._siblingOffset[hitIdx][1],
                    depth: depth + 1
                });
            }
        }
        return null;
    }
    _addNode(min, max, leaf) {
        this.minimums.push(min);
        this.maximums.push(max);
        this.leaves.push(leaf);
        this.childOffsets.push(0);
        return this.nodeCount++;
    }
    _construct(mips, x, y, lvl, parentIdx) {
        if (mips[lvl].isLeaf(x, y) === 1) {
            return;
        }
        // Update parent offset
        if (!this.childOffsets[parentIdx])
            this.childOffsets[parentIdx] = this.nodeCount;
        // Construct all 4 children and place them next to each other in memory
        const childLvl = lvl - 1;
        const childMip = mips[childLvl];
        let leafMask = 0;
        let firstNodeIdx = 0;
        for (let i = 0; i < this._siblingOffset.length; i++) {
            const childX = x * 2 + this._siblingOffset[i][0];
            const childY = y * 2 + this._siblingOffset[i][1];
            const elevation = childMip.getElevation(childX, childY);
            const leaf = childMip.isLeaf(childX, childY);
            const nodeIdx = this._addNode(elevation.min, elevation.max, leaf);
            if (leaf)
                leafMask |= 1 << i;
            if (!firstNodeIdx)
                firstNodeIdx = nodeIdx;
        }
        // Continue construction of the tree recursively to non-leaf nodes.
        for (let i = 0; i < this._siblingOffset.length; i++) {
            if (!(leafMask & 1 << i)) {
                this._construct(mips, x * 2 + this._siblingOffset[i][0], y * 2 + this._siblingOffset[i][1], childLvl, firstNodeIdx + i);
            }
        }
    }
}
function bilinearLerp(p00, p10, p01, p11, x, y) {
    return number(number(p00, p01, y), number(p10, p11, y), x);
}
// Sample elevation in normalized uv-space ([0, 0] is the top left)
// This function does not account for exaggeration
function sampleElevation(fx, fy, dem) {
    // Sample position in texels
    const demSize = dem.dim;
    const x = clamp(fx * demSize - 0.5, 0, demSize - 1);
    const y = clamp(fy * demSize - 0.5, 0, demSize - 1);
    // Compute 4 corner points for bilinear interpolation
    const ixMin = Math.floor(x);
    const iyMin = Math.floor(y);
    const ixMax = Math.min(ixMin + 1, demSize - 1);
    const iyMax = Math.min(iyMin + 1, demSize - 1);
    const e00 = dem.get(ixMin, iyMin);
    const e10 = dem.get(ixMax, iyMin);
    const e01 = dem.get(ixMin, iyMax);
    const e11 = dem.get(ixMax, iyMax);
    return bilinearLerp(e00, e10, e01, e11, x - ixMin, y - iyMin);
}
function buildDemMipmap(dem) {
    const demSize = dem.dim;
    const elevationDiffThreshold = 5;
    const texelSizeOfMip0 = 8;
    const levelCount = Math.ceil(Math.log2(demSize / texelSizeOfMip0));
    const mips = [];
    let blockCount = Math.ceil(Math.pow(2, levelCount));
    const blockSize = 1 / blockCount;
    const blockSamples = (x, y, size, exclusive, outBounds) => {
        const padding = exclusive ? 1 : 0;
        const minx = x * size;
        const maxx = (x + 1) * size - padding;
        const miny = y * size;
        const maxy = (y + 1) * size - padding;
        outBounds[0] = minx;
        outBounds[1] = miny;
        outBounds[2] = maxx;
        outBounds[3] = maxy;
    };
    // The first mip (0) is built by sampling 4 corner points of each 8x8 texel block
    let mip = new MipLevel(blockCount);
    const blockBounds = [];
    for (let idx = 0; idx < blockCount * blockCount; idx++) {
        const y = Math.floor(idx / blockCount);
        const x = idx % blockCount;
        blockSamples(x, y, blockSize, false, blockBounds);
        const e0 = sampleElevation(blockBounds[0], blockBounds[1], dem);
        // minx, miny
        const e1 = sampleElevation(blockBounds[2], blockBounds[1], dem);
        // maxx, miny
        const e2 = sampleElevation(blockBounds[2], blockBounds[3], dem);
        // maxx, maxy
        const e3 = sampleElevation(blockBounds[0], blockBounds[3], dem);
        // minx, maxy
        mip.minimums.push(Math.min(e0, e1, e2, e3));
        mip.maximums.push(Math.max(e0, e1, e2, e3));
        mip.leaves.push(1);
    }
    mips.push(mip);
    // Construct the rest of the mip levels from bottom to up
    for (blockCount /= 2; blockCount >= 1; blockCount /= 2) {
        const prevMip = mips[mips.length - 1];
        mip = new MipLevel(blockCount);
        for (let idx = 0; idx < blockCount * blockCount; idx++) {
            const y = Math.floor(idx / blockCount);
            const x = idx % blockCount;
            // Sample elevation of all 4 children mip texels. 4 leaf nodes can be concatenated into a single
            // leaf if the total elevation difference is below the threshold value
            blockSamples(x, y, 2, true, blockBounds);
            const e0 = prevMip.getElevation(blockBounds[0], blockBounds[1]);
            const e1 = prevMip.getElevation(blockBounds[2], blockBounds[1]);
            const e2 = prevMip.getElevation(blockBounds[2], blockBounds[3]);
            const e3 = prevMip.getElevation(blockBounds[0], blockBounds[3]);
            const l0 = prevMip.isLeaf(blockBounds[0], blockBounds[1]);
            const l1 = prevMip.isLeaf(blockBounds[2], blockBounds[1]);
            const l2 = prevMip.isLeaf(blockBounds[2], blockBounds[3]);
            const l3 = prevMip.isLeaf(blockBounds[0], blockBounds[3]);
            const minElevation = Math.min(e0.min, e1.min, e2.min, e3.min);
            const maxElevation = Math.max(e0.max, e1.max, e2.max, e3.max);
            const canConcatenate = l0 && l1 && l2 && l3;
            mip.maximums.push(maxElevation);
            mip.minimums.push(minElevation);
            if (maxElevation - minElevation <= elevationDiffThreshold && canConcatenate) {
                // All samples have uniform elevation. Mark this as a leaf
                mip.leaves.push(1);
            } else {
                mip.leaves.push(0);
            }
        }
        mips.push(mip);
    }
    return mips;
}

//      
// DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders
// data can be populated either from a pngraw image tile or from serliazed data sent back from a worker. When data is initially
// loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the
// elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of
// integer overflow when creating the texture used in the hillshadePrepare step.
// DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8
// surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a
// tile's edge without backfilling from neighboring tiles.
const unpackVectors = {
    mapbox: [
        6553.6,
        25.6,
        0.1,
        10000
    ],
    terrarium: [
        256,
        1,
        1 / 256,
        32768
    ],
    float: [
        1,
        1,
        1,
        1
    ]
};
function unpackMapbox(r, g, b) {
    // unpacking formula for mapbox.terrain-rgb:
    // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb
    return (r * 256 * 256 + g * 256 + b) / 10 - 10000;
}
function unpackTerrarium(r, g, b) {
    // unpacking formula for mapzen terrarium:
    // https://aws.amazon.com/public-datasets/terrain/
    return r * 256 + g + b / 256 - 32768;
}
class DEMData {
    get tree() {
        if (!this._tree)
            this._buildQuadTree();
        return this._tree;
    }
    // RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride
    // and dim is calculated as stride - 2.
    constructor(uid, data, sourceEncoding, convertToFloat, borderReady = false) {
        this.uid = uid;
        if (data.height !== data.width)
            throw new RangeError('DEM tiles must be square');
        if (sourceEncoding && sourceEncoding !== 'mapbox' && sourceEncoding !== 'terrarium')
            return warnOnce(`"${ sourceEncoding }" is not a valid encoding type. Valid types include "mapbox" and "terrarium".`);
        this.stride = data.height;
        const dim = this.dim = data.height - 2;
        const values = new Uint32Array(data.data.buffer);
        this.pixels = new Uint8Array(data.data.buffer);
        this.encoding = sourceEncoding || 'mapbox';
        this.borderReady = borderReady;
        this._modifiedForSources = {};
        if (!borderReady) {
            // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image
            // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring
            // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder
            for (let x = 0; x < dim; x++) {
                // left vertical border
                values[this._idx(-1, x)] = values[this._idx(0, x)];
                // right vertical border
                values[this._idx(dim, x)] = values[this._idx(dim - 1, x)];
                // left horizontal border
                values[this._idx(x, -1)] = values[this._idx(x, 0)];
                // right horizontal border
                values[this._idx(x, dim)] = values[this._idx(x, dim - 1)];
            }
            // corners
            values[this._idx(-1, -1)] = values[this._idx(0, 0)];
            values[this._idx(dim, -1)] = values[this._idx(dim - 1, 0)];
            values[this._idx(-1, dim)] = values[this._idx(0, dim - 1)];
            values[this._idx(dim, dim)] = values[this._idx(dim - 1, dim - 1)];
        }
        if (convertToFloat) {
            const floatView = new Float32Array(data.data.buffer);
            const unpack = this.encoding === 'terrarium' ? unpackTerrarium : unpackMapbox;
            for (let i = 0; i < values.length; ++i) {
                const byteIdx = i * 4;
                floatView[i] = unpack(this.pixels[byteIdx], this.pixels[byteIdx + 1], this.pixels[byteIdx + 2]);
            }
            this.encoding = 'float';
        }
        this._timestamp = exported$1.now();
    }
    _buildQuadTree() {
        // Construct the implicit sparse quad tree by traversing mips from top to down
        this._tree = new DemMinMaxQuadTree(this);
    }
    get(x, y, clampToEdge = false) {
        if (clampToEdge) {
            x = clamp(x, -1, this.dim);
            y = clamp(y, -1, this.dim);
        }
        const idx = this._idx(x, y);
        if (this.encoding === 'float') {
            if (!this.floatView) {
                this.floatView = new Float32Array(this.pixels.buffer);
            }
            return this.floatView[idx];
        }
        const byteIndex = idx * 4;
        const unpack = this.encoding === 'terrarium' ? unpackTerrarium : unpackMapbox;
        return unpack(this.pixels[byteIndex], this.pixels[byteIndex + 1], this.pixels[byteIndex + 2]);
    }
    set(x, y, v) {
        const idx = this._idx(x, y);
        if (this.encoding === 'float') {
            if (!this.floatView) {
                this.floatView = new Float32Array(this.pixels.buffer);
            }
            const p = this.floatView[idx];
            this.floatView[idx] = v;
            return v - p;
        }
        const byteIndex = idx * 4;
        const unpack = this.encoding === 'terrarium' ? unpackTerrarium : unpackMapbox;
        const p = unpack(this.pixels[byteIndex], this.pixels[byteIndex + 1], this.pixels[byteIndex + 2]);
        const packed = DEMData.pack(v, this.encoding === 'terrarium' ? 'terrarium' : 'mapbox');
        this.pixels[byteIndex] = packed[0];
        this.pixels[byteIndex + 1] = packed[1];
        this.pixels[byteIndex + 2] = packed[2];
        return v - p;
    }
    static getUnpackVector(encoding) {
        return unpackVectors[encoding];
    }
    get unpackVector() {
        return unpackVectors[this.encoding];
    }
    _idx(x, y) {
        if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1)
            throw new RangeError('out of range source coordinates for DEM data');
        return (y + 1) * this.stride + (x + 1);
    }
    static pack(altitude, encoding) {
        const color = [
            0,
            0,
            0,
            0
        ];
        const vector = DEMData.getUnpackVector(encoding);
        let v = Math.floor((altitude + vector[3]) / vector[2]);
        color[2] = v % 256;
        v = Math.floor(v / 256);
        color[1] = v % 256;
        v = Math.floor(v / 256);
        color[0] = v;
        return color;
    }
    getPixels() {
        if (this.encoding === 'float') {
            return new Float32Image({
                width: this.stride,
                height: this.stride
            }, this.pixels);
        } else {
            return new RGBAImage({
                width: this.stride,
                height: this.stride
            }, this.pixels);
        }
    }
    backfillBorder(borderTile, dx, dy) {
        if (this.dim !== borderTile.dim)
            throw new Error('dem dimension mismatch');
        let xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim;
        switch (dx) {
        case -1:
            xMin = xMax - 1;
            break;
        case 1:
            xMax = xMin + 1;
            break;
        }
        switch (dy) {
        case -1:
            yMin = yMax - 1;
            break;
        case 1:
            yMax = yMin + 1;
            break;
        }
        const ox = -dx * this.dim;
        const oy = -dy * this.dim;
        for (let y = yMin; y < yMax; y++) {
            for (let x = xMin; x < xMax; x++) {
                const i = 4 * this._idx(x, y);
                const j = 4 * this._idx(x + ox, y + oy);
                this.pixels[i + 0] = borderTile.pixels[j + 0];
                this.pixels[i + 1] = borderTile.pixels[j + 1];
                this.pixels[i + 2] = borderTile.pixels[j + 2];
                this.pixels[i + 3] = borderTile.pixels[j + 3];
            }
        }
    }
    onDeserialize() {
        if (this._tree)
            this._tree.dem = this;
    }
}
register(DEMData, 'DEMData');
register(DemMinMaxQuadTree, 'DemMinMaxQuadTree', { omit: ['dem'] });

//      
/**
 * Options common to {@link Map#queryTerrainElevation} and {@link Map#unproject3d}, used to control how elevation
 * data is returned.
 *
 * @typedef {Object} ElevationQueryOptions
 * @property {boolean} exaggerated When set to `true` returns the value of the elevation with the terrains `exaggeration` on the style already applied,
 * when`false` it returns the raw value of the underlying data without styling applied.
 */
/**
 * Provides access to elevation data from raster-dem source cache.
 */
class Elevation {
    /**
     * Helper that checks whether DEM data is available at a given mercator coordinate.
     * @param {MercatorCoordinate} point Mercator coordinate of the point to check against.
     * @returns {boolean} `true` indicating whether the data is available at `point`, and `false` otherwise.
     */
    isDataAvailableAtPoint(point) {
        const sourceCache = this._source();
        if (this.isUsingMockSource() || !sourceCache || point.y < 0 || point.y > 1) {
            return false;
        }
        const cache = sourceCache;
        const z = cache.getSource().maxzoom;
        const tiles = 1 << z;
        const wrap = Math.floor(point.x);
        const px = point.x - wrap;
        const x = Math.floor(px * tiles);
        const y = Math.floor(point.y * tiles);
        const demTile = this.findDEMTileFor(new OverscaledTileID(z, wrap, z, x, y));
        return !!(demTile && demTile.dem);
    }
    /**
     * Helper around `getAtPoint` that guarantees that a numeric value is returned.
     * @param {MercatorCoordinate} point Mercator coordinate of the point.
     * @param {number} defaultIfNotLoaded Value that is returned if the dem tile of the provided point is not loaded.
     * @returns {number} Altitude in meters.
     */
    getAtPointOrZero(point, defaultIfNotLoaded = 0) {
        return this.getAtPoint(point, defaultIfNotLoaded) || 0;
    }
    /**
     * Altitude above sea level in meters at specified point.
     * @param {MercatorCoordinate} point Mercator coordinate of the point.
     * @param {number} defaultIfNotLoaded Value that is returned if the DEM tile of the provided point is not loaded.
     * @param {boolean} exaggerated `true` if styling exaggeration should be applied to the resulting elevation.
     * @returns {number} Altitude in meters.
     * If there is no loaded tile that carries information for the requested
     * point elevation, returns `defaultIfNotLoaded`.
     * Doesn't invoke network request to fetch the data.
     */
    getAtPoint(point, defaultIfNotLoaded, exaggerated = true) {
        if (this.isUsingMockSource()) {
            return null;
        }
        // Force a cast to null for both null and undefined
        if (defaultIfNotLoaded == null)
            defaultIfNotLoaded = null;
        const src = this._source();
        if (!src)
            return defaultIfNotLoaded;
        if (point.y < 0 || point.y > 1) {
            return defaultIfNotLoaded;
        }
        const cache = src;
        const z = cache.getSource().maxzoom;
        const tiles = 1 << z;
        const wrap = Math.floor(point.x);
        const px = point.x - wrap;
        const tileID = new OverscaledTileID(z, wrap, z, Math.floor(px * tiles), Math.floor(point.y * tiles));
        const demTile = this.findDEMTileFor(tileID);
        if (!(demTile && demTile.dem)) {
            return defaultIfNotLoaded;
        }
        const dem = demTile.dem;
        const tilesAtTileZoom = 1 << demTile.tileID.canonical.z;
        const x = (px * tilesAtTileZoom - demTile.tileID.canonical.x) * dem.dim;
        const y = (point.y * tilesAtTileZoom - demTile.tileID.canonical.y) * dem.dim;
        const i = Math.floor(x);
        const j = Math.floor(y);
        const exaggeration = exaggerated ? this.exaggeration() : 1;
        return exaggeration * number(number(dem.get(i, j), dem.get(i, j + 1), y - j), number(dem.get(i + 1, j), dem.get(i + 1, j + 1), y - j), x - i);
    }
    /*
     * x and y are offset within tile, in 0 .. EXTENT coordinate space.
     */
    getAtTileOffset(tileID, x, y) {
        const tilesAtTileZoom = 1 << tileID.canonical.z;
        return this.getAtPointOrZero(new MercatorCoordinate(tileID.wrap + (tileID.canonical.x + x / EXTENT) / tilesAtTileZoom, (tileID.canonical.y + y / EXTENT) / tilesAtTileZoom));
    }
    getAtTileOffsetFunc(tileID, lat, worldSize, projection) {
        return p => {
            const elevation = this.getAtTileOffset(tileID, p.x, p.y);
            const upVector = projection.upVector(tileID.canonical, p.x, p.y);
            const upVectorScale = projection.upVectorScale(tileID.canonical, lat, worldSize).metersToTile;
            // $FlowFixMe can't yet resolve tuple vs array incompatibilities
            vec3_1.scale(upVector, upVector, elevation * upVectorScale);
            return upVector;
        };
    }
    /*
     * Batch fetch for multiple tile points: points holds input and return value:
     * vec3's items on index 0 and 1 define x and y offset within tile, in [0 .. EXTENT]
     * range, respectively. vec3 item at index 2 is output value, in meters.
     * If a DEM tile that covers tileID is loaded, true is returned, otherwise false.
     * Nearest filter sampling on dem data is done (no interpolation).
     */
    getForTilePoints(tileID, points, interpolated, useDemTile) {
        if (this.isUsingMockSource()) {
            return false;
        }
        const helper = DEMSampler.create(this, tileID, useDemTile);
        if (!helper) {
            return false;
        }
        points.forEach(p => {
            p[2] = this.exaggeration() * helper.getElevationAt(p[0], p[1], interpolated);
        });
        return true;
    }
    /**
     * Get elevation minimum and maximum for tile identified by `tileID`.
     * @param {OverscaledTileID} tileID The `tileId` is a sub tile (or covers the same space) of the DEM tile we read the information from.
     * @returns {?{min: number, max: number}} The min and max elevation.
     */
    getMinMaxForTile(tileID) {
        if (this.isUsingMockSource()) {
            return null;
        }
        const demTile = this.findDEMTileFor(tileID);
        if (!(demTile && demTile.dem)) {
            return null;
        }
        const dem = demTile.dem;
        const tree = dem.tree;
        const demTileID = demTile.tileID;
        const scale = 1 << tileID.canonical.z - demTileID.canonical.z;
        let xOffset = tileID.canonical.x / scale - demTileID.canonical.x;
        let yOffset = tileID.canonical.y / scale - demTileID.canonical.y;
        let index = 0;
        // Start from DEM tree root.
        for (let i = 0; i < tileID.canonical.z - demTileID.canonical.z; i++) {
            if (tree.leaves[index])
                break;
            xOffset *= 2;
            yOffset *= 2;
            const childOffset = 2 * Math.floor(yOffset) + Math.floor(xOffset);
            index = tree.childOffsets[index] + childOffset;
            xOffset = xOffset % 1;
            yOffset = yOffset % 1;
        }
        return {
            min: this.exaggeration() * tree.minimums[index],
            max: this.exaggeration() * tree.maximums[index]
        };
    }
    /**
     * Get elevation minimum below MSL for the visible tiles. This function accounts
     * for terrain exaggeration and is conservative based on the maximum DEM error,
     * do not expect accurate values from this function.
     * If no negative elevation is visible, this function returns 0.
     * @returns {number} The min elevation below sea level of all visible tiles.
     */
    getMinElevationBelowMSL() {
        throw new Error('Pure virtual method called.');
    }
    /**
     * Performs raycast against visible DEM tiles on the screen and returns the distance travelled along the ray.
     * `x` & `y` components of the position are expected to be in normalized mercator coordinates [0, 1] and z in meters.
     * @param {vec3} position The ray origin.
     * @param {vec3} dir The ray direction.
     * @param {number} exaggeration The terrain exaggeration.
    */
    raycast(position, dir, exaggeration) {
        throw new Error('Pure virtual method called.');
    }
    /**
     * Given a point on screen, returns 3D MercatorCoordinate on terrain.
     * Helper function that wraps `raycast`.
     *
     * @param {Point} screenPoint Screen point in pixels in top-left origin coordinate system.
     * @returns {vec3} If there is intersection with terrain, returns 3D MercatorCoordinate's of
     * intersection, as vec3(x, y, z), otherwise null.
     */
    /* eslint no-unused-vars: ["error", { "args": "none" }] */
    pointCoordinate(screenPoint) {
        throw new Error('Pure virtual method called.');
    }
    /*
     * Implementation provides SourceCache of raster-dem source type cache, in
     * order to access already loaded cached tiles.
     */
    _source() {
        throw new Error('Pure virtual method called.');
    }
    /*
     * Whether the SourceCache instance is a mock source cache.
     * This mock source cache is used solely for the Globe projection and with terrain disabled,
     * where we only want to leverage the draping rendering pipeline without incurring DEM-tile
     * download overhead. This function is useful to skip DEM processing as the mock data source
     * placeholder contains only 0 height.
     */
    isUsingMockSource() {
        throw new Error('Pure virtual method called.');
    }
    /*
     * A multiplier defined by style as terrain exaggeration. Elevation provided
     * by getXXXX methods is multiplied by this.
     */
    exaggeration() {
        throw new Error('Pure virtual method called.');
    }
    /**
     * Lookup DEM tile that corresponds to (covers) tileID.
     * @private
     */
    findDEMTileFor(_) {
        throw new Error('Pure virtual method called.');
    }
    /**
     * Get list of DEM tiles used to render current frame.
     * @private
     */
    get visibleDemTiles() {
        throw new Error('Getter must be implemented in subclass.');
    }
}
/**
 * Helper class computes and caches data required to lookup elevation offsets at the tile level.
 */
class DEMSampler {
    constructor(demTile, scale, offset) {
        this._demTile = demTile;
        // demTile.dem will always exist because the factory method `create` does the check
        // Make flow happy with a cast through any
        this._dem = this._demTile.dem;
        this._scale = scale;
        this._offset = offset;
    }
    static create(elevation, tileID, useDemTile) {
        const demTile = useDemTile || elevation.findDEMTileFor(tileID);
        if (!(demTile && demTile.dem)) {
            return;
        }
        const dem = demTile.dem;
        const demTileID = demTile.tileID;
        const scale = 1 << tileID.canonical.z - demTileID.canonical.z;
        const xOffset = (tileID.canonical.x / scale - demTileID.canonical.x) * dem.dim;
        const yOffset = (tileID.canonical.y / scale - demTileID.canonical.y) * dem.dim;
        const k = dem.dim / EXTENT / scale;
        return new DEMSampler(demTile, k, [
            xOffset,
            yOffset
        ]);
    }
    tileCoordToPixel(x, y) {
        const px = x * this._scale + this._offset[0];
        const py = y * this._scale + this._offset[1];
        const i = Math.floor(px);
        const j = Math.floor(py);
        return new Point$2(i, j);
    }
    getElevationAt(x, y, interpolated, clampToEdge) {
        const px = x * this._scale + this._offset[0];
        const py = y * this._scale + this._offset[1];
        const i = Math.floor(px);
        const j = Math.floor(py);
        const dem = this._dem;
        clampToEdge = !!clampToEdge;
        return interpolated ? number(number(dem.get(i, j, clampToEdge), dem.get(i, j + 1, clampToEdge), py - j), number(dem.get(i + 1, j, clampToEdge), dem.get(i + 1, j + 1, clampToEdge), py - j), px - i) : dem.get(i, j, clampToEdge);
    }
    getElevationAtPixel(x, y, clampToEdge) {
        return this._dem.get(x, y, !!clampToEdge);
    }
    getMeterToDEM(lat) {
        return (1 << this._demTile.tileID.canonical.z) * mercatorZfromAltitude(1, lat) * this._dem.stride;
    }
}

//      
class FeatureIndex {
    constructor(tileID, promoteId) {
        this.tileID = tileID;
        this.x = tileID.canonical.x;
        this.y = tileID.canonical.y;
        this.z = tileID.canonical.z;
        this.grid = new Grid(EXTENT, 16, 0);
        this.featureIndexArray = new FeatureIndexArray();
        this.promoteId = promoteId;
    }
    insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, layoutVertexArrayOffset = 0) {
        const key = this.featureIndexArray.length;
        this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex, layoutVertexArrayOffset);
        const grid = this.grid;
        for (let r = 0; r < geometry.length; r++) {
            const ring = geometry[r];
            const bbox = [
                Infinity,
                Infinity,
                -Infinity,
                -Infinity
            ];
            for (let i = 0; i < ring.length; i++) {
                const p = ring[i];
                bbox[0] = Math.min(bbox[0], p.x);
                bbox[1] = Math.min(bbox[1], p.y);
                bbox[2] = Math.max(bbox[2], p.x);
                bbox[3] = Math.max(bbox[3], p.y);
            }
            if (bbox[0] < EXTENT && bbox[1] < EXTENT && bbox[2] >= 0 && bbox[3] >= 0) {
                grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);
            }
        }
    }
    loadVTLayers() {
        if (!this.vtLayers) {
            this.vtLayers = new VectorTile(new Protobuf(this.rawTileData)).layers;
            this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']);
            this.vtFeatures = {};
            for (const layer in this.vtLayers) {
                this.vtFeatures[layer] = [];
            }
        }
        return this.vtLayers;
    }
    // Finds non-symbol features in this tile at a particular position.
    query(args, styleLayers, serializedLayers, sourceFeatureState) {
        this.loadVTLayers();
        const params = args.params || {}, filter = createFilter(params.filter);
        const tilespaceGeometry = args.tileResult;
        const transform = args.transform;
        const bounds = tilespaceGeometry.bufferedTilespaceBounds;
        const queryPredicate = (bx1, by1, bx2, by2) => {
            return polygonIntersectsBox(tilespaceGeometry.bufferedTilespaceGeometry, bx1, by1, bx2, by2);
        };
        const matching = this.grid.query(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y, queryPredicate);
        matching.sort(topDownFeatureComparator);
        let elevationHelper = null;
        if (transform.elevation && matching.length > 0) {
            elevationHelper = DEMSampler.create(transform.elevation, this.tileID);
        }
        const result = {};
        let previousIndex;
        for (let k = 0; k < matching.length; k++) {
            const index = matching[k];
            // don't check the same feature more than once
            if (index === previousIndex)
                continue;
            previousIndex = index;
            const match = this.featureIndexArray.get(index);
            let featureGeometry = null;
            this.loadMatchingFeature(result, match, filter, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, (feature, styleLayer, featureState, layoutVertexArrayOffset = 0) => {
                if (!featureGeometry) {
                    featureGeometry = loadGeometry(feature, this.tileID.canonical, args.tileTransform);
                }
                return styleLayer.queryIntersectsFeature(tilespaceGeometry, feature, featureState, featureGeometry, this.z, args.transform, args.pixelPosMatrix, elevationHelper, layoutVertexArrayOffset);
            });
        }
        return result;
    }
    loadMatchingFeature(result, featureIndexData, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) {
        const {featureIndex, bucketIndex, sourceLayerIndex, layoutVertexArrayOffset} = featureIndexData;
        const layerIDs = this.bucketLayerIDs[bucketIndex];
        if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs))
            return;
        const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);
        const sourceLayer = this.vtLayers[sourceLayerName];
        const feature = sourceLayer.feature(featureIndex);
        if (filter.needGeometry) {
            const evaluationFeature = toEvaluationFeature(feature, true);
            // $FlowFixMe[method-unbinding]
            if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {
                return;
            }    // $FlowFixMe[method-unbinding]
        } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
            return;
        }
        const id = this.getId(feature, sourceLayerName);
        for (let l = 0; l < layerIDs.length; l++) {
            const layerID = layerIDs[l];
            if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) {
                continue;
            }
            const styleLayer = styleLayers[layerID];
            if (!styleLayer)
                continue;
            let featureState = {};
            if (id !== undefined && sourceFeatureState) {
                // `feature-state` expression evaluation requires feature state to be available
                featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id);
            }
            const serializedLayer = extend$1({}, serializedLayers[layerID]);
            serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages);
            serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages);
            const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState, layoutVertexArrayOffset);
            if (!intersectionZ) {
                // Only applied for non-symbol features
                continue;
            }
            const geojsonFeature = new Feature(feature, this.z, this.x, this.y, id);
            geojsonFeature.layer = serializedLayer;
            let layerResult = result[layerID];
            if (layerResult === undefined) {
                layerResult = result[layerID] = [];
            }
            layerResult.push({
                featureIndex,
                feature: geojsonFeature,
                intersectionZ
            });
        }
    }
    // Given a set of symbol indexes that have already been looked up,
    // return a matching set of GeoJSONFeatures
    lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterSpec, filterLayerIDs, availableImages, styleLayers) {
        const result = {};
        this.loadVTLayers();
        const filter = createFilter(filterSpec);
        for (const symbolFeatureIndex of symbolFeatureIndexes) {
            this.loadMatchingFeature(result, {
                bucketIndex,
                sourceLayerIndex,
                featureIndex: symbolFeatureIndex,
                layoutVertexArrayOffset: 0
            }, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers);
        }
        return result;
    }
    loadFeature(featureIndexData) {
        const {featureIndex, sourceLayerIndex} = featureIndexData;
        this.loadVTLayers();
        const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);
        const featureCache = this.vtFeatures[sourceLayerName];
        if (featureCache[featureIndex]) {
            return featureCache[featureIndex];
        }
        const sourceLayer = this.vtLayers[sourceLayerName];
        const feature = sourceLayer.feature(featureIndex);
        featureCache[featureIndex] = feature;
        return feature;
    }
    hasLayer(id) {
        for (const layerIDs of this.bucketLayerIDs) {
            for (const layerID of layerIDs) {
                if (id === layerID)
                    return true;
            }
        }
        return false;
    }
    getId(feature, sourceLayerId) {
        let id = feature.id;
        if (this.promoteId) {
            const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId];
            // $FlowFixMe[incompatible-type] - Flow can't narrow the id type from IVectorTileFeature.id
            if (propName != null)
                id = feature.properties[propName];
            if (typeof id === 'boolean')
                id = Number(id);
        }
        return id;
    }
}
register(FeatureIndex, 'FeatureIndex', {
    omit: [
        'rawTileData',
        'sourceLayerCoder'
    ]
});
function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) {
    return mapObject(serializedProperties, (property, key) => {
        const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null;
        return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop;
    });
}
function topDownFeatureComparator(a, b) {
    return b - a;
}

//      
const symbolLayoutAttributes = createLayout([
    {
        name: 'a_pos_offset',
        components: 4,
        type: 'Int16'
    },
    {
        name: 'a_tex_size',
        components: 4,
        type: 'Uint16'
    },
    {
        name: 'a_pixeloffset',
        components: 4,
        type: 'Int16'
    }
], 4);
const symbolGlobeExtAttributes = createLayout([
    {
        name: 'a_globe_anchor',
        components: 3,
        type: 'Int16'
    },
    {
        name: 'a_globe_normal',
        components: 3,
        type: 'Float32'
    }
], 4);
const dynamicLayoutAttributes = createLayout([{
        name: 'a_projected_pos',
        components: 4,
        type: 'Float32'
    }], 4);
createLayout([{
        name: 'a_fade_opacity',
        components: 1,
        type: 'Uint32'
    }], 4);
const zOffsetAttributes = createLayout([{
        name: 'a_z_offset',
        components: 1,
        type: 'Float32'
    }], 4);
const iconTransitioningAttributes = createLayout([{
        name: 'a_texb',
        components: 2,
        type: 'Uint16'
    }]);
const collisionVertexAttributes = createLayout([
    {
        name: 'a_placed',
        components: 2,
        type: 'Uint8'
    },
    {
        name: 'a_shift',
        components: 2,
        type: 'Float32'
    }
]);
const collisionVertexAttributesExt = createLayout([
    {
        name: 'a_size_scale',
        components: 1,
        type: 'Float32'
    },
    {
        name: 'a_padding',
        components: 2,
        type: 'Float32'
    }
]);
createLayout([
    // the box is centered around the anchor point
    {
        type: 'Int16',
        name: 'projectedAnchorX'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorY'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorZ'
    },
    {
        type: 'Int16',
        name: 'tileAnchorX'
    },
    {
        type: 'Int16',
        name: 'tileAnchorY'
    },
    // distances to the edges from the anchor
    {
        type: 'Float32',
        name: 'x1'
    },
    {
        type: 'Float32',
        name: 'y1'
    },
    {
        type: 'Float32',
        name: 'x2'
    },
    {
        type: 'Float32',
        name: 'y2'
    },
    {
        type: 'Int16',
        name: 'padding'
    },
    // the index of the feature in the original vectortile
    {
        type: 'Uint32',
        name: 'featureIndex'
    },
    // the source layer the feature appears in
    {
        type: 'Uint16',
        name: 'sourceLayerIndex'
    },
    // the bucket the feature appears in
    {
        type: 'Uint16',
        name: 'bucketIndex'
    }
]);
const collisionBoxLayout = createLayout([
    // used to render collision boxes for debugging purposes
    {
        name: 'a_pos',
        components: 3,
        type: 'Int16'
    },
    {
        name: 'a_anchor_pos',
        components: 2,
        type: 'Int16'
    },
    {
        name: 'a_extrude',
        components: 2,
        type: 'Int16'
    }
], 4);
const collisionCircleLayout = createLayout([
    // used to render collision circles for debugging purposes
    {
        name: 'a_pos_2f',
        components: 2,
        type: 'Float32'
    },
    {
        name: 'a_radius',
        components: 1,
        type: 'Float32'
    },
    {
        name: 'a_flags',
        components: 2,
        type: 'Int16'
    }
], 4);
createLayout([{
        name: 'triangle',
        components: 3,
        type: 'Uint16'
    }]);
createLayout([
    {
        type: 'Int16',
        name: 'projectedAnchorX'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorY'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorZ'
    },
    {
        type: 'Float32',
        name: 'tileAnchorX'
    },
    {
        type: 'Float32',
        name: 'tileAnchorY'
    },
    {
        type: 'Uint16',
        name: 'glyphStartIndex'
    },
    {
        type: 'Uint16',
        name: 'numGlyphs'
    },
    {
        type: 'Uint32',
        name: 'vertexStartIndex'
    },
    {
        type: 'Uint32',
        name: 'lineStartIndex'
    },
    {
        type: 'Uint32',
        name: 'lineLength'
    },
    {
        type: 'Uint16',
        name: 'segment'
    },
    {
        type: 'Uint16',
        name: 'lowerSize'
    },
    {
        type: 'Uint16',
        name: 'upperSize'
    },
    {
        type: 'Float32',
        name: 'lineOffsetX'
    },
    {
        type: 'Float32',
        name: 'lineOffsetY'
    },
    {
        type: 'Uint8',
        name: 'writingMode'
    },
    {
        type: 'Uint8',
        name: 'placedOrientation'
    },
    {
        type: 'Uint8',
        name: 'hidden'
    },
    {
        type: 'Uint32',
        name: 'crossTileID'
    },
    {
        type: 'Int16',
        name: 'associatedIconIndex'
    },
    {
        type: 'Uint8',
        name: 'flipState'
    }
]);
createLayout([
    {
        type: 'Float32',
        name: 'tileAnchorX'
    },
    {
        type: 'Float32',
        name: 'tileAnchorY'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorX'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorY'
    },
    {
        type: 'Int16',
        name: 'projectedAnchorZ'
    },
    {
        type: 'Int16',
        name: 'rightJustifiedTextSymbolIndex'
    },
    {
        type: 'Int16',
        name: 'centerJustifiedTextSymbolIndex'
    },
    {
        type: 'Int16',
        name: 'leftJustifiedTextSymbolIndex'
    },
    {
        type: 'Int16',
        name: 'verticalPlacedTextSymbolIndex'
    },
    {
        type: 'Int16',
        name: 'placedIconSymbolIndex'
    },
    {
        type: 'Int16',
        name: 'verticalPlacedIconSymbolIndex'
    },
    {
        type: 'Uint16',
        name: 'key'
    },
    {
        type: 'Uint16',
        name: 'textBoxStartIndex'
    },
    {
        type: 'Uint16',
        name: 'textBoxEndIndex'
    },
    {
        type: 'Uint16',
        name: 'verticalTextBoxStartIndex'
    },
    {
        type: 'Uint16',
        name: 'verticalTextBoxEndIndex'
    },
    {
        type: 'Uint16',
        name: 'iconBoxStartIndex'
    },
    {
        type: 'Uint16',
        name: 'iconBoxEndIndex'
    },
    {
        type: 'Uint16',
        name: 'verticalIconBoxStartIndex'
    },
    {
        type: 'Uint16',
        name: 'verticalIconBoxEndIndex'
    },
    {
        type: 'Uint16',
        name: 'featureIndex'
    },
    {
        type: 'Uint16',
        name: 'numHorizontalGlyphVertices'
    },
    {
        type: 'Uint16',
        name: 'numVerticalGlyphVertices'
    },
    {
        type: 'Uint16',
        name: 'numIconVertices'
    },
    {
        type: 'Uint16',
        name: 'numVerticalIconVertices'
    },
    {
        type: 'Uint16',
        name: 'useRuntimeCollisionCircles'
    },
    {
        type: 'Uint32',
        name: 'crossTileID'
    },
    {
        type: 'Float32',
        components: 2,
        name: 'textOffset'
    },
    {
        type: 'Float32',
        name: 'collisionCircleDiameter'
    },
    {
        type: 'Float32',
        name: 'zOffset'
    },
    {
        type: 'Uint8',
        name: 'hasIconTextFit'
    }
]);
createLayout([{
        type: 'Float32',
        name: 'offsetX'
    }]);
createLayout([
    {
        type: 'Int16',
        name: 'x'
    },
    {
        type: 'Int16',
        name: 'y'
    }
]);

//      
// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout
var ONE_EM = 24;

//      
const SIZE_PACK_FACTOR = 128;
// For {text,icon}-size, get the bucket-level data that will be needed by
// the painter to set symbol-size-related uniforms
function getSizeData(tileZoom, value) {
    const {expression} = value;
    if (expression.kind === 'constant') {
        // $FlowFixMe[method-unbinding]
        const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1));
        return {
            kind: 'constant',
            layoutSize
        };
    } else if (expression.kind === 'source') {
        return { kind: 'source' };
    } else {
        const {zoomStops, interpolationType} = expression;
        // calculate covering zoom stops for zoom-dependent values
        let lower = 0;
        while (lower < zoomStops.length && zoomStops[lower] <= tileZoom)
            lower++;
        lower = Math.max(0, lower - 1);
        let upper = lower;
        while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1)
            upper++;
        upper = Math.min(zoomStops.length - 1, upper);
        const minZoom = zoomStops[lower];
        const maxZoom = zoomStops[upper];
        // We'd like to be able to use CameraExpression or CompositeExpression in these
        // return types rather than ExpressionSpecification, but the former are not
        // transferrable across Web Worker boundaries.
        if (expression.kind === 'composite') {
            return {
                kind: 'composite',
                minZoom,
                maxZoom,
                interpolationType
            };
        }
        // for camera functions, also save off the function values
        // evaluated at the covering zoom levels
        // $FlowFixMe[method-unbinding]
        const minSize = expression.evaluate(new EvaluationParameters(minZoom));
        // $FlowFixMe[method-unbinding]
        const maxSize = expression.evaluate(new EvaluationParameters(maxZoom));
        return {
            kind: 'camera',
            minZoom,
            maxZoom,
            minSize,
            maxSize,
            interpolationType
        };
    }
}
function evaluateSizeForFeature(sizeData, {uSize, uSizeT}, {lowerSize, upperSize}) {
    if (sizeData.kind === 'source') {
        return lowerSize / SIZE_PACK_FACTOR;
    } else if (sizeData.kind === 'composite') {
        return number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT);
    }
    return uSize;
}
function evaluateSizeForZoom(sizeData, zoom) {
    let uSizeT = 0;
    let uSize = 0;
    if (sizeData.kind === 'constant') {
        uSize = sizeData.layoutSize;
    } else if (sizeData.kind !== 'source') {
        const {interpolationType, minZoom, maxZoom} = sizeData;
        // Even though we could get the exact value of the camera function
        // at z = tr.zoom, we intentionally do not: instead, we interpolate
        // between the camera function values at a pair of zoom stops covering
        // [tileZoom, tileZoom + 1] in order to be consistent with this
        // restriction on composite functions
        const t = !interpolationType ? 0 : clamp(Interpolate$1.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);
        if (sizeData.kind === 'camera') {
            uSize = number(sizeData.minSize, sizeData.maxSize, t);
        } else {
            uSizeT = t;
        }
    }
    return {
        uSizeT,
        uSize
    };
}

var symbolSize = /*#__PURE__*/Object.freeze({
__proto__: null,
SIZE_PACK_FACTOR: SIZE_PACK_FACTOR,
evaluateSizeForFeature: evaluateSizeForFeature,
evaluateSizeForZoom: evaluateSizeForZoom,
getSizeData: getSizeData
});

//      
function transformText(text, layer, feature) {
    const transform = layer.layout.get('text-transform').evaluate(feature, {});
    if (transform === 'uppercase') {
        text = text.toLocaleUpperCase();
    } else if (transform === 'lowercase') {
        text = text.toLocaleLowerCase();
    }
    if (plugin.applyArabicShaping) {
        text = plugin.applyArabicShaping(text);
    }
    return text;
}
function transformText$1 (text, layer, feature) {
    text.sections.forEach(section => {
        section.text = transformText(section.text, layer, feature);
    });
    return text;
}

//      
function mergeLines (features) {
    const leftIndex = {};
    const rightIndex = {};
    const mergedFeatures = [];
    let mergedIndex = 0;
    function add(k) {
        mergedFeatures.push(features[k]);
        mergedIndex++;
    }
    function mergeFromRight(leftKey, rightKey, geom) {
        const i = rightIndex[leftKey];
        delete rightIndex[leftKey];
        rightIndex[rightKey] = i;
        mergedFeatures[i].geometry[0].pop();
        mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]);
        return i;
    }
    function mergeFromLeft(leftKey, rightKey, geom) {
        const i = leftIndex[rightKey];
        delete leftIndex[rightKey];
        leftIndex[leftKey] = i;
        mergedFeatures[i].geometry[0].shift();
        mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]);
        return i;
    }
    function getKey(text, geom, onRight) {
        const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0];
        return `${ text }:${ point.x }:${ point.y }`;
    }
    for (let k = 0; k < features.length; k++) {
        const feature = features[k];
        const geom = feature.geometry;
        const text = feature.text ? feature.text.toString() : null;
        if (!text) {
            add(k);
            continue;
        }
        const leftKey = getKey(text, geom), rightKey = getKey(text, geom, true);
        if (leftKey in rightIndex && rightKey in leftIndex && rightIndex[leftKey] !== leftIndex[rightKey]) {
            // found lines with the same text adjacent to both ends of the current line, merge all three
            const j = mergeFromLeft(leftKey, rightKey, geom);
            const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry);
            delete leftIndex[leftKey];
            delete rightIndex[rightKey];
            rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i;
            mergedFeatures[j].geometry = null;
        } else if (leftKey in rightIndex) {
            // found mergeable line adjacent to the start of the current line, merge
            mergeFromRight(leftKey, rightKey, geom);
        } else if (rightKey in leftIndex) {
            // found mergeable line adjacent to the end of the current line, merge
            mergeFromLeft(leftKey, rightKey, geom);
        } else {
            // no adjacent lines, add as a new item
            add(k);
            leftIndex[leftKey] = mergedIndex - 1;
            rightIndex[rightKey] = mergedIndex - 1;
        }
    }
    return mergedFeatures.filter(f => f.geometry);
}

//      
const verticalizedCharacterMap = {
    '!': '\uFE15',
    '#': '\uFF03',
    '$': '\uFF04',
    '%': '\uFF05',
    '&': '\uFF06',
    '(': '\uFE35',
    ')': '\uFE36',
    '*': '\uFF0A',
    '+': '\uFF0B',
    ',': '\uFE10',
    '-': '\uFE32',
    '.': '\u30FB',
    '/': '\uFF0F',
    ':': '\uFE13',
    ';': '\uFE14',
    '<': '\uFE3F',
    '=': '\uFF1D',
    '>': '\uFE40',
    '?': '\uFE16',
    '@': '\uFF20',
    '[': '\uFE47',
    '\\': '\uFF3C',
    ']': '\uFE48',
    '^': '\uFF3E',
    '_': '︳',
    '`': '\uFF40',
    '{': '\uFE37',
    '|': '\u2015',
    '}': '\uFE38',
    '~': '\uFF5E',
    '\xA2': '\uFFE0',
    '\xA3': '\uFFE1',
    '\xA5': '\uFFE5',
    '\xA6': '\uFFE4',
    '\xAC': '\uFFE2',
    '\xAF': '\uFFE3',
    '\u2013': '\uFE32',
    '\u2014': '\uFE31',
    '\u2018': '\uFE43',
    '\u2019': '\uFE44',
    '\u201C': '\uFE41',
    '\u201D': '\uFE42',
    '\u2026': '\uFE19',
    '\u2027': '\u30FB',
    '\u20A9': '\uFFE6',
    '\u3001': '\uFE11',
    '\u3002': '\uFE12',
    '\u3008': '\uFE3F',
    '\u3009': '\uFE40',
    '\u300A': '\uFE3D',
    '\u300B': '\uFE3E',
    '\u300C': '\uFE41',
    '\u300D': '\uFE42',
    '\u300E': '\uFE43',
    '\u300F': '\uFE44',
    '\u3010': '\uFE3B',
    '\u3011': '\uFE3C',
    '\u3014': '\uFE39',
    '\u3015': '\uFE3A',
    '\u3016': '\uFE17',
    '\u3017': '\uFE18',
    '\uFF01': '\uFE15',
    '\uFF08': '\uFE35',
    '\uFF09': '\uFE36',
    '\uFF0C': '\uFE10',
    '\uFF0D': '\uFE32',
    '\uFF0E': '\u30FB',
    '\uFF1A': '\uFE13',
    '\uFF1B': '\uFE14',
    '\uFF1C': '\uFE3F',
    '\uFF1E': '\uFE40',
    '\uFF1F': '\uFE16',
    '\uFF3B': '\uFE47',
    '\uFF3D': '\uFE48',
    '＿': '︳',
    '\uFF5B': '\uFE37',
    '\uFF5C': '\u2015',
    '\uFF5D': '\uFE38',
    '\uFF5F': '\uFE35',
    '\uFF60': '\uFE36',
    '\uFF61': '\uFE12',
    '\uFF62': '\uFE41',
    '\uFF63': '\uFE42',
    '\u2190': '\u2191',
    '\u2192': '\u2193'
};
function verticalizePunctuation(input, skipContextChecking) {
    let output = '';
    for (let i = 0; i < input.length; i++) {
        const nextCharCode = input.charCodeAt(i + 1) || null;
        const prevCharCode = input.charCodeAt(i - 1) || null;
        const canReplacePunctuation = skipContextChecking || (!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]]);
        if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) {
            output += verticalizedCharacterMap[input[i]];
        } else {
            output += input[i];
        }
    }
    return output;
}
function isVerticalClosePunctuation(chr) {
    return chr === '\uFE36' || chr === '\uFE48' || chr === '\uFE38' || chr === '\uFE44' || chr === '\uFE42' || chr === '\uFE3E' || chr === '\uFE3C' || chr === '\uFE3A' || chr === '\uFE18' || chr === '\uFE40' || chr === '\uFE10' || chr === '\uFE13' || chr === '\uFE14' || chr === '\uFF40' || chr === '\uFFE3' || chr === '\uFE11' || chr === '\uFE12';
}
function isVerticalOpenPunctuation(chr) {
    return chr === '\uFE35' || chr === '\uFE47' || chr === '\uFE37' || chr === '\uFE43' || chr === '\uFE41' || chr === '\uFE3D' || chr === '\uFE3B' || chr === '\uFE39' || chr === '\uFE17' || chr === '\uFE3F';
}

//      
const border$1 = 3;
function readFontstacks(tag, glyphData, pbf) {
    glyphData.glyphs = [];
    if (tag === 1) {
        pbf.readMessage(readFontstack, glyphData);
    }
}
function readFontstack(tag, glyphData, pbf) {
    if (tag === 3) {
        const {id, bitmap, width, height, left, top, advance} = pbf.readMessage(readGlyph, {});
        glyphData.glyphs.push({
            id,
            bitmap: new AlphaImage({
                width: width + 2 * border$1,
                height: height + 2 * border$1
            }, bitmap),
            metrics: {
                width,
                height,
                left,
                top,
                advance
            }
        });
    } else if (tag === 4) {
        glyphData.ascender = pbf.readSVarint();
    } else if (tag === 5) {
        glyphData.descender = pbf.readSVarint();
    }
}
function readGlyph(tag, glyph, pbf) {
    if (tag === 1)
        glyph.id = pbf.readVarint();
    else if (tag === 2)
        glyph.bitmap = pbf.readBytes();
    else if (tag === 3)
        glyph.width = pbf.readVarint();
    else if (tag === 4)
        glyph.height = pbf.readVarint();
    else if (tag === 5)
        glyph.left = pbf.readSVarint();
    else if (tag === 6)
        glyph.top = pbf.readSVarint();
    else if (tag === 7)
        glyph.advance = pbf.readVarint();
}
function parseGlyphPBF (data) {
    return new Protobuf(data).readFields(readFontstacks, {});
}
const GLYPH_PBF_BORDER = border$1;

function potpack(boxes) {
    // calculate total box area and maximum box width
    let area = 0;
    let maxWidth = 0;
    for (const box of boxes) {
        area += box.w * box.h;
        maxWidth = Math.max(maxWidth, box.w);
    }
    // sort the boxes for insertion by height, descending
    boxes.sort((a, b) => b.h - a.h);
    // aim for a squarish resulting container,
    // slightly adjusted for sub-100% space utilization
    const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth);
    // start with a single empty space, unbounded at the bottom
    const spaces = [{
            x: 0,
            y: 0,
            w: startWidth,
            h: Infinity
        }];
    let width = 0;
    let height = 0;
    for (const box of boxes) {
        // look through spaces backwards so that we check smaller spaces first
        for (let i = spaces.length - 1; i >= 0; i--) {
            const space = spaces[i];
            // look for empty spaces that can accommodate the current box
            if (box.w > space.w || box.h > space.h)
                continue;
            // found the space; add the box to its top-left corner
            // |-------|-------|
            // |  box  |       |
            // |_______|       |
            // |         space |
            // |_______________|
            box.x = space.x;
            box.y = space.y;
            height = Math.max(height, box.y + box.h);
            width = Math.max(width, box.x + box.w);
            if (box.w === space.w && box.h === space.h) {
                // space matches the box exactly; remove it
                const last = spaces.pop();
                if (i < spaces.length)
                    spaces[i] = last;
            } else if (box.h === space.h) {
                // space matches the box height; update it accordingly
                // |-------|---------------|
                // |  box  | updated space |
                // |_______|_______________|
                space.x += box.w;
                space.w -= box.w;
            } else if (box.w === space.w) {
                // space matches the box width; update it accordingly
                // |---------------|
                // |      box      |
                // |_______________|
                // | updated space |
                // |_______________|
                space.y += box.h;
                space.h -= box.h;
            } else {
                // otherwise the box splits the space into two spaces
                // |-------|-----------|
                // |  box  | new space |
                // |_______|___________|
                // | updated space     |
                // |___________________|
                spaces.push({
                    x: space.x + box.w,
                    y: space.y,
                    w: space.w - box.w,
                    h: box.h
                });
                space.y += box.h;
                space.h -= box.h;
            }
            break;
        }
    }
    return {
        w: width,
        // container width
        h: height,
        // container height
        fill: area / (width * height) || 0    // space utilization
    };
}

//      
const IMAGE_PADDING = 1;
class ImagePosition {
    constructor(paddedRect, {pixelRatio, version, stretchX, stretchY, content}) {
        this.paddedRect = paddedRect;
        this.pixelRatio = pixelRatio;
        this.stretchX = stretchX;
        this.stretchY = stretchY;
        this.content = content;
        this.version = version;
    }
    get tl() {
        return [
            this.paddedRect.x + IMAGE_PADDING,
            this.paddedRect.y + IMAGE_PADDING
        ];
    }
    get br() {
        return [
            this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING,
            this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING
        ];
    }
    get displaySize() {
        return [
            (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio,
            (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio
        ];
    }
}
class ImageAtlas {
    constructor(icons, patterns) {
        const iconPositions = {}, patternPositions = {};
        this.haveRenderCallbacks = [];
        const bins = [];
        this.addImages(icons, iconPositions, bins);
        this.addImages(patterns, patternPositions, bins);
        const {w, h} = potpack(bins);
        const image = new RGBAImage({
            width: w || 1,
            height: h || 1
        });
        for (const id in icons) {
            const src = icons[id];
            const bin = iconPositions[id].paddedRect;
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x: bin.x + IMAGE_PADDING,
                y: bin.y + IMAGE_PADDING
            }, src.data);
        }
        for (const id in patterns) {
            const src = patterns[id];
            const bin = patternPositions[id].paddedRect;
            const x = bin.x + IMAGE_PADDING, y = bin.y + IMAGE_PADDING, w = src.data.width, h = src.data.height;
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x,
                y
            }, src.data);
            // Add 1 pixel wrapped padding on each side of the image.
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: h - 1
            }, {
                x,
                y: y - 1
            }, {
                width: w,
                height: 1
            });
            // T
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x,
                y: y + h
            }, {
                width: w,
                height: 1
            });
            // B
            RGBAImage.copy(src.data, image, {
                x: w - 1,
                y: 0
            }, {
                x: x - 1,
                y
            }, {
                width: 1,
                height: h
            });
            // L
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x: x + w,
                y
            }, {
                width: 1,
                height: h
            });    // R
        }
        this.image = image;
        this.iconPositions = iconPositions;
        this.patternPositions = patternPositions;
    }
    addImages(images, positions, bins) {
        for (const id in images) {
            const src = images[id];
            const bin = {
                x: 0,
                y: 0,
                w: src.data.width + 2 * IMAGE_PADDING,
                h: src.data.height + 2 * IMAGE_PADDING
            };
            bins.push(bin);
            positions[id] = new ImagePosition(bin, src);
            if (src.hasRenderCallback) {
                this.haveRenderCallbacks.push(id);
            }
        }
    }
    patchUpdatedImages(imageManager, texture, scope) {
        this.haveRenderCallbacks = this.haveRenderCallbacks.filter(id => imageManager.hasImage(id, scope));
        imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks, scope);
        for (const name in imageManager.getUpdatedImages(scope)) {
            this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name, scope), texture);
            this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name, scope), texture);
        }
    }
    patchUpdatedImage(position, image, texture) {
        if (!position || !image)
            return;
        if (position.version === image.version)
            return;
        position.version = image.version;
        const [x, y] = position.tl;
        texture.update(image.data, undefined, {
            x,
            y
        });
    }
}
register(ImagePosition, 'ImagePosition');
register(ImageAtlas, 'ImageAtlas');

const WritingMode = {
    horizontal: 1,
    vertical: 2,
    horizontalOnly: 3
};
const SHAPING_DEFAULT_OFFSET = -17;
// The position of a glyph relative to the text's anchor point.
// A collection of positioned glyphs and some metadata
function isEmpty(positionedLines) {
    for (const line of positionedLines) {
        if (line.positionedGlyphs.length !== 0) {
            return false;
        }
    }
    return true;
}
// Max number of images in label is 6401 U+E000–U+F8FF that covers
// Basic Multilingual Plane Unicode Private Use Area (PUA).
const PUAbegin = 57344;
const PUAend = 63743;
class SectionOptions {
    // Text options
    // Image options
    constructor() {
        this.scale = 1;
        this.fontStack = '';
        this.imageName = null;
    }
    static forText(scale, fontStack) {
        const textOptions = new SectionOptions();
        textOptions.scale = scale || 1;
        textOptions.fontStack = fontStack;
        return textOptions;
    }
    static forImage(imageName) {
        const imageOptions = new SectionOptions();
        imageOptions.imageName = imageName;
        return imageOptions;
    }
}
class TaggedString {
    // maps each character in 'text' to its corresponding entry in 'sections'
    constructor() {
        this.text = '';
        this.sectionIndex = [];
        this.sections = [];
        this.imageSectionID = null;
    }
    static fromFeature(text, defaultFontStack) {
        const result = new TaggedString();
        for (let i = 0; i < text.sections.length; i++) {
            const section = text.sections[i];
            if (!section.image) {
                result.addTextSection(section, defaultFontStack);
            } else {
                result.addImageSection(section);
            }
        }
        return result;
    }
    length() {
        return this.text.length;
    }
    getSection(index) {
        return this.sections[this.sectionIndex[index]];
    }
    getSections() {
        return this.sections;
    }
    getSectionIndex(index) {
        return this.sectionIndex[index];
    }
    getCodePoint(index) {
        return this.text.codePointAt(index);
    }
    verticalizePunctuation(skipContextChecking) {
        this.text = verticalizePunctuation(this.text, skipContextChecking);
    }
    trim() {
        let beginningWhitespace = 0;
        for (let i = 0; i < this.text.length && whitespace[this.text.charCodeAt(i)]; i++) {
            beginningWhitespace++;
        }
        let trailingWhitespace = this.text.length;
        for (let i = this.text.length - 1; i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; i--) {
            trailingWhitespace--;
        }
        this.text = this.text.substring(beginningWhitespace, trailingWhitespace);
        this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace);
    }
    substring(start, end) {
        const substring = new TaggedString();
        substring.text = this.text.substring(start, end);
        substring.sectionIndex = this.sectionIndex.slice(start, end);
        substring.sections = this.sections;
        return substring;
    }
    toString() {
        return this.text;
    }
    getMaxScale() {
        return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0);
    }
    addTextSection(section, defaultFontStack) {
        this.text += section.text;
        this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack));
        const index = this.sections.length - 1;
        for (let i = 0; i < section.text.length; ++i) {
            this.sectionIndex.push(index);
        }
    }
    addImageSection(section) {
        const imageName = section.image ? section.image.namePrimary : '';
        if (imageName.length === 0) {
            warnOnce(`Can't add FormattedSection with an empty image.`);
            return;
        }
        const nextImageSectionCharCode = this.getNextImageSectionCharCode();
        if (!nextImageSectionCharCode) {
            warnOnce(`Reached maximum number of images ${ PUAend - PUAbegin + 2 }`);
            return;
        }
        this.text += String.fromCodePoint(nextImageSectionCharCode);
        this.sections.push(SectionOptions.forImage(imageName));
        this.sectionIndex.push(this.sections.length - 1);
    }
    getNextImageSectionCharCode() {
        if (!this.imageSectionID) {
            this.imageSectionID = PUAbegin;
            return this.imageSectionID;
        }
        if (this.imageSectionID >= PUAend)
            return null;
        return ++this.imageSectionID;
    }
}
function breakLines(input, lineBreakPoints) {
    const lines = [];
    const text = input.text;
    let start = 0;
    for (const lineBreak of lineBreakPoints) {
        lines.push(input.substring(start, lineBreak));
        start = lineBreak;
    }
    if (start < text.length) {
        lines.push(input.substring(start, text.length));
    }
    return lines;
}
function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate, writingMode, allowVerticalPlacement, layoutTextSize, layoutTextSizeThisZoom) {
    const logicalInput = TaggedString.fromFeature(text, defaultFontStack);
    if (writingMode === WritingMode.vertical) {
        logicalInput.verticalizePunctuation(allowVerticalPlacement);
    }
    let lines = [];
    const lineBreaks = determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);
    const {processBidirectionalText, processStyledBidirectionalText} = plugin;
    if (processBidirectionalText && logicalInput.sections.length === 1) {
        // Bidi doesn't have to be style-aware
        const untaggedLines = processBidirectionalText(logicalInput.toString(), lineBreaks);
        for (const line of untaggedLines) {
            const taggedLine = new TaggedString();
            taggedLine.text = line;
            taggedLine.sections = logicalInput.sections;
            for (let i = 0; i < line.length; i++) {
                taggedLine.sectionIndex.push(0);
            }
            lines.push(taggedLine);
        }
    } else if (processStyledBidirectionalText) {
        // Need version of mapbox-gl-rtl-text with style support for combining RTL text with formatting
        const processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, lineBreaks);
        for (const line of processedLines) {
            const taggedLine = new TaggedString();
            taggedLine.text = line[0];
            taggedLine.sectionIndex = line[1];
            taggedLine.sections = logicalInput.sections;
            lines.push(taggedLine);
        }
    } else {
        lines = breakLines(logicalInput, lineBreaks);
    }
    const positionedLines = [];
    const shaping = {
        positionedLines,
        text: logicalInput.toString(),
        top: translate[1],
        bottom: translate[1],
        left: translate[0],
        right: translate[0],
        writingMode,
        iconsInText: false,
        verticalizable: false,
        hasBaseline: false
    };
    shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom);
    if (isEmpty(positionedLines))
        return false;
    return shaping;
}
// using computed properties due to https://github.com/facebook/flow/issues/380
/* eslint no-useless-computed-key: 0 */
const whitespace = {
    [9]: true,
    // tab
    [10]: true,
    // newline
    [11]: true,
    // vertical tab
    [12]: true,
    // form feed
    [13]: true,
    // carriage return
    [32]: true
};
const breakable = {
    [10]: true,
    // newline
    [32]: true,
    // space
    [38]: true,
    // ampersand
    [40]: true,
    // left parenthesis
    [41]: true,
    // right parenthesis
    [43]: true,
    // plus sign
    [45]: true,
    // hyphen-minus
    [47]: true,
    // solidus
    [173]: true,
    // soft hyphen
    [183]: true,
    // middle dot
    [8203]: true,
    // zero-width space
    [8208]: true,
    // hyphen
    [8211]: true,
    // en dash
    [8231]: true    // interpunct
            // Many other characters may be reasonable breakpoints
            // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation
            // See https://github.com/mapbox/mapbox-gl-js/issues/3658
};
function getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize) {
    if (!section.imageName) {
        const positions = glyphMap[section.fontStack];
        const glyph = positions && positions.glyphs[codePoint];
        if (!glyph)
            return 0;
        return glyph.metrics.advance * section.scale + spacing;
    } else {
        const imagePosition = imagePositions[section.imageName];
        if (!imagePosition)
            return 0;
        return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing;
    }
}
function determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) {
    let totalWidth = 0;
    for (let index = 0; index < logicalInput.length(); index++) {
        const section = logicalInput.getSection(index);
        totalWidth += getGlyphAdvance(logicalInput.getCodePoint(index), section, glyphMap, imagePositions, spacing, layoutTextSize);
    }
    const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth));
    return totalWidth / lineCount;
}
function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) {
    const raggedness = Math.pow(lineWidth - targetWidth, 2);
    if (isLastBreak) {
        // Favor finals lines shorter than average over longer than average
        if (lineWidth < targetWidth) {
            return raggedness / 2;
        } else {
            return raggedness * 2;
        }
    }
    return raggedness + Math.abs(penalty) * penalty;
}
function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) {
    let penalty = 0;
    // Force break on newline
    if (codePoint === 10) {
        penalty -= 10000;
    }
    // Penalize breaks between characters that allow ideographic breaking because
    // they are less preferable than breaks at spaces (or zero width spaces).
    if (penalizableIdeographicBreak) {
        penalty += 150;
    }
    // Penalize open parenthesis at end of line
    if (codePoint === 40 || codePoint === 65288) {
        penalty += 50;
    }
    // Penalize close parenthesis at beginning of line
    if (nextCodePoint === 41 || nextCodePoint === 65289) {
        penalty += 50;
    }
    return penalty;
}
function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) {
    // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth
    //  ...but in fact we allow lines longer than maxWidth (if there's no break points)
    //  ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give
    //     more lopsided results.
    let bestPriorBreak = null;
    let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak);
    for (const potentialBreak of potentialBreaks) {
        const lineWidth = breakX - potentialBreak.x;
        const breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness;
        if (breakBadness <= bestBreakBadness) {
            bestPriorBreak = potentialBreak;
            bestBreakBadness = breakBadness;
        }
    }
    return {
        index: breakIndex,
        x: breakX,
        priorBreak: bestPriorBreak,
        badness: bestBreakBadness
    };
}
function leastBadBreaks(lastLineBreak) {
    if (!lastLineBreak) {
        return [];
    }
    return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);
}
function determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) {
    if (!logicalInput)
        return [];
    const potentialLineBreaks = [];
    const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);
    const hasServerSuggestedBreakpoints = logicalInput.text.indexOf('\u200B') >= 0;
    let currentX = 0;
    for (let i = 0; i < logicalInput.length(); i++) {
        const section = logicalInput.getSection(i);
        const codePoint = logicalInput.getCodePoint(i);
        if (!whitespace[codePoint])
            currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize);
        // Ideographic characters, spaces, and word-breaking punctuation that often appear without
        // surrounding spaces.
        if (i < logicalInput.length() - 1) {
            const ideographicBreak = charAllowsIdeographicBreaking(codePoint);
            if (breakable[codePoint] || ideographicBreak || section.imageName) {
                potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, logicalInput.getCodePoint(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), false));
            }
        }
    }
    return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialLineBreaks, 0, true));
}
function getAnchorAlignment(anchor) {
    let horizontalAlign = 0.5, verticalAlign = 0.5;
    switch (anchor) {
    case 'right':
    case 'top-right':
    case 'bottom-right':
        horizontalAlign = 1;
        break;
    case 'left':
    case 'top-left':
    case 'bottom-left':
        horizontalAlign = 0;
        break;
    }
    switch (anchor) {
    case 'bottom':
    case 'bottom-right':
    case 'bottom-left':
        verticalAlign = 1;
        break;
    case 'top':
    case 'top-right':
    case 'top-left':
        verticalAlign = 0;
        break;
    }
    return {
        horizontalAlign,
        verticalAlign
    };
}
function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) {
    let x = 0;
    let y = 0;
    let maxLineLength = 0;
    const justify = textJustify === 'right' ? 1 : textJustify === 'left' ? 0 : 0.5;
    let hasBaseline = false;
    for (const line of lines) {
        const sections = line.getSections();
        for (const section of sections) {
            if (section.imageName)
                continue;
            const glyphData = glyphMap[section.fontStack];
            if (!glyphData)
                continue;
            hasBaseline = glyphData.ascender !== undefined && glyphData.descender !== undefined;
            if (!hasBaseline)
                break;
        }
        if (!hasBaseline)
            break;
    }
    let lineIndex = 0;
    for (const line of lines) {
        line.trim();
        const lineMaxScale = line.getMaxScale();
        const maxLineOffset = (lineMaxScale - 1) * ONE_EM;
        const positionedLine = {
            positionedGlyphs: [],
            lineOffset: 0
        };
        shaping.positionedLines[lineIndex] = positionedLine;
        const positionedGlyphs = positionedLine.positionedGlyphs;
        let lineOffset = 0;
        if (!line.length()) {
            y += lineHeight;
            // Still need a line feed after empty line
            ++lineIndex;
            continue;
        }
        let biggestHeight = 0;
        let baselineOffset = 0;
        for (let i = 0; i < line.length(); i++) {
            const section = line.getSection(i);
            const sectionIndex = line.getSectionIndex(i);
            const codePoint = line.getCodePoint(i);
            let sectionScale = section.scale;
            let metrics = null;
            let rect = null;
            let imageName = null;
            let verticalAdvance = ONE_EM;
            let glyphOffset = 0;
            const vertical = !(writingMode === WritingMode.horizontal || !allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint) || allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)));
            if (!section.imageName) {
                // Find glyph position in the glyph atlas, if bitmap is null,
                // glyphPosition will not exit in the glyphPosition map
                const glyphPositionData = glyphPositions[section.fontStack];
                if (!glyphPositionData)
                    continue;
                if (glyphPositionData[codePoint]) {
                    rect = glyphPositionData[codePoint];
                }
                const glyphData = glyphMap[section.fontStack];
                if (!glyphData)
                    continue;
                const glyph = glyphData.glyphs[codePoint];
                if (!glyph)
                    continue;
                metrics = glyph.metrics;
                verticalAdvance = codePoint !== 8203 ? ONE_EM : 0;
                // In order to make different fonts aligned, they must share a general baseline that aligns with every
                // font's real baseline. Glyph's offset is counted from the top left corner, where the ascender line
                // starts.
                // First of all, each glyph's baseline lies on the center line of the shaping line. Since ascender
                // is above the baseline, the glyphOffset is the negative shift. Then, in order to make glyphs fit in
                // the shaping box, for each line, we shift the glyph with biggest height(with scale) to make its center
                // lie on the center line of the line, which will lead to a baseline shift. Then adjust the whole line
                // with the baseline offset we calculated from the shift.
                if (hasBaseline) {
                    const ascender = glyphData.ascender !== undefined ? Math.abs(glyphData.ascender) : 0;
                    const descender = glyphData.descender !== undefined ? Math.abs(glyphData.descender) : 0;
                    const value = (ascender + descender) * sectionScale;
                    if (biggestHeight < value) {
                        biggestHeight = value;
                        baselineOffset = (ascender - descender) / 2 * sectionScale;
                    }
                    glyphOffset = -ascender * sectionScale;
                } else {
                    // If font's baseline is not applicable, fall back to use a default baseline offset, see
                    // Shaping::yOffset. Since we're laying out at 24 points, we need also calculate how much it will
                    // move when we scale up or down.
                    glyphOffset = SHAPING_DEFAULT_OFFSET + (lineMaxScale - sectionScale) * ONE_EM;
                }
            } else {
                const imagePosition = imagePositions[section.imageName];
                if (!imagePosition)
                    continue;
                imageName = section.imageName;
                shaping.iconsInText = shaping.iconsInText || true;
                rect = imagePosition.paddedRect;
                const size = imagePosition.displaySize;
                // If needed, allow to set scale factor for an image using
                // alias "image-scale" that could be alias for "font-scale"
                // when FormattedSection is an image section.
                sectionScale = sectionScale * ONE_EM / layoutTextSizeThisZoom;
                metrics = {
                    width: size[0],
                    height: size[1],
                    left: IMAGE_PADDING,
                    top: -GLYPH_PBF_BORDER,
                    advance: vertical ? size[1] : size[0],
                    localGlyph: false
                };
                if (!hasBaseline) {
                    glyphOffset = SHAPING_DEFAULT_OFFSET + lineMaxScale * ONE_EM - size[1] * sectionScale;
                } else {
                    // Based on node-fontnik: 'top = heightAboveBaseline - Ascender'(it is not valid for locally
                    // generated glyph). Since the top is a constant: glyph's borderSize. So if we set image glyph with
                    // 'ascender = height', it means we pull down the glyph under baseline with a distance of glyph's borderSize.
                    const imageAscender = metrics.height;
                    glyphOffset = -imageAscender * sectionScale;
                }
                verticalAdvance = metrics.advance;
                // Difference between height of an image and one EM at max line scale.
                // Pushes current line down if an image size is over 1 EM at max line scale.
                const offset = (vertical ? size[0] : size[1]) * sectionScale - ONE_EM * lineMaxScale;
                if (offset > 0 && offset > lineOffset) {
                    lineOffset = offset;
                }
            }
            if (!vertical) {
                positionedGlyphs.push({
                    glyph: codePoint,
                    imageName,
                    x,
                    y: y + glyphOffset,
                    vertical,
                    scale: sectionScale,
                    localGlyph: metrics.localGlyph,
                    fontStack: section.fontStack,
                    sectionIndex,
                    metrics,
                    rect
                });
                x += metrics.advance * sectionScale + spacing;
            } else {
                shaping.verticalizable = true;
                positionedGlyphs.push({
                    glyph: codePoint,
                    imageName,
                    x,
                    y: y + glyphOffset,
                    vertical,
                    scale: sectionScale,
                    localGlyph: metrics.localGlyph,
                    fontStack: section.fontStack,
                    sectionIndex,
                    metrics,
                    rect
                });
                x += verticalAdvance * sectionScale + spacing;
            }
        }
        // Only justify if we placed at least one glyph
        if (positionedGlyphs.length !== 0) {
            const lineLength = x - spacing;
            maxLineLength = Math.max(lineLength, maxLineLength);
            // Justify the line so that its top is aligned with the current height of y, and its horizontal coordinates
            // are justified according to the TextJustifyType
            if (hasBaseline) {
                justifyLine(positionedGlyphs, justify, lineOffset, baselineOffset, lineHeight * lineMaxScale / 2);
            } else {
                // Scaled line height offset is counted in glyphOffset, so here just use an unscaled line height
                justifyLine(positionedGlyphs, justify, lineOffset, 0, lineHeight / 2);
            }
        }
        x = 0;
        const currentLineHeight = lineHeight * lineMaxScale + lineOffset;
        positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset);
        y += currentLineHeight;
        ++lineIndex;
    }
    const height = y;
    const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor);
    align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, height);
    // Calculate the bounding box
    shaping.top += -verticalAlign * height;
    shaping.bottom = shaping.top + height;
    shaping.left += -horizontalAlign * maxLineLength;
    shaping.right = shaping.left + maxLineLength;
    shaping.hasBaseline = hasBaseline;
}
// justify right = 1, left = 0, center = 0.5
function justifyLine(positionedGlyphs, justify, lineOffset, baselineOffset, halfLineHeight) {
    if (!justify && !lineOffset && !baselineOffset && !halfLineHeight) {
        return;
    }
    const end = positionedGlyphs.length - 1;
    const lastGlyph = positionedGlyphs[end];
    const lastAdvance = lastGlyph.metrics.advance * lastGlyph.scale;
    const lineIndent = (lastGlyph.x + lastAdvance) * justify;
    for (let j = 0; j <= end; j++) {
        positionedGlyphs[j].x -= lineIndent;
        positionedGlyphs[j].y += lineOffset + baselineOffset + halfLineHeight;
    }
}
function align(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, blockHeight) {
    const shiftX = (justify - horizontalAlign) * maxLineLength;
    const shiftY = -blockHeight * verticalAlign;
    for (const line of positionedLines) {
        for (const positionedGlyph of line.positionedGlyphs) {
            positionedGlyph.x += shiftX;
            positionedGlyph.y += shiftY;
        }
    }
}
function shapeIcon(imagePrimary, imageSecondary, iconOffset, iconAnchor) {
    const {horizontalAlign, verticalAlign} = getAnchorAlignment(iconAnchor);
    const dx = iconOffset[0];
    const dy = iconOffset[1];
    const x1 = dx - imagePrimary.displaySize[0] * horizontalAlign;
    const x2 = x1 + imagePrimary.displaySize[0];
    const y1 = dy - imagePrimary.displaySize[1] * verticalAlign;
    const y2 = y1 + imagePrimary.displaySize[1];
    return {
        imagePrimary,
        imageSecondary,
        top: y1,
        bottom: y2,
        left: x1,
        right: x2
    };
}
function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) {
    const image = shapedIcon.imagePrimary;
    let collisionPadding;
    if (image.content) {
        const content = image.content;
        const pixelRatio = image.pixelRatio || 1;
        collisionPadding = [
            content[0] / pixelRatio,
            content[1] / pixelRatio,
            image.displaySize[0] - content[2] / pixelRatio,
            image.displaySize[1] - content[3] / pixelRatio
        ];
    }
    // We don't respect the icon-anchor, because icon-text-fit is set. Instead,
    // the icon will be centered on the text, then stretched in the given
    // dimensions.
    const textLeft = shapedText.left * fontScale;
    const textRight = shapedText.right * fontScale;
    let top, right, bottom, left;
    if (textFit === 'width' || textFit === 'both') {
        // Stretched horizontally to the text width
        left = iconOffset[0] + textLeft - padding[3];
        right = iconOffset[0] + textRight + padding[1];
    } else {
        // Centered on the text
        left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2;
        right = left + image.displaySize[0];
    }
    const textTop = shapedText.top * fontScale;
    const textBottom = shapedText.bottom * fontScale;
    if (textFit === 'height' || textFit === 'both') {
        // Stretched vertically to the text height
        top = iconOffset[1] + textTop - padding[0];
        bottom = iconOffset[1] + textBottom + padding[2];
    } else {
        // Centered on the text
        top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2;
        bottom = top + image.displaySize[1];
    }
    return {
        imagePrimary: image,
        imageSecondary: undefined,
        top,
        right,
        bottom,
        left,
        collisionPadding
    };
}

//      
class Anchor extends Point$2 {
    constructor(x, y, z, angle, segment) {
        super(x, y);
        this.angle = angle;
        this.z = z;
        if (segment !== undefined) {
            this.segment = segment;
        }
    }
    clone() {
        return new Anchor(this.x, this.y, this.z, this.angle, this.segment);
    }
}
register(Anchor, 'Anchor');

//      
/**
 * Labels placed around really sharp angles aren't readable. Check if any
 * part of the potential label has a combined angle that is too big.
 *
 * @param line
 * @param anchor The point on the line around which the label is anchored.
 * @param labelLength The length of the label in geometry units.
 * @param windowSize The check fails if the combined angles within a part of the line that is `windowSize` long is too big.
 * @param maxAngle The maximum combined angle that any window along the label is allowed to have.
 *
 * @returns {boolean} whether the label should be placed
 * @private
 */
function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) {
    // horizontal labels always pass
    if (anchor.segment === undefined)
        return true;
    let p = anchor;
    let index = anchor.segment + 1;
    let anchorDistance = 0;
    // move backwards along the line to the first segment the label appears on
    while (anchorDistance > -labelLength / 2) {
        index--;
        // there isn't enough room for the label after the beginning of the line
        if (index < 0)
            return false;
        anchorDistance -= line[index].dist(p);
        p = line[index];
    }
    anchorDistance += line[index].dist(line[index + 1]);
    index++;
    // store recent corners and their total angle difference
    const recentCorners = [];
    let recentAngleDelta = 0;
    // move forwards by the length of the label and check angles along the way
    while (anchorDistance < labelLength / 2) {
        const prev = line[index - 1];
        const current = line[index];
        const next = line[index + 1];
        // there isn't enough room for the label before the end of the line
        if (!next)
            return false;
        let angleDelta = prev.angleTo(current) - current.angleTo(next);
        // restrict angle to -pi..pi range
        angleDelta = Math.abs((angleDelta + 3 * Math.PI) % (Math.PI * 2) - Math.PI);
        recentCorners.push({
            distance: anchorDistance,
            angleDelta
        });
        recentAngleDelta += angleDelta;
        // remove corners that are far enough away from the list of recent anchors
        while (anchorDistance - recentCorners[0].distance > windowSize) {
            recentAngleDelta -= recentCorners.shift().angleDelta;
        }
        // the sum of angles within the window area exceeds the maximum allowed value. check fails.
        if (recentAngleDelta > maxAngle)
            return false;
        index++;
        anchorDistance += current.dist(next);
    }
    // no part of the line had an angle greater than the maximum allowed. check passes.
    return true;
}

//      
function getLineLength(line) {
    let lineLength = 0;
    for (let k = 0; k < line.length - 1; k++) {
        lineLength += line[k].dist(line[k + 1]);
    }
    return lineLength;
}
function getAngleWindowSize(shapedText, glyphSize, boxScale) {
    return shapedText ? 3 / 5 * glyphSize * boxScale : 0;
}
function getShapedLabelLength(shapedText, shapedIcon) {
    return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0);
}
function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) {
    const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);
    const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale;
    let prevDistance = 0;
    const centerDistance = getLineLength(line) / 2;
    for (let i = 0; i < line.length - 1; i++) {
        const a = line[i], b = line[i + 1];
        const segmentDistance = a.dist(b);
        if (prevDistance + segmentDistance > centerDistance) {
            // The center is on this segment
            const t = (centerDistance - prevDistance) / segmentDistance, x = number(a.x, b.x, t), y = number(a.y, b.y, t);
            const anchor = new Anchor(x, y, 0, b.angleTo(a), i);
            if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {
                return anchor;
            } else {
                return;
            }
        }
        prevDistance += segmentDistance;
    }
}
function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) {
    // Resample a line to get anchor points for labels and check that each
    // potential label passes text-max-angle check and has enough froom to fit
    // on the line.
    const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);
    const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon);
    const labelLength = shapedLabelLength * boxScale;
    // Is the line continued from outside the tile boundary?
    const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent;
    // Is the label long, relative to the spacing?
    // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges.
    if (spacing - labelLength < spacing / 4) {
        spacing = labelLength + spacing / 4;
    }
    // Offset the first anchor by:
    // Either half the label length plus a fixed extra offset if the line is not continued
    // Or half the spacing if the line is continued.
    // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections.
    const fixedExtraOffset = glyphSize * 2;
    const offset = !isLineContinued ? (shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling % spacing : spacing / 2 * overscaling % spacing;
    return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent);
}
function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) {
    const halfLabelLength = labelLength / 2;
    const lineLength = getLineLength(line);
    let distance = 0, markedDistance = offset - spacing;
    let anchors = [];
    for (let i = 0; i < line.length - 1; i++) {
        const a = line[i], b = line[i + 1];
        const segmentDist = a.dist(b), angle = b.angleTo(a);
        while (markedDistance + spacing < distance + segmentDist) {
            markedDistance += spacing;
            const t = (markedDistance - distance) / segmentDist, x = number(a.x, b.x, t), y = number(a.y, b.y, t);
            // Check that the point is within the tile boundaries and that
            // the label would fit before the beginning and end of the line
            // if placed at this point.
            if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && markedDistance - halfLabelLength >= 0 && markedDistance + halfLabelLength <= lineLength) {
                const anchor = new Anchor(x, y, 0, angle, i);
                if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {
                    anchors.push(anchor);
                }
            }
        }
        distance += segmentDist;
    }
    if (!placeAtMiddle && !anchors.length && !isLineContinued) {
        // The first attempt at finding anchors at which labels can be placed failed.
        // Try again, but this time just try placing one anchor at the middle of the line.
        // This has the most effect for short lines in overscaled tiles, since the
        // initial offset used in overscaled tiles is calculated to align labels with positions in
        // parent tiles instead of placing the label as close to the beginning as possible.
        anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent);
    }
    return anchors;
}

//      
/**
 * Returns the part of a multiline that intersects with the provided rectangular box.
 *
 * @param lines
 * @param x1 the left edge of the box
 * @param y1 the top edge of the box
 * @param x2 the right edge of the box
 * @param y2 the bottom edge of the box
 * @returns lines
 * @private
 */
function clipLine(lines, x1, y1, x2, y2) {
    const clippedLines = [];
    for (let l = 0; l < lines.length; l++) {
        const line = lines[l];
        let clippedLine;
        for (let i = 0; i < line.length - 1; i++) {
            let p0 = line[i];
            let p1 = line[i + 1];
            if (p0.x < x1 && p1.x < x1) {
                continue;
            } else if (p0.x < x1) {
                p0 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();
            } else if (p1.x < x1) {
                p1 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();
            }
            if (p0.y < y1 && p1.y < y1) {
                continue;
            } else if (p0.y < y1) {
                p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();
            } else if (p1.y < y1) {
                p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();
            }
            if (p0.x >= x2 && p1.x >= x2) {
                continue;
            } else if (p0.x >= x2) {
                p0 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();
            } else if (p1.x >= x2) {
                p1 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();
            }
            if (p0.y >= y2 && p1.y >= y2) {
                continue;
            } else if (p0.y >= y2) {
                p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();
            } else if (p1.y >= y2) {
                p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();
            }
            if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) {
                clippedLine = [p0];
                clippedLines.push(clippedLine);
            }
            clippedLine.push(p1);
        }
    }
    return clippedLines;
}

//      
function loadGlyphRange (fontstack, range, urlTemplate, requestManager, callback) {
    const begin = range * 256;
    const end = begin + 255;
    const request = requestManager.transformRequest(requestManager.normalizeGlyphsURL(urlTemplate).replace('{fontstack}', fontstack).replace('{range}', `${ begin }-${ end }`), ResourceType.Glyphs);
    getArrayBuffer(request, (err, data) => {
        if (err) {
            callback(err);
        } else if (data) {
            const glyphs = {};
            const glyphData = parseGlyphPBF(data);
            for (const glyph of glyphData.glyphs) {
                glyphs[glyph.id] = glyph;
            }
            callback(null, {
                glyphs,
                ascender: glyphData.ascender,
                descender: glyphData.descender
            });
        }
    });
}

const INF = 100000000000000000000;
class TinySDF {
    constructor({fontSize = 24, buffer = 3, radius = 8, cutoff = 0.25, fontFamily = 'sans-serif', fontWeight = 'normal', fontStyle = 'normal'} = {}) {
        this.buffer = buffer;
        this.cutoff = cutoff;
        this.radius = radius;
        // make the canvas size big enough to both have the specified buffer around the glyph
        // for "halo", and account for some glyphs possibly being larger than their font size
        const size = this.size = fontSize + buffer * 4;
        const canvas = this._createCanvas(size);
        const ctx = this.ctx = canvas.getContext('2d', { willReadFrequently: true });
        ctx.font = `${ fontStyle } ${ fontWeight } ${ fontSize }px ${ fontFamily }`;
        ctx.textBaseline = 'alphabetic';
        ctx.textAlign = 'left';
        // Necessary so that RTL text doesn't have different alignment
        ctx.fillStyle = 'black';
        // temporary arrays for the distance transform
        this.gridOuter = new Float64Array(size * size);
        this.gridInner = new Float64Array(size * size);
        this.f = new Float64Array(size);
        this.z = new Float64Array(size + 1);
        this.v = new Uint16Array(size);
    }
    _createCanvas(size) {
        const canvas = document.createElement('canvas');
        canvas.width = canvas.height = size;
        return canvas;
    }
    draw(char) {
        const {
            width: glyphAdvance,
            actualBoundingBoxAscent,
            actualBoundingBoxDescent,
            actualBoundingBoxLeft,
            actualBoundingBoxRight
        } = this.ctx.measureText(char);
        // The integer/pixel part of the top alignment is encoded in metrics.glyphTop
        // The remainder is implicitly encoded in the rasterization
        const glyphTop = Math.ceil(actualBoundingBoxAscent);
        const glyphLeft = 0;
        // If the glyph overflows the canvas size, it will be clipped at the bottom/right
        const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft)));
        const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent));
        const width = glyphWidth + 2 * this.buffer;
        const height = glyphHeight + 2 * this.buffer;
        const len = Math.max(width * height, 0);
        const data = new Uint8ClampedArray(len);
        const glyph = {
            data,
            width,
            height,
            glyphWidth,
            glyphHeight,
            glyphTop,
            glyphLeft,
            glyphAdvance
        };
        if (glyphWidth === 0 || glyphHeight === 0)
            return glyph;
        const {ctx, buffer, gridInner, gridOuter} = this;
        ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);
        ctx.fillText(char, buffer, buffer + glyphTop);
        const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);
        // Initialize grids outside the glyph range to alpha 0
        gridOuter.fill(INF, 0, len);
        gridInner.fill(0, 0, len);
        for (let y = 0; y < glyphHeight; y++) {
            for (let x = 0; x < glyphWidth; x++) {
                const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255;
                // alpha value
                if (a === 0)
                    continue;
                // empty pixels
                const j = (y + buffer) * width + x + buffer;
                if (a === 1) {
                    // fully drawn pixels
                    gridOuter[j] = 0;
                    gridInner[j] = INF;
                } else {
                    // aliased pixels
                    const d = 0.5 - a;
                    gridOuter[j] = d > 0 ? d * d : 0;
                    gridInner[j] = d < 0 ? d * d : 0;
                }
            }
        }
        edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);
        edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z);
        for (let i = 0; i < len; i++) {
            const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);
            data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff));
        }
        return glyph;
    }
}
// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf
function edt(data, x0, y0, width, height, gridSize, f, v, z) {
    for (let x = x0; x < x0 + width; x++)
        edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);
    for (let y = y0; y < y0 + height; y++)
        edt1d(data, y * gridSize + x0, 1, width, f, v, z);
}
// 1D squared distance transform
function edt1d(grid, offset, stride, length, f, v, z) {
    v[0] = 0;
    z[0] = -INF;
    z[1] = INF;
    f[0] = grid[offset];
    for (let q = 1, k = 0, s = 0; q < length; q++) {
        f[q] = grid[offset + q * stride];
        const q2 = q * q;
        do {
            const r = v[k];
            s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;
        } while (s <= z[k] && --k > -1);
        k++;
        v[k] = q;
        z[k] = s;
        z[k + 1] = INF;
    }
    for (let q = 0, k = 0; q < length; q++) {
        while (z[k + 1] < q)
            k++;
        const r = v[k];
        const qr = q - r;
        grid[offset + q * stride] = f[r] + qr * qr;
    }
}

//      
/*
  SDF_SCALE controls the pixel density of locally generated glyphs relative
  to "normal" SDFs which are generated at 24pt font and a "pixel ratio" of 1.
  The GlyphManager will generate glyphs SDF_SCALE times as large,
  but with the same glyph metrics, and the quad generation code will scale them
  back down so they display at the same size.

  The choice of SDF_SCALE is a trade-off between performance and quality.
  Glyph generation time grows quadratically with the the scale, while quality
  improvements drop off rapidly when the scale is higher than the pixel ratio
  of the device. The scale of 2 buys noticeable improvements on HDPI screens
  at acceptable cost.

  The scale can be any value, but in order to avoid small distortions, these
  pixel-based values must come out to integers:
   - "localGlyphPadding" in GlyphAtlas
   - Font/Canvas/Buffer size for TinySDF
  localGlyphPadding + buffer should equal 4 * SDF_SCALE. So if you wanted to
  use an SDF_SCALE of 1.75, you could manually set localGlyphAdding to 2 and
  buffer to 5.
*/
const SDF_SCALE = 2;
const LocalGlyphMode = {
    none: 0,
    ideographs: 1,
    all: 2
};
class GlyphManager {
    // Multiple fontstacks may share the same local glyphs, so keep an index
    // into the glyphs based soley on font weight
    // exposed as statics to enable stubbing in unit tests
    constructor(requestManager, localGlyphMode, localFontFamily) {
        this.requestManager = requestManager;
        this.localGlyphMode = localGlyphMode;
        this.localFontFamily = localFontFamily;
        this.urls = {};
        this.entries = {};
        this.localGlyphs = {
            // Only these four font weights are supported
            '200': {},
            '400': {},
            '500': {},
            '900': {}
        };
    }
    setURL(url, scope) {
        this.urls[scope] = url;
    }
    getGlyphs(glyphs, scope, callback) {
        const all = [];
        // Fallback to the default glyphs URL if none is specified
        const url = this.urls[scope] || config.GLYPHS_URL;
        for (const stack in glyphs) {
            for (const id of glyphs[stack]) {
                all.push({
                    stack,
                    id
                });
            }
        }
        asyncAll(all, ({stack, id}, fnCallback) => {
            let entry = this.entries[stack];
            if (!entry) {
                entry = this.entries[stack] = {
                    glyphs: {},
                    requests: {},
                    ranges: {},
                    ascender: undefined,
                    descender: undefined
                };
            }
            let glyph = entry.glyphs[id];
            if (glyph !== undefined) {
                fnCallback(null, {
                    stack,
                    id,
                    glyph
                });
                return;
            }
            glyph = this._tinySDF(entry, stack, id);
            if (glyph) {
                entry.glyphs[id] = glyph;
                fnCallback(null, {
                    stack,
                    id,
                    glyph
                });
                return;
            }
            const range = Math.floor(id / 256);
            if (range * 256 > 65535) {
                fnCallback(new Error('glyphs > 65535 not supported'));
                return;
            }
            if (entry.ranges[range]) {
                fnCallback(null, {
                    stack,
                    id,
                    glyph
                });
                return;
            }
            let requests = entry.requests[range];
            if (!requests) {
                requests = entry.requests[range] = [];
                GlyphManager.loadGlyphRange(stack, range, url, this.requestManager, (err, response) => {
                    if (response) {
                        entry.ascender = response.ascender;
                        entry.descender = response.descender;
                        for (const id in response.glyphs) {
                            if (!this._doesCharSupportLocalGlyph(+id)) {
                                entry.glyphs[+id] = response.glyphs[+id];
                            }
                        }
                        entry.ranges[range] = true;
                    }
                    for (const cb of requests) {
                        cb(err, response);
                    }
                    delete entry.requests[range];
                });
            }
            requests.push((err, result) => {
                if (err) {
                    fnCallback(err);
                } else if (result) {
                    fnCallback(null, {
                        stack,
                        id,
                        glyph: result.glyphs[id] || null
                    });
                }
            });
        }, (err, glyphs) => {
            if (err) {
                callback(err);
            } else if (glyphs) {
                const result = {};
                for (const {stack, id, glyph} of glyphs) {
                    // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred.
                    if (result[stack] === undefined)
                        result[stack] = {};
                    if (result[stack].glyphs === undefined)
                        result[stack].glyphs = {};
                    result[stack].glyphs[id] = glyph && {
                        id: glyph.id,
                        bitmap: glyph.bitmap.clone(),
                        metrics: glyph.metrics
                    };
                    result[stack].ascender = this.entries[stack].ascender;
                    result[stack].descender = this.entries[stack].descender;
                }
                callback(null, result);
            }
        });
    }
    _doesCharSupportLocalGlyph(id) {
        if (this.localGlyphMode === LocalGlyphMode.none) {
            return false;
        } else if (this.localGlyphMode === LocalGlyphMode.all) {
            return !!this.localFontFamily;
        } else {
            /* eslint-disable new-cap */
            return !!this.localFontFamily && (unicodeBlockLookup['CJK Unified Ideographs'](id) || unicodeBlockLookup['Hangul Syllables'](id) || unicodeBlockLookup['Hiragana'](id) || unicodeBlockLookup['Katakana'](id) || // gl-native parity: Extend Ideographs rasterization range to include CJK symbols and punctuations
            unicodeBlockLookup['CJK Symbols and Punctuation'](id) || unicodeBlockLookup['CJK Unified Ideographs Extension A'](id) || unicodeBlockLookup['CJK Unified Ideographs Extension B'](id)    // very rare surrogate characters
);    /* eslint-enable new-cap */
        }
    }
    _tinySDF(entry, stack, id) {
        const fontFamily = this.localFontFamily;
        if (!fontFamily || !this._doesCharSupportLocalGlyph(id))
            return;
        let tinySDF = entry.tinySDF;
        if (!tinySDF) {
            let fontWeight = '400';
            if (/bold/i.test(stack)) {
                fontWeight = '900';
            } else if (/medium/i.test(stack)) {
                fontWeight = '500';
            } else if (/light/i.test(stack)) {
                fontWeight = '200';
            }
            const fontSize = 24 * SDF_SCALE;
            const buffer = 3 * SDF_SCALE;
            const radius = 8 * SDF_SCALE;
            tinySDF = entry.tinySDF = new GlyphManager.TinySDF({
                fontFamily,
                fontWeight,
                fontSize,
                buffer,
                radius
            });
            tinySDF.fontWeight = fontWeight;
        }
        if (this.localGlyphs[tinySDF.fontWeight][id]) {
            return this.localGlyphs[tinySDF.fontWeight][id];
        }
        const char = String.fromCodePoint(id);
        const {data, width, height, glyphWidth, glyphHeight, glyphLeft, glyphTop, glyphAdvance} = tinySDF.draw(char);
        /*
        TinySDF's "top" is the distance from the alphabetic baseline to the
         top of the glyph.

        Server-generated fonts specify "top" relative to an origin above the
         em box (the origin comes from FreeType, but I'm unclear on exactly
         how it's derived)
          ref: https://github.com/mapbox/sdf-glyph-foundry

        Server fonts don't yet include baseline information, so we can't line
        up exactly with them (and they don't line up with each other)
          ref: https://github.com/mapbox/node-fontnik/pull/160

        To approximately align TinySDF glyphs with server-provided glyphs, we
        use this baseline adjustment factor calibrated to be in between DIN Pro
        and Arial Unicode (but closer to Arial Unicode)
        */
        const baselineAdjustment = 27;
        const glyph = this.localGlyphs[tinySDF.fontWeight][id] = {
            id,
            bitmap: new AlphaImage({
                width,
                height
            }, data),
            metrics: {
                width: glyphWidth / SDF_SCALE,
                height: glyphHeight / SDF_SCALE,
                left: glyphLeft / SDF_SCALE,
                top: glyphTop / SDF_SCALE - baselineAdjustment,
                advance: glyphAdvance / SDF_SCALE,
                localGlyph: true
            }
        };
        return glyph;
    }
}
GlyphManager.loadGlyphRange = loadGlyphRange;
GlyphManager.TinySDF = TinySDF;

//      
/**
 * A textured quad for rendering a single icon or glyph.
 *
 * The zoom range the glyph can be shown is defined by minScale and maxScale.
 *
 * @param tl The offset of the top left corner from the anchor.
 * @param tr The offset of the top right corner from the anchor.
 * @param bl The offset of the bottom left corner from the anchor.
 * @param br The offset of the bottom right corner from the anchor.
 * @param texPrimary The texture coordinates of the primary image.
 * @param texSecondary The texture coordinates of an optional secondary image.
 *
 * @private
 */
// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual
// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped
// on one edge in some cases.
const border = IMAGE_PADDING;
/**
 * Create the quads used for rendering an icon.
 * @private
 */
function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) {
    const quads = [];
    const image = shapedIcon.imagePrimary;
    const pixelRatio = image.pixelRatio;
    const imageWidth = image.paddedRect.w - 2 * border;
    const imageHeight = image.paddedRect.h - 2 * border;
    const iconWidth = shapedIcon.right - shapedIcon.left;
    const iconHeight = shapedIcon.bottom - shapedIcon.top;
    const stretchX = image.stretchX || [[
            0,
            imageWidth
        ]];
    const stretchY = image.stretchY || [[
            0,
            imageHeight
        ]];
    const reduceRanges = (sum, range) => sum + range[1] - range[0];
    const stretchWidth = stretchX.reduce(reduceRanges, 0);
    const stretchHeight = stretchY.reduce(reduceRanges, 0);
    const fixedWidth = imageWidth - stretchWidth;
    const fixedHeight = imageHeight - stretchHeight;
    let stretchOffsetX = 0;
    let stretchContentWidth = stretchWidth;
    let stretchOffsetY = 0;
    let stretchContentHeight = stretchHeight;
    let fixedOffsetX = 0;
    let fixedContentWidth = fixedWidth;
    let fixedOffsetY = 0;
    let fixedContentHeight = fixedHeight;
    if (image.content && hasIconTextFit) {
        const content = image.content;
        stretchOffsetX = sumWithinRange(stretchX, 0, content[0]);
        stretchOffsetY = sumWithinRange(stretchY, 0, content[1]);
        stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]);
        stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]);
        fixedOffsetX = content[0] - stretchOffsetX;
        fixedOffsetY = content[1] - stretchOffsetY;
        fixedContentWidth = content[2] - content[0] - stretchContentWidth;
        fixedContentHeight = content[3] - content[1] - stretchContentHeight;
    }
    const makeBox = (left, top, right, bottom) => {
        const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);
        const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth);
        const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);
        const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight);
        const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);
        const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth);
        const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);
        const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight);
        const tl = new Point$2(leftEm, topEm);
        const tr = new Point$2(rightEm, topEm);
        const br = new Point$2(rightEm, bottomEm);
        const bl = new Point$2(leftEm, bottomEm);
        const pixelOffsetTL = new Point$2(leftPx / pixelRatio, topPx / pixelRatio);
        const pixelOffsetBR = new Point$2(rightPx / pixelRatio, bottomPx / pixelRatio);
        const angle = iconRotate * Math.PI / 180;
        if (angle) {
            const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [
                    cos,
                    -sin,
                    sin,
                    cos
                ];
            tl._matMult(matrix);
            tr._matMult(matrix);
            bl._matMult(matrix);
            br._matMult(matrix);
        }
        const x1 = left.stretch + left.fixed;
        const x2 = right.stretch + right.fixed;
        const y1 = top.stretch + top.fixed;
        const y2 = bottom.stretch + bottom.fixed;
        const subRect = {
            x: image.paddedRect.x + border + x1,
            y: image.paddedRect.y + border + y1,
            w: x2 - x1,
            h: y2 - y1
        };
        const imageSecondary = shapedIcon.imageSecondary;
        const subRectB = imageSecondary ? {
            x: imageSecondary.paddedRect.x + border + x1,
            y: imageSecondary.paddedRect.y + border + y1,
            w: x2 - x1,
            h: y2 - y1
        } : undefined;
        const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth;
        const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight;
        // Icon quad is padded, so texture coordinates also need to be padded.
        return {
            tl,
            tr,
            bl,
            br,
            texPrimary: subRect,
            texSecondary: subRectB,
            writingMode: undefined,
            glyphOffset: [
                0,
                0
            ],
            sectionIndex: 0,
            pixelOffsetTL,
            pixelOffsetBR,
            minFontScaleX,
            minFontScaleY,
            isSDF: isSDFIcon
        };
    };
    if (!hasIconTextFit || !image.stretchX && !image.stretchY) {
        quads.push(makeBox({
            fixed: 0,
            stretch: -1
        }, {
            fixed: 0,
            stretch: -1
        }, {
            fixed: 0,
            stretch: imageWidth + 1
        }, {
            fixed: 0,
            stretch: imageHeight + 1
        }));
    } else {
        const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth);
        const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight);
        for (let xi = 0; xi < xCuts.length - 1; xi++) {
            const x1 = xCuts[xi];
            const x2 = xCuts[xi + 1];
            for (let yi = 0; yi < yCuts.length - 1; yi++) {
                const y1 = yCuts[yi];
                const y2 = yCuts[yi + 1];
                quads.push(makeBox(x1, y1, x2, y2));
            }
        }
    }
    return quads;
}
function sumWithinRange(ranges, min, max) {
    let sum = 0;
    for (const range of ranges) {
        sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0]));
    }
    return sum;
}
function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) {
    const cuts = [{
            fixed: -border,
            stretch: 0
        }];
    for (const [c1, c2] of stretchZones) {
        const last = cuts[cuts.length - 1];
        cuts.push({
            fixed: c1 - last.stretch,
            stretch: last.stretch
        });
        cuts.push({
            fixed: c1 - last.stretch,
            stretch: last.stretch + (c2 - c1)
        });
    }
    cuts.push({
        fixed: fixedSize + border,
        stretch: stretchSize
    });
    return cuts;
}
function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) {
    return stretchOffset / stretchSize * iconSize + iconOffset;
}
function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) {
    return fixedOffset - fixedSize * stretchOffset / stretchSize;
}
function getRotateOffset(textOffset) {
    const x = textOffset[0], y = textOffset[1];
    const product = x * y;
    if (product > 0) {
        return [
            x,
            -y
        ];
    } else if (product < 0) {
        return [
            -x,
            y
        ];
    } else if (x === 0) {
        return [
            y,
            x
        ];
    } else {
        return [
            y,
            -x
        ];
    }
}
function getMidlineOffset(shaping, lineHeight, previousOffset, lineIndex) {
    const currentLineHeight = lineHeight + shaping.positionedLines[lineIndex].lineOffset;
    if (lineIndex === 0) {
        return previousOffset + currentLineHeight / 2;
    }
    const aboveLineHeight = lineHeight + shaping.positionedLines[lineIndex - 1].lineOffset;
    return previousOffset + (currentLineHeight + aboveLineHeight) / 2;
}
/**
 * Create the quads used for rendering a text label.
 * @private
 */
function getGlyphQuads(anchor, shaping, textOffset, layer, alongLine, feature, imageMap, allowVerticalPlacement) {
    const quads = [];
    if (shaping.positionedLines.length === 0)
        return quads;
    const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180;
    const rotateOffset = getRotateOffset(textOffset);
    let shapingHeight = Math.abs(shaping.top - shaping.bottom);
    for (const line of shaping.positionedLines) {
        shapingHeight -= line.lineOffset;
    }
    const lineCounts = shaping.positionedLines.length;
    const lineHeight = shapingHeight / lineCounts;
    let currentOffset = shaping.top - textOffset[1];
    for (let lineIndex = 0; lineIndex < lineCounts; ++lineIndex) {
        const line = shaping.positionedLines[lineIndex];
        currentOffset = getMidlineOffset(shaping, lineHeight, currentOffset, lineIndex);
        for (const positionedGlyph of line.positionedGlyphs) {
            if (!positionedGlyph.rect)
                continue;
            const textureRect = positionedGlyph.rect || {};
            // The rects have an additional buffer that is not included in their size.
            const glyphPadding = 1;
            let rectBuffer = GLYPH_PBF_BORDER + glyphPadding;
            let isSDF = true;
            let pixelRatio = 1;
            let lineOffset = 0;
            if (positionedGlyph.imageName) {
                const image = imageMap[positionedGlyph.imageName];
                if (!image)
                    continue;
                if (image.sdf) {
                    warnOnce('SDF images are not supported in formatted text and will be ignored.');
                    continue;
                }
                isSDF = false;
                pixelRatio = image.pixelRatio;
                rectBuffer = IMAGE_PADDING / pixelRatio;
            }
            const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical;
            const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2;
            const metrics = positionedGlyph.metrics;
            const rect = positionedGlyph.rect;
            if (rect === null)
                continue;
            // Align images and scaled glyphs in the middle of a vertical line.
            if (allowVerticalPlacement && shaping.verticalizable) {
                // image's advance for vertical shaping is its height, so that we have to take the difference into
                // account after image glyph is rotated
                lineOffset = positionedGlyph.imageName ? halfAdvance - positionedGlyph.metrics.width * positionedGlyph.scale / 2 : 0;
            }
            const glyphOffset = alongLine ? [
                positionedGlyph.x + halfAdvance,
                positionedGlyph.y
            ] : [
                0,
                0
            ];
            let builtInOffset = [
                0,
                0
            ];
            let verticalizedLabelOffset = [
                0,
                0
            ];
            let useRotateOffset = false;
            if (!alongLine) {
                if (rotateVerticalGlyph) {
                    // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation
                    // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset.
                    verticalizedLabelOffset = [
                        positionedGlyph.x + halfAdvance + rotateOffset[0],
                        positionedGlyph.y + rotateOffset[1] - lineOffset
                    ];
                    useRotateOffset = true;
                } else {
                    builtInOffset = [
                        positionedGlyph.x + halfAdvance + textOffset[0],
                        positionedGlyph.y + textOffset[1] - lineOffset
                    ];
                }
            }
            const paddedWidth = rect.w * positionedGlyph.scale / (pixelRatio * (positionedGlyph.localGlyph ? SDF_SCALE : 1));
            const paddedHeight = rect.h * positionedGlyph.scale / (pixelRatio * (positionedGlyph.localGlyph ? SDF_SCALE : 1));
            let tl, tr, bl, br;
            if (!rotateVerticalGlyph) {
                const x1 = (metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0];
                const y1 = (-metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1];
                const x2 = x1 + paddedWidth;
                const y2 = y1 + paddedHeight;
                tl = new Point$2(x1, y1);
                tr = new Point$2(x2, y1);
                bl = new Point$2(x1, y2);
                br = new Point$2(x2, y2);
            } else {
                // For vertical glyph placement, follow the steps to put the glyph bitmap in right coordinates:
                // 1. Rotate the glyph by using original glyph coordinates instead of padded coordinates, since the
                // rotation center and xOffsetCorrection are all based on original glyph's size.
                // 2. Do x offset correction so that 'tl' is shifted to the same x coordinate before rotation.
                // 3. Adjust glyph positon for 'tl' by applying vertial padding and horizontal shift, now 'tl' is the
                // coordinate where we draw the glyph bitmap.
                // 4. Calculate other three bitmap coordinates.
                // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em)
                // In horizontal orientation, the "yShift" is the negative value of the height that
                // the glyph is above the horizontal midline.
                // By rotating counter-clockwise around the point at the center of the left
                // edge of a 24x24 layout box centered below the midline, we align the midline
                // of the rotated glyphs with the horizontal midline, so the yShift is no longer
                // necessary, but we also pull the glyph to the left along the x axis.
                const yShift = positionedGlyph.y - currentOffset;
                const center = new Point$2(-halfAdvance, halfAdvance - yShift);
                const verticalRotation = -Math.PI / 2;
                const verticalOffsetCorrection = new Point$2(...verticalizedLabelOffset);
                // Relative position before rotation
                // tl ----- tr
                //   |     |
                //   |     |
                // bl ----- br
                tl = new Point$2(-halfAdvance + builtInOffset[0], builtInOffset[1]);
                tl._rotateAround(verticalRotation, center)._add(verticalOffsetCorrection);
                // Relative position after rotating
                // tr ----- br
                //   |     |
                //   |     |
                // tl ----- bl
                // After rotation, glyph lies on the horizontal midline.
                // Shift back to tl's original x coordinate before rotation by applying 'xOffsetCorrection'.
                tl.x += -yShift + halfAdvance;
                // Add padding for y coordinate's justification
                tl.y -= (metrics.left - rectBuffer) * positionedGlyph.scale;
                // Adjust x coordinate according to glyph bitmap's height and the vectical advance
                const verticalAdvance = positionedGlyph.imageName ? metrics.advance * positionedGlyph.scale : ONE_EM * positionedGlyph.scale;
                // Check wether the glyph is generated from server side or locally
                const chr = String.fromCodePoint(positionedGlyph.glyph);
                if (isVerticalClosePunctuation(chr)) {
                    // Place vertical punctuation in right place, pull down 1 pixel's space for close punctuations
                    tl.x += (-rectBuffer + 1) * positionedGlyph.scale;
                } else if (isVerticalOpenPunctuation(chr)) {
                    const xOffset = verticalAdvance - metrics.height * positionedGlyph.scale;
                    // Place vertical punctuation in right place, pull up 1 pixel's space for open punctuations
                    tl.x += xOffset + (-rectBuffer - 1) * positionedGlyph.scale;
                } else if (!positionedGlyph.imageName && (metrics.width + rectBuffer * 2 !== rect.w || metrics.height + rectBuffer * 2 !== rect.h)) {
                    // Locally generated glyphs' bitmap do not have exact 'rectBuffer' padded around the glyphs,
                    // but the original tl do have distance of rectBuffer padded to the top of the glyph.
                    const perfectPaddedHeight = (metrics.height + rectBuffer * 2) * positionedGlyph.scale;
                    const delta = verticalAdvance - perfectPaddedHeight;
                    tl.x += delta / 2;
                } else {
                    // Place the glyph bitmap right in the center of the 24x24 point boxes
                    const delta = verticalAdvance - paddedHeight;
                    tl.x += delta / 2;
                }
                // Calculate other three points
                tr = new Point$2(tl.x, tl.y - paddedWidth);
                bl = new Point$2(tl.x + paddedHeight, tl.y);
                br = new Point$2(tl.x + paddedHeight, tl.y - paddedWidth);
            }
            if (textRotate) {
                let center;
                if (!alongLine) {
                    if (useRotateOffset) {
                        center = new Point$2(rotateOffset[0], rotateOffset[1]);
                    } else {
                        center = new Point$2(textOffset[0], textOffset[1]);
                    }
                } else {
                    center = new Point$2(0, 0);
                }
                tl._rotateAround(textRotate, center);
                tr._rotateAround(textRotate, center);
                bl._rotateAround(textRotate, center);
                br._rotateAround(textRotate, center);
            }
            const pixelOffsetTL = new Point$2(0, 0);
            const pixelOffsetBR = new Point$2(0, 0);
            const minFontScaleX = 0;
            const minFontScaleY = 0;
            quads.push({
                tl,
                tr,
                bl,
                br,
                texPrimary: textureRect,
                texSecondary: undefined,
                writingMode: shaping.writingMode,
                glyphOffset,
                sectionIndex: positionedGlyph.sectionIndex,
                isSDF,
                pixelOffsetTL,
                pixelOffsetBR,
                minFontScaleX,
                minFontScaleY
            });
        }
    }
    return quads;
}

//      
/**
 * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility
 * This is a copy of http://github.com/mapbox/polylabel adapted to use Points
 *
 * @param polygonRings first item in array is the outer ring followed optionally by the list of holes, should be an element of the result of util/classify_rings
 * @param precision Specified in input coordinate units. If 0 returns after first run, if > 0 repeatedly narrows the search space until the radius of the area searched for the best pole is less than precision
 * @param debug Print some statistics to the console during execution
 * @returns Pole of Inaccessibility.
 * @private
 */
function findPoleOfInaccessibility (polygonRings, precision = 1, debug = false) {
    // find the bounding box of the outer ring
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    const outerRing = polygonRings[0];
    for (let i = 0; i < outerRing.length; i++) {
        const p = outerRing[i];
        if (!i || p.x < minX)
            minX = p.x;
        if (!i || p.y < minY)
            minY = p.y;
        if (!i || p.x > maxX)
            maxX = p.x;
        if (!i || p.y > maxY)
            maxY = p.y;
    }
    const width = maxX - minX;
    const height = maxY - minY;
    const cellSize = Math.min(width, height);
    let h = cellSize / 2;
    // a priority queue of cells in order of their "potential" (max distance to polygon)
    const cellQueue = new Queue([], compareMax);
    if (cellSize === 0)
        return new Point$2(minX, minY);
    // cover polygon with initial cells
    for (let x = minX; x < maxX; x += cellSize) {
        for (let y = minY; y < maxY; y += cellSize) {
            cellQueue.push(new Cell(x + h, y + h, h, polygonRings));
        }
    }
    // take centroid as the first best guess
    let bestCell = getCentroidCell(polygonRings);
    let numProbes = cellQueue.length;
    while (cellQueue.length) {
        // pick the most promising cell from the queue
        const cell = cellQueue.pop();
        // update the best cell if we found a better one
        if (cell.d > bestCell.d || !bestCell.d) {
            bestCell = cell;
            if (debug)
                console.log('found best %d after %d probes', Math.round(10000 * cell.d) / 10000, numProbes);
        }
        // do not drill down further if there's no chance of a better solution
        if (cell.max - bestCell.d <= precision)
            continue;
        // split the cell into four cells
        h = cell.h / 2;
        cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings));
        cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings));
        cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings));
        cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings));
        numProbes += 4;
    }
    if (debug) {
        console.log(`num probes: ${ numProbes }`);
        console.log(`best distance: ${ bestCell.d }`);
    }
    return bestCell.p;
}
function compareMax(a, b) {
    return b.max - a.max;
}
class Cell {
    constructor(x, y, h, polygon) {
        this.p = new Point$2(x, y);
        this.h = h;
        // half the cell size
        this.d = pointToPolygonDist(this.p, polygon);
        // distance from cell center to polygon
        this.max = this.d + this.h * Math.SQRT2;    // max distance to polygon within a cell
    }
}
// signed distance from point to polygon outline (negative if point is outside)
function pointToPolygonDist(p, polygon) {
    let inside = false;
    let minDistSq = Infinity;
    for (let k = 0; k < polygon.length; k++) {
        const ring = polygon[k];
        for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
            const a = ring[i];
            const b = ring[j];
            if (a.y > p.y !== b.y > p.y && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)
                inside = !inside;
            minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b));
        }
    }
    return (inside ? 1 : -1) * Math.sqrt(minDistSq);
}
// get polygon centroid
function getCentroidCell(polygon) {
    let area = 0;
    let x = 0;
    let y = 0;
    const points = polygon[0];
    for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) {
        const a = points[i];
        const b = points[j];
        const f = a.x * b.y - b.x * a.y;
        x += (a.x + b.x) * f;
        y += (a.y + b.y) * f;
        area += f * 3;
    }
    return new Cell(x / area, y / area, 0, polygon);
}

//      
// The symbol layout process needs `text-size` evaluated at up to five different zoom levels, and
// `icon-size` at up to three:
//
//   1. `text-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `text-size`
//       expressions, and to calculate the box dimensions for icon-text-fit.
//   2. `icon-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `icon-size`
//       expressions.
//   3. `text-size` and `icon-size` at the zoom level of the bucket, plus one. Used to calculate collision boxes.
//   4. `text-size` at zoom level 18. Used for something line-symbol-placement-related.
//   5.  For composite `*-size` expressions: two zoom levels of curve stops that "cover" the zoom level of the
//       bucket. These go into a vertex buffer and are used by the shader to interpolate the size at render time.
//
// (1) and (2) are stored in `bucket.layers[0].layout`. The remainder are below.
//
// The radial offset is to the edge of the text box
// In the horizontal direction, the edge of the text box is where glyphs start
// But in the vertical direction, the glyphs appear to "start" at the baseline
// We don't actually load baseline data, but we assume an offset of ONE_EM - 17
// (see "yOffset" in shaping.js)
const baselineOffset = 7;
const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY;
const sqrt2 = Math.sqrt(2);
function evaluateVariableOffset(anchor, [offsetX, offsetY]) {
    let x = 0, y = 0;
    if (offsetY === INVALID_TEXT_OFFSET) {
        // radial offset
        if (offsetX < 0)
            offsetX = 0;
        // Ignore negative offset.
        // solve for r where r^2 + r^2 = offsetX^2
        const hypotenuse = offsetX / sqrt2;
        switch (anchor) {
        case 'top-right':
        case 'top-left':
            y = hypotenuse - baselineOffset;
            break;
        case 'bottom-right':
        case 'bottom-left':
            y = -hypotenuse + baselineOffset;
            break;
        case 'bottom':
            y = -offsetX + baselineOffset;
            break;
        case 'top':
            y = offsetX - baselineOffset;
            break;
        }
        switch (anchor) {
        case 'top-right':
        case 'bottom-right':
            x = -hypotenuse;
            break;
        case 'top-left':
        case 'bottom-left':
            x = hypotenuse;
            break;
        case 'left':
            x = offsetX;
            break;
        case 'right':
            x = -offsetX;
            break;
        }
    } else {
        // text offset
        // Use absolute offset values.
        offsetX = Math.abs(offsetX);
        offsetY = Math.abs(offsetY);
        switch (anchor) {
        case 'top-right':
        case 'top-left':
        case 'top':
            y = offsetY - baselineOffset;
            break;
        case 'bottom-right':
        case 'bottom-left':
        case 'bottom':
            y = -offsetY + baselineOffset;
            break;
        }
        switch (anchor) {
        case 'top-right':
        case 'bottom-right':
        case 'right':
            x = -offsetX;
            break;
        case 'top-left':
        case 'bottom-left':
        case 'left':
            x = offsetX;
            break;
        }
    }
    return [
        x,
        y
    ];
}
function performSymbolLayout(bucket, glyphMap, glyphPositions, imageMap, imagePositions, showCollisionBoxes, availableImages, canonical, tileZoom, projection, brightness) {
    bucket.createArrays();
    const tileSize = 512 * bucket.overscaling;
    bucket.tilePixelRatio = EXTENT / tileSize;
    bucket.compareText = {};
    bucket.iconsNeedLinear = false;
    const layout = bucket.layers[0].layout;
    const unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values;
    const sizes = {};
    if (bucket.textSizeData.kind === 'composite') {
        const {minZoom, maxZoom} = bucket.textSizeData;
        sizes.compositeTextSizes = [
            unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),
            unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)
        ];
    }
    if (bucket.iconSizeData.kind === 'composite') {
        const {minZoom, maxZoom} = bucket.iconSizeData;
        sizes.compositeIconSizes = [
            unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),
            unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)
        ];
    }
    sizes.layoutTextSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(tileZoom + 1), canonical);
    sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(tileZoom + 1), canonical);
    sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18), canonical);
    const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';
    const textSize = layout.get('text-size');
    let hasAnySecondaryIcon = false;
    for (const feature of bucket.features) {
        if (feature.icon && feature.icon.nameSecondary) {
            hasAnySecondaryIcon = true;
            break;
        }
    }
    for (const feature of bucket.features) {
        const fontstack = layout.get('text-font').evaluate(feature, {}, canonical).join(',');
        const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, canonical);
        const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, canonical);
        const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, canonical);
        const shapedTextOrientations = {
            horizontal: {},
            vertical: undefined
        };
        const text = feature.text;
        let textOffset = [
            0,
            0
        ];
        if (text) {
            const unformattedText = text.toString();
            const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, canonical) * ONE_EM;
            const lineHeight = layout.get('text-line-height').evaluate(feature, {}, canonical) * ONE_EM;
            const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0;
            const textAnchor = layout.get('text-anchor').evaluate(feature, {}, canonical);
            const variableTextAnchor = layout.get('text-variable-anchor');
            if (!variableTextAnchor) {
                const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, canonical);
                // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector
                // is calculated at placement time instead of layout time
                if (radialOffset) {
                    // The style spec says don't use `text-offset` and `text-radial-offset` together
                    // but doesn't actually specify what happens if you use both. We go with the radial offset.
                    textOffset = evaluateVariableOffset(textAnchor, [
                        radialOffset * ONE_EM,
                        INVALID_TEXT_OFFSET
                    ]);
                } else {
                    textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM);
                }
            }
            let textJustify = textAlongLine ? 'center' : layout.get('text-justify').evaluate(feature, {}, canonical);
            const isPointPlacement = layout.get('symbol-placement') === 'point';
            const maxWidth = isPointPlacement ? layout.get('text-max-width').evaluate(feature, {}, canonical) * ONE_EM : Infinity;
            const addVerticalShapingIfNeeded = textJustify => {
                if (bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) {
                    // Vertical POI label placement is meant to be used for scripts that support vertical
                    // writing mode, thus, default left justification is used. If Latin
                    // scripts would need to be supported, this should take into account other justifications.
                    shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom);
                }
            };
            // If this layer uses text-variable-anchor, generate shapings for all justification possibilities.
            if (!textAlongLine && variableTextAnchor) {
                const justifications = textJustify === 'auto' ? variableTextAnchor.map(a => getAnchorJustification(a)) : [textJustify];
                let singleLine = false;
                for (let i = 0; i < justifications.length; i++) {
                    const justification = justifications[i];
                    if (shapedTextOrientations.horizontal[justification])
                        continue;
                    if (singleLine) {
                        // If the shaping for the first justification was only a single line, we
                        // can re-use it for the other justifications
                        shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0];
                    } else {
                        // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply
                        // the offsets for the anchor in the placement step.
                        const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, 'center', justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);
                        if (shaping) {
                            shapedTextOrientations.horizontal[justification] = shaping;
                            singleLine = shaping.positionedLines.length === 1;
                        }
                    }
                }
                addVerticalShapingIfNeeded('left');
            } else {
                if (textJustify === 'auto') {
                    textJustify = getAnchorJustification(textAnchor);
                }
                // Add horizontal shaping for all point labels and line labels that need horizontal writing mode.
                if (isPointPlacement || (layout.get('text-writing-mode').indexOf('horizontal') >= 0 || !allowsVerticalWritingMode(unformattedText))) {
                    const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);
                    if (shaping)
                        shapedTextOrientations.horizontal[textJustify] = shaping;
                }
                // Vertical point label (if allowVerticalPlacement is enabled).
                addVerticalShapingIfNeeded(isPointPlacement ? 'left' : textJustify);
            }
        }
        let shapedIcon;
        let isSDFIcon = false;
        if (feature.icon && feature.icon.namePrimary) {
            const image = imageMap[feature.icon.namePrimary];
            if (image) {
                shapedIcon = shapeIcon(imagePositions[feature.icon.namePrimary], feature.icon.nameSecondary ? imagePositions[feature.icon.nameSecondary] : undefined, layout.get('icon-offset').evaluate(feature, {}, canonical), layout.get('icon-anchor').evaluate(feature, {}, canonical));
                isSDFIcon = image.sdf;
                if (bucket.sdfIcons === undefined) {
                    bucket.sdfIcons = image.sdf;
                } else if (bucket.sdfIcons !== image.sdf) {
                    warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer');
                }
                if (image.pixelRatio !== bucket.pixelRatio) {
                    bucket.iconsNeedLinear = true;
                } else if (layout.get('icon-rotate').constantOr(1) !== 0) {
                    bucket.iconsNeedLinear = true;
                }
            }
        }
        const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;
        if (!bucket.iconsInText) {
            bucket.iconsInText = shapedText ? shapedText.iconsInText : false;
        }
        if (shapedText || shapedIcon) {
            addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, availableImages, canonical, projection, brightness, hasAnySecondaryIcon);
        }
    }
    if (showCollisionBoxes) {
        bucket.generateCollisionDebugBuffers(tileZoom, bucket.collisionBoxArray);
    }
}
// Choose the justification that matches the direction of the TextAnchor
function getAnchorJustification(anchor) {
    switch (anchor) {
    case 'right':
    case 'top-right':
    case 'bottom-right':
        return 'right';
    case 'left':
    case 'top-left':
    case 'bottom-left':
        return 'left';
    }
    return 'center';
}
/**
 * for "very" overscaled tiles (overscaleFactor > 2) on high zoom levels (z > 18)
 * we use the tile pixel ratio from the previous zoom level and clamp it to 1
 * in order to thin out labels density and save memory and CPU .
 * @private
 */
function tilePixelRatioForSymbolSpacing(overscaleFactor, overscaledZ) {
    if (overscaledZ > 18 && overscaleFactor > 2) {
        overscaleFactor >>= 1;
    }
    const tilePixelRatio = EXTENT / (512 * overscaleFactor);
    return Math.max(tilePixelRatio, 1);
}
/**
 * Given a feature and its shaped text and icon data, add a 'symbol
 * instance' for each _possible_ placement of the symbol feature.
 * (At render time Placement.updateBucketOpacities() selects which of these
 * instances to show or hide based on collisions with symbols in other layers.)
 * @private
 */
function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, availableImages, canonical, projection, brightness, hasAnySecondaryIcon) {
    // To reduce the number of labels that jump around when zooming we need
    // to use a text-size value that is the same for all zoom levels.
    // bucket calculates text-size at a high zoom level so that all tiles can
    // use the same value when calculating anchor positions.
    let textMaxSize = sizes.textMaxSize.evaluate(feature, {}, canonical);
    if (textMaxSize === undefined) {
        textMaxSize = layoutTextSize;
    }
    const layout = bucket.layers[0].layout;
    const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical);
    const defaultShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;
    const isGlobe = projection.name === 'globe';
    const glyphSize = ONE_EM, fontScale = layoutTextSize / glyphSize, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = tilePixelRatioForSymbolSpacing(bucket.overscaling, bucket.zoom) * layout.get('symbol-spacing'), textPadding = layout.get('text-padding') * bucket.tilePixelRatio, iconPadding = layout.get('icon-padding') * bucket.tilePixelRatio, textMaxAngle = degToRad(layout.get('text-max-angle')), textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', symbolPlacement = layout.get('symbol-placement'), textRepeatDistance = symbolMinDistance / 2;
    const iconTextFit = layout.get('icon-text-fit').evaluate(feature, {}, canonical);
    const iconTextFitPadding = layout.get('icon-text-fit-padding').evaluate(feature, {}, canonical);
    const hasIconTextFit = iconTextFit !== 'none';
    if (bucket.hasAnyIconTextFit === false && hasIconTextFit) {
        bucket.hasAnyIconTextFit = true;
    }
    let verticallyShapedIcon;
    // Adjust shaped icon size when icon-text-fit is used.
    if (shapedIcon && hasIconTextFit) {
        if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {
            verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, iconTextFitPadding, iconOffset, fontScale);
        }
        if (defaultShaping) {
            shapedIcon = fitIconToText(shapedIcon, defaultShaping, iconTextFit, iconTextFitPadding, iconOffset, fontScale);
        }
    }
    const addSymbolAtAnchor = (line, anchor, canonicalId) => {
        if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) {
            // Symbol layers are drawn across tile boundaries, We filter out symbols
            // outside our tile boundaries (which may be included in vector tile buffers)
            // to prevent double-drawing symbols.
            return;
        }
        let globe = null;
        if (isGlobe) {
            const {x, y, z} = projection.projectTilePoint(anchor.x, anchor.y, canonicalId);
            globe = {
                anchor: new Anchor(x, y, z, 0, undefined),
                up: projection.upVector(canonicalId, anchor.x, anchor.y)
            };
        }
        addSymbol(bucket, anchor, globe, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, availableImages, canonical, brightness, hasAnySecondaryIcon);
    };
    if (symbolPlacement === 'line') {
        for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) {
            const anchors = getAnchors(line, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT);
            for (const anchor of anchors) {
                const shapedText = defaultShaping;
                if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {
                    addSymbolAtAnchor(line, anchor, canonical);
                }
            }
        }
    } else if (symbolPlacement === 'line-center') {
        // No clipping, multiple lines per feature are allowed
        // "lines" with only one point are ignored as in clipLines
        for (const line of feature.geometry) {
            if (line.length > 1) {
                const anchor = getCenterAnchor(line, textMaxAngle, shapedTextOrientations.vertical || defaultShaping, shapedIcon, glyphSize, textMaxBoxScale);
                if (anchor) {
                    addSymbolAtAnchor(line, anchor, canonical);
                }
            }
        }
    } else if (feature.type === 'Polygon') {
        for (const polygon of classifyRings$1(feature.geometry, 0)) {
            // 16 here represents 2 pixels
            const poi = findPoleOfInaccessibility(polygon, 16);
            addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0, 0, undefined), canonical);
        }
    } else if (feature.type === 'LineString') {
        // https://github.com/mapbox/mapbox-gl-js/issues/3808
        for (const line of feature.geometry) {
            addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0, 0, undefined), canonical);
        }
    } else if (feature.type === 'Point') {
        for (const points of feature.geometry) {
            for (const point of points) {
                addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0, 0, undefined), canonical);
            }
        }
    }
}
const MAX_GLYPH_ICON_SIZE = 255;
const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR;
function addTextVertices(bucket, globe, tileAnchor, shapedText, imageMap, layer, textAlongLine, feature, textOffset, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, availableImages, canonical, brightness) {
    const glyphQuads = getGlyphQuads(tileAnchor, shapedText, textOffset, layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement);
    const sizeData = bucket.textSizeData;
    let textSizeData = null;
    if (sizeData.kind === 'source') {
        textSizeData = [SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}, canonical)];
        if (textSizeData[0] > MAX_PACKED_SIZE) {
            warnOnce(`${ bucket.layerIds[0] }: Value for "text-size" is >= ${ MAX_GLYPH_ICON_SIZE }. Reduce your "text-size".`);
        }
    } else if (sizeData.kind === 'composite') {
        textSizeData = [
            SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical),
            SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)
        ];
        if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {
            warnOnce(`${ bucket.layerIds[0] }: Value for "text-size" is >= ${ MAX_GLYPH_ICON_SIZE }. Reduce your "text-size".`);
        }
    }
    bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, globe, tileAnchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, availableImages, canonical, brightness, false);
    // The placedSymbolArray is used at render time in drawTileSymbols
    // These indices allow access to the array at collision detection time
    for (const placementType of placementTypes) {
        placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1;
    }
    return glyphQuads.length * 4;
}
function getDefaultHorizontalShaping(horizontalShaping) {
    // We don't care which shaping we get because this is used for collision purposes
    // and all the justifications have the same collision box
    for (const justification in horizontalShaping) {
        return horizontalShaping[justification];
    }
    return null;
}
function evaluateBoxCollisionFeature(collisionBoxArray, projectedAnchor, tileAnchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, padding, rotate, textOffset) {
    let y1 = shaped.top;
    let y2 = shaped.bottom;
    let x1 = shaped.left;
    let x2 = shaped.right;
    const collisionPadding = shaped.collisionPadding;
    if (collisionPadding) {
        x1 -= collisionPadding[0];
        y1 -= collisionPadding[1];
        x2 += collisionPadding[2];
        y2 += collisionPadding[3];
    }
    if (rotate) {
        // Account for *-rotate in point collision boxes
        // See https://github.com/mapbox/mapbox-gl-js/issues/6075
        // Doesn't account for icon-text-fit
        const tl = new Point$2(x1, y1);
        const tr = new Point$2(x2, y1);
        const bl = new Point$2(x1, y2);
        const br = new Point$2(x2, y2);
        const rotateRadians = degToRad(rotate);
        let rotateCenter = new Point$2(0, 0);
        if (textOffset) {
            rotateCenter = new Point$2(textOffset[0], textOffset[1]);
        }
        tl._rotateAround(rotateRadians, rotateCenter);
        tr._rotateAround(rotateRadians, rotateCenter);
        bl._rotateAround(rotateRadians, rotateCenter);
        br._rotateAround(rotateRadians, rotateCenter);
        // Collision features require an "on-axis" geometry,
        // so take the envelope of the rotated geometry
        // (may be quite large for wide labels rotated 45 degrees)
        x1 = Math.min(tl.x, tr.x, bl.x, br.x);
        x2 = Math.max(tl.x, tr.x, bl.x, br.x);
        y1 = Math.min(tl.y, tr.y, bl.y, br.y);
        y2 = Math.max(tl.y, tr.y, bl.y, br.y);
    }
    collisionBoxArray.emplaceBack(projectedAnchor.x, projectedAnchor.y, projectedAnchor.z, tileAnchor.x, tileAnchor.y, x1, y1, x2, y2, padding, featureIndex, sourceLayerIndex, bucketIndex);
    return collisionBoxArray.length - 1;
}
function evaluateCircleCollisionFeature(shaped) {
    if (shaped.collisionPadding) {
        // Compute height of the shape in glyph metrics and apply padding.
        // Note that the pixel based 'text-padding' is applied at runtime
        shaped.top -= shaped.collisionPadding[1];
        shaped.bottom += shaped.collisionPadding[3];
    }
    // Set minimum box height to avoid very many small labels
    const height = shaped.bottom - shaped.top;
    return height > 0 ? Math.max(10, height) : null;
}
/**
 * Add a single label & icon placement.
 *
 * @private
 */
function addSymbol(bucket, anchor, globe, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, availableImages, canonical, brightness, hasAnySecondaryIcon) {
    const lineArray = bucket.addToLineVertexArray(anchor, line);
    let textBoxIndex, iconBoxIndex, verticalTextBoxIndex, verticalIconBoxIndex;
    let textCircle, verticalTextCircle, verticalIconCircle;
    let numIconVertices = 0;
    let numVerticalIconVertices = 0;
    let numHorizontalGlyphVertices = 0;
    let numVerticalGlyphVertices = 0;
    let placedIconSymbolIndex = -1;
    let verticalPlacedIconSymbolIndex = -1;
    const placedTextSymbolIndices = {};
    let key = murmur3$1('');
    const collisionFeatureAnchor = globe ? globe.anchor : anchor;
    const hasIconTextFit = layer.layout.get('icon-text-fit').evaluate(feature, {}, canonical) !== 'none';
    let textOffset0 = 0;
    let textOffset1 = 0;
    if (layer._unevaluatedLayout.getValue('text-radial-offset') === undefined) {
        [textOffset0, textOffset1] = layer.layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM);
    } else {
        textOffset0 = layer.layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM;
        textOffset1 = INVALID_TEXT_OFFSET;
    }
    if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {
        const verticalShaping = shapedTextOrientations.vertical;
        if (textAlongLine) {
            verticalTextCircle = evaluateCircleCollisionFeature(verticalShaping);
            if (verticallyShapedIcon) {
                verticalIconCircle = evaluateCircleCollisionFeature(verticallyShapedIcon);
            }
        } else {
            const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);
            const verticalTextRotation = textRotation + 90;
            verticalTextBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textPadding, verticalTextRotation, textOffset);
            if (verticallyShapedIcon) {
                verticalIconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconPadding, verticalTextRotation);
            }
        }
    }
    // Place icon first, so text can have a reference to its index in the placed symbol array.
    // Text symbols can lazily shift at render-time because of variable anchor placement.
    // If the style specifies an `icon-text-fit` then the icon would have to shift along with it.
    // For more info check `updateVariableAnchors` in `draw_symbol.js` .
    if (shapedIcon) {
        const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}, canonical);
        const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit);
        const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined;
        iconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconPadding, iconRotate);
        numIconVertices = iconQuads.length * 4;
        const sizeData = bucket.iconSizeData;
        let iconSizeData = null;
        if (sizeData.kind === 'source') {
            iconSizeData = [SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}, canonical)];
            if (iconSizeData[0] > MAX_PACKED_SIZE) {
                warnOnce(`${ bucket.layerIds[0] }: Value for "icon-size" is >= ${ MAX_GLYPH_ICON_SIZE }. Reduce your "icon-size".`);
            }
        } else if (sizeData.kind === 'composite') {
            iconSizeData = [
                SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical),
                SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)
            ];
            if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {
                warnOnce(`${ bucket.layerIds[0] }: Value for "icon-size" is >= ${ MAX_GLYPH_ICON_SIZE }. Reduce your "icon-size".`);
            }
        }
        bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, false, globe, anchor, lineArray.lineStartIndex, lineArray.lineLength, // The icon itself does not have an associated symbol since the text isnt placed yet
        -1, availableImages, canonical, brightness, hasAnySecondaryIcon);
        placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;
        if (verticalIconQuads) {
            numVerticalIconVertices = verticalIconQuads.length * 4;
            bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, WritingMode.vertical, globe, anchor, lineArray.lineStartIndex, lineArray.lineLength, // The icon itself does not have an associated symbol since the text isnt placed yet
            -1, availableImages, canonical, brightness, hasAnySecondaryIcon);
            verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;
        }
    }
    for (const justification in shapedTextOrientations.horizontal) {
        const shaping = shapedTextOrientations.horizontal[justification];
        if (!textBoxIndex) {
            key = murmur3$1(shaping.text);
            // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature
            // We're counting on all versions having similar dimensions
            if (textAlongLine) {
                textCircle = evaluateCircleCollisionFeature(shaping);
            } else {
                const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);
                textBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textPadding, textRotate, textOffset);
            }
        }
        const singleLine = shaping.positionedLines.length === 1;
        numHorizontalGlyphVertices += addTextVertices(bucket, globe, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, singleLine ? Object.keys(shapedTextOrientations.horizontal) : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, availableImages, canonical, brightness);
        if (singleLine) {
            break;
        }
    }
    if (shapedTextOrientations.vertical) {
        numVerticalGlyphVertices += addTextVertices(bucket, globe, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, availableImages, canonical, brightness);
    }
    // Check if runtime collision circles should be used for any of the collision features.
    // It is enough to choose the tallest feature shape as circles are always placed on a line.
    // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize"
    let collisionCircleDiameter = -1;
    const getCollisionCircleHeight = (diameter, prevHeight) => {
        return diameter ? Math.max(diameter, prevHeight) : prevHeight;
    };
    collisionCircleDiameter = getCollisionCircleHeight(textCircle, collisionCircleDiameter);
    collisionCircleDiameter = getCollisionCircleHeight(verticalTextCircle, collisionCircleDiameter);
    collisionCircleDiameter = getCollisionCircleHeight(verticalIconCircle, collisionCircleDiameter);
    const useRuntimeCollisionCircles = collisionCircleDiameter > -1 ? 1 : 0;
    if (bucket.glyphOffsetArray.length >= SymbolBucket$1.MAX_GLYPHS)
        warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907');
    if (feature.sortKey !== undefined) {
        bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey);
    }
    const projectedAnchor = collisionFeatureAnchor;
    bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, projectedAnchor.x, projectedAnchor.y, projectedAnchor.z, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical >= 0 ? placedTextSymbolIndices.vertical : -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxIndex !== undefined ? textBoxIndex : bucket.collisionBoxArray.length, textBoxIndex !== undefined ? textBoxIndex + 1 : bucket.collisionBoxArray.length, verticalTextBoxIndex !== undefined ? verticalTextBoxIndex : bucket.collisionBoxArray.length, verticalTextBoxIndex !== undefined ? verticalTextBoxIndex + 1 : bucket.collisionBoxArray.length, iconBoxIndex !== undefined ? iconBoxIndex : bucket.collisionBoxArray.length, iconBoxIndex !== undefined ? iconBoxIndex + 1 : bucket.collisionBoxArray.length, verticalIconBoxIndex ? verticalIconBoxIndex : bucket.collisionBoxArray.length, verticalIconBoxIndex ? verticalIconBoxIndex + 1 : bucket.collisionBoxArray.length, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textOffset0, textOffset1, collisionCircleDiameter, 0, hasIconTextFit ? 1 : 0);
}
function anchorIsTooClose(bucket, text, repeatDistance, anchor) {
    const compareText = bucket.compareText;
    if (!(text in compareText)) {
        compareText[text] = [];
    } else {
        const otherAnchors = compareText[text];
        for (let k = otherAnchors.length - 1; k >= 0; k--) {
            if (anchor.dist(otherAnchors[k]) < repeatDistance) {
                // If it's within repeatDistance of one anchor, stop looking
                return true;
            }
        }
    }
    // If anchor is not within repeatDistance of any other anchor, add to array
    compareText[text].push(anchor);
    return false;
}

//      
function farthestPixelDistanceOnPlane(tr, pixelsPerMeter) {
    // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the
    // center top point [width/2 + offset.x, 0] in Z units, using the law of sines.
    // 1 Z unit is equivalent to 1 horizontal px at the center of the map
    // (the distance between[width/2, height/2] and [width/2 + 1, height/2])
    const fovAboveCenter = tr.fovAboveCenter;
    // Adjust distance to MSL by the minimum possible elevation visible on screen,
    // this way the far plane is pushed further in the case of negative elevation.
    const minElevationInPixels = tr.elevation ? tr.elevation.getMinElevationBelowMSL() * pixelsPerMeter : 0;
    const cameraToSeaLevelDistance = (tr._camera.position[2] * tr.worldSize - minElevationInPixels) / Math.cos(tr._pitch);
    const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * cameraToSeaLevelDistance / Math.sin(Math.max(Math.PI / 2 - tr._pitch - fovAboveCenter, 0.01));
    // Calculate z distance of the farthest fragment that should be rendered.
    const furthestDistance = Math.sin(tr._pitch) * topHalfSurfaceDistance + cameraToSeaLevelDistance;
    const horizonDistance = cameraToSeaLevelDistance * (1 / tr._horizonShift);
    // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`
    return Math.min(furthestDistance * 1.01, horizonDistance);
}
function farthestPixelDistanceOnSphere(tr, pixelsPerMeter) {
    // Find farthest distance of the globe that is potentially visible to the camera.
    // First check if the view frustum is fully covered by the map by casting a ray
    // from the top left/right corner and see if it intersects with the globe. In case
    // of no intersection we need to find distance to the horizon point where the
    // surface normal is perpendicular to the camera forward direction.
    const cameraDistance = tr.cameraToCenterDistance;
    const centerPixelAltitude = tr._centerAltitude * pixelsPerMeter;
    const camera = tr._camera;
    const forward = tr._camera.forward();
    const cameraPosition = vec3_1.add([], vec3_1.scale([], forward, -cameraDistance), [
        0,
        0,
        centerPixelAltitude
    ]);
    const globeRadius = tr.worldSize / (2 * Math.PI);
    const globeCenter = [
        0,
        0,
        -globeRadius
    ];
    const aspectRatio = tr.width / tr.height;
    const tanFovAboveCenter = Math.tan(tr.fovAboveCenter);
    const up = vec3_1.scale([], camera.up(), tanFovAboveCenter);
    const right = vec3_1.scale([], camera.right(), tanFovAboveCenter * aspectRatio);
    const dir = vec3_1.normalize([], vec3_1.add([], vec3_1.add([], forward, up), right));
    const pointOnGlobe = [];
    const ray = new Ray(cameraPosition, dir);
    let pixelDistance;
    if (ray.closestPointOnSphere(globeCenter, globeRadius, pointOnGlobe)) {
        const p0 = vec3_1.add([], pointOnGlobe, globeCenter);
        const p1 = vec3_1.sub([], p0, cameraPosition);
        // Globe is fully covering the view frustum. Project the intersection
        // point to the camera view vector in order to find the pixel distance
        pixelDistance = Math.cos(tr.fovAboveCenter) * vec3_1.length(p1);
    } else {
        // Background space is visible. Find distance to the point of the
        // globe where surface normal is parallel to the view vector
        const globeCenterToCamera = vec3_1.sub([], cameraPosition, globeCenter);
        const cameraToGlobe = vec3_1.sub([], globeCenter, cameraPosition);
        vec3_1.normalize(cameraToGlobe, cameraToGlobe);
        const cameraHeight = vec3_1.length(globeCenterToCamera) - globeRadius;
        pixelDistance = Math.sqrt(cameraHeight * (cameraHeight + 2 * globeRadius));
        const angle = Math.acos(pixelDistance / (globeRadius + cameraHeight)) - Math.acos(vec3_1.dot(forward, cameraToGlobe));
        pixelDistance *= Math.cos(angle);
    }
    return pixelDistance * 1.01;
}

//      
function tileTransform(id, projection) {
    if (!projection.isReprojectedInTileSpace) {
        return {
            scale: 1 << id.z,
            x: id.x,
            y: id.y,
            x2: id.x + 1,
            y2: id.y + 1,
            projection
        };
    }
    const s = Math.pow(2, -id.z);
    const x1 = id.x * s;
    const x2 = (id.x + 1) * s;
    const y1 = id.y * s;
    const y2 = (id.y + 1) * s;
    const lng1 = lngFromMercatorX(x1);
    const lng2 = lngFromMercatorX(x2);
    const lat1 = latFromMercatorY(y1);
    const lat2 = latFromMercatorY(y2);
    const p0 = projection.project(lng1, lat1);
    const p1 = projection.project(lng2, lat1);
    const p2 = projection.project(lng2, lat2);
    const p3 = projection.project(lng1, lat2);
    let minX = Math.min(p0.x, p1.x, p2.x, p3.x);
    let minY = Math.min(p0.y, p1.y, p2.y, p3.y);
    let maxX = Math.max(p0.x, p1.x, p2.x, p3.x);
    let maxY = Math.max(p0.y, p1.y, p2.y, p3.y);
    // we pick an error threshold for calculating the bbox that balances between performance and precision
    const maxErr = s / 16;
    function processSegment(pa, pb, ax, ay, bx, by) {
        const mx = (ax + bx) / 2;
        const my = (ay + by) / 2;
        const pm = projection.project(lngFromMercatorX(mx), latFromMercatorY(my));
        const err = Math.max(0, minX - pm.x, minY - pm.y, pm.x - maxX, pm.y - maxY);
        minX = Math.min(minX, pm.x);
        maxX = Math.max(maxX, pm.x);
        minY = Math.min(minY, pm.y);
        maxY = Math.max(maxY, pm.y);
        if (err > maxErr) {
            processSegment(pa, pm, ax, ay, mx, my);
            processSegment(pm, pb, mx, my, bx, by);
        }
    }
    processSegment(p0, p1, x1, y1, x2, y1);
    processSegment(p1, p2, x2, y1, x2, y2);
    processSegment(p2, p3, x2, y2, x1, y2);
    processSegment(p3, p0, x1, y2, x1, y1);
    // extend the bbox by max error to make sure coords don't go past tile extent
    minX -= maxErr;
    minY -= maxErr;
    maxX += maxErr;
    maxY += maxErr;
    const max = Math.max(maxX - minX, maxY - minY);
    const scale = 1 / max;
    return {
        scale,
        x: minX * scale,
        y: minY * scale,
        x2: maxX * scale,
        y2: maxY * scale,
        projection
    };
}
function tileAABB(tr, numTiles, z, x, y, wrap, min, max, projection) {
    if (projection.name === 'globe') {
        const tileId = new CanonicalTileID(z, x, y);
        return aabbForTileOnGlobe(tr, numTiles, tileId, false);
    }
    const tt = tileTransform({
        z,
        x,
        y
    }, projection);
    const tx = tt.x / tt.scale;
    const ty = tt.y / tt.scale;
    const tx2 = tt.x2 / tt.scale;
    const ty2 = tt.y2 / tt.scale;
    return new Aabb([
        (wrap + tx) * numTiles,
        numTiles * ty,
        min
    ], [
        (wrap + tx2) * numTiles,
        numTiles * ty2,
        max
    ]);
}
function getTilePoint(tileTransform, {x, y}, wrap = 0) {
    return new Point$2(((x - wrap) * tileTransform.scale - tileTransform.x) * EXTENT, (y * tileTransform.scale - tileTransform.y) * EXTENT);
}
function getTileVec3(tileTransform, coord, wrap = 0) {
    const x = ((coord.x - wrap) * tileTransform.scale - tileTransform.x) * EXTENT;
    const y = (coord.y * tileTransform.scale - tileTransform.y) * EXTENT;
    return vec3_1.fromValues(x, y, altitudeFromMercatorZ(coord.z, coord.y));
}

//      
const identity = mat4_1.identity(new Float32Array(16));
class Projection {
    constructor(options) {
        this.spec = options;
        this.name = options.name;
        this.wrap = false;
        this.requiresDraping = false;
        this.supportsWorldCopies = false;
        this.supportsTerrain = false;
        this.supportsFog = false;
        this.supportsFreeCamera = false;
        this.zAxisUnit = 'meters';
        this.isReprojectedInTileSpace = true;
        this.unsupportedLayers = ['custom'];
        this.center = [
            0,
            0
        ];
        this.range = [
            3.5,
            7
        ];
    }
    project(lng, lat) {
        // eslint-disable-line
        return {
            x: 0,
            y: 0,
            z: 0
        };    // overriden in subclasses
    }
    unproject(x, y) {
        // eslint-disable-line
        return new LngLat$1(0, 0);    // overriden in subclasses
    }
    projectTilePoint(x, y, _) {
        return {
            x,
            y,
            z: 0
        };
    }
    locationPoint(tr, lngLat, terrain = true) {
        return tr._coordinatePoint(tr.locationCoordinate(lngLat), terrain);
    }
    pixelsPerMeter(lat, worldSize) {
        return mercatorZfromAltitude(1, lat) * worldSize;
    }
    // pixels-per-meter is used to describe relation between real world and pixel distances.
    // `pixelSpaceConversion` can be used to convert the ratio from mercator projection to
    // the currently active projection.
    //
    // `pixelSpaceConversion` is useful for converting between pixel spaces where some logic
    // expects mercator pixels, such as raycasting where the scale is expected to be in
    // mercator pixels.
    pixelSpaceConversion(lat, worldSize, interpolationT) {
        // eslint-disable-line
        return 1;
    }
    farthestPixelDistance(tr) {
        return farthestPixelDistanceOnPlane(tr, tr.pixelsPerMeter);
    }
    pointCoordinate(tr, x, y, z) {
        const horizonOffset = tr.horizonLineFromTop(false);
        const clamped = new Point$2(x, Math.max(horizonOffset, y));
        return tr.rayIntersectionCoordinate(tr.pointRayIntersection(clamped, z));
    }
    pointCoordinate3D(tr, x, y) {
        const p = new Point$2(x, y);
        if (tr.elevation) {
            return tr.elevation.pointCoordinate(p);
        } else {
            const mc = this.pointCoordinate(tr, p.x, p.y, 0);
            return [
                mc.x,
                mc.y,
                mc.z
            ];
        }
    }
    isPointAboveHorizon(tr, p) {
        if (tr.elevation) {
            const raycastOnTerrain = this.pointCoordinate3D(tr, p.x, p.y);
            return !raycastOnTerrain;
        }
        const horizon = tr.horizonLineFromTop();
        return p.y < horizon;
    }
    createInversionMatrix(tr, id) {
        // eslint-disable-line
        return identity;
    }
    createTileMatrix(tr, worldSize, id) {
        let scale, scaledX, scaledY;
        const canonical = id.canonical;
        const posMatrix = mat4_1.identity(new Float64Array(16));
        if (this.isReprojectedInTileSpace) {
            const cs = tileTransform(canonical, this);
            scale = 1;
            scaledX = cs.x + id.wrap * cs.scale;
            scaledY = cs.y;
            mat4_1.scale(posMatrix, posMatrix, [
                scale / cs.scale,
                scale / cs.scale,
                tr.pixelsPerMeter / worldSize
            ]);
        } else {
            scale = worldSize / tr.zoomScale(canonical.z);
            const unwrappedX = canonical.x + Math.pow(2, canonical.z) * id.wrap;
            scaledX = unwrappedX * scale;
            scaledY = canonical.y * scale;
        }
        mat4_1.translate(posMatrix, posMatrix, [
            scaledX,
            scaledY,
            0
        ]);
        mat4_1.scale(posMatrix, posMatrix, [
            scale / EXTENT,
            scale / EXTENT,
            1
        ]);
        return posMatrix;
    }
    upVector(id, x, y) {
        // eslint-disable-line
        return [
            0,
            0,
            1
        ];
    }
    upVectorScale(id, latitude, worldSize) {
        // eslint-disable-line
        return { metersToTile: 1 };
    }
}

//      
// based on https://github.com/d3/d3-geo-projection, MIT-licensed
class Albers extends Projection {
    constructor(options) {
        super(options);
        this.range = [
            4,
            7
        ];
        this.center = options.center || [
            -96,
            37.5
        ];
        const [lat0, lat1] = this.parallels = options.parallels || [
            29.5,
            45.5
        ];
        const sy0 = Math.sin(degToRad(lat0));
        this.n = (sy0 + Math.sin(degToRad(lat1))) / 2;
        this.c = 1 + sy0 * (2 * this.n - sy0);
        this.r0 = Math.sqrt(this.c) / this.n;
    }
    project(lng, lat) {
        const {n, c, r0} = this;
        const lambda = degToRad(lng - this.center[0]);
        const phi = degToRad(lat);
        const r = Math.sqrt(c - 2 * n * Math.sin(phi)) / n;
        const x = r * Math.sin(lambda * n);
        const y = r * Math.cos(lambda * n) - r0;
        return {
            x,
            y,
            z: 0
        };
    }
    unproject(x, y) {
        const {n, c, r0} = this;
        const r0y = r0 + y;
        let l = Math.atan2(x, Math.abs(r0y)) * Math.sign(r0y);
        if (r0y * n < 0) {
            l -= Math.PI * Math.sign(x) * Math.sign(r0y);
        }
        const dt = degToRad(this.center[0]) * n;
        l = wrap$1(l, -Math.PI - dt, Math.PI - dt);
        const lng = clamp(radToDeg(l / n) + this.center[0], -180, 180);
        const phi = Math.asin(clamp((c - (x * x + r0y * r0y) * n * n) / (2 * n), -1, 1));
        const lat = clamp(radToDeg(phi), -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
        return new LngLat$1(lng, lat);
    }
}

//      
const a1 = 1.340264;
const a2 = -0.081106;
const a3 = 0.000893;
const a4 = 0.003796;
const M = Math.sqrt(3) / 2;
class EqualEarth extends Projection {
    project(lng, lat) {
        // based on https://github.com/d3/d3-geo, MIT-licensed
        lat = lat / 180 * Math.PI;
        lng = lng / 180 * Math.PI;
        const theta = Math.asin(M * Math.sin(lat));
        const theta2 = theta * theta;
        const theta6 = theta2 * theta2 * theta2;
        const x = lng * Math.cos(theta) / (M * (a1 + 3 * a2 * theta2 + theta6 * (7 * a3 + 9 * a4 * theta2)));
        const y = theta * (a1 + a2 * theta2 + theta6 * (a3 + a4 * theta2));
        return {
            x: (x / Math.PI + 0.5) * 0.5,
            y: 1 - (y / Math.PI + 1) * 0.5,
            z: 0
        };
    }
    unproject(x, y) {
        // based on https://github.com/d3/d3-geo, MIT-licensed
        x = (2 * x - 0.5) * Math.PI;
        y = (2 * (1 - y) - 1) * Math.PI;
        let theta = y;
        let theta2 = theta * theta;
        let theta6 = theta2 * theta2 * theta2;
        for (let i = 0, delta, fy, fpy; i < 12; ++i) {
            fy = theta * (a1 + a2 * theta2 + theta6 * (a3 + a4 * theta2)) - y;
            fpy = a1 + 3 * a2 * theta2 + theta6 * (7 * a3 + 9 * a4 * theta2);
            delta = fy / fpy;
            theta = clamp(theta - delta, -Math.PI / 3, Math.PI / 3);
            theta2 = theta * theta;
            theta6 = theta2 * theta2 * theta2;
            if (Math.abs(delta) < 1e-12)
                break;
        }
        const lambda = M * x * (a1 + 3 * a2 * theta2 + theta6 * (7 * a3 + 9 * a4 * theta2)) / Math.cos(theta);
        const phi = Math.asin(Math.sin(theta) / M);
        const lng = clamp(lambda * 180 / Math.PI, -180, 180);
        const lat = clamp(phi * 180 / Math.PI, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
        return new LngLat$1(lng, lat);
    }
}

//      
class Equirectangular extends Projection {
    constructor(options) {
        super(options);
        this.wrap = true;
        this.supportsWorldCopies = true;
    }
    project(lng, lat) {
        const x = 0.5 + lng / 360;
        const y = 0.5 - lat / 360;
        return {
            x,
            y,
            z: 0
        };
    }
    unproject(x, y) {
        const lng = (x - 0.5) * 360;
        const lat = clamp((0.5 - y) * 360, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
        return new LngLat$1(lng, lat);
    }
}

//      
const halfPi = Math.PI / 2;
function tany(y) {
    return Math.tan((halfPi + y) / 2);
}
// based on https://github.com/d3/d3-geo, MIT-licensed
class LambertConformalConic extends Projection {
    constructor(options) {
        super(options);
        this.center = options.center || [
            0,
            30
        ];
        const [lat0, lat1] = this.parallels = options.parallels || [
            30,
            30
        ];
        let y0 = degToRad(lat0);
        let y1 = degToRad(lat1);
        // Run projection math on inverted lattitudes if the paralell lines are south of the equator
        // This fixes divide by zero errors with a South polar projection
        this.southernCenter = y0 + y1 < 0;
        if (this.southernCenter) {
            y0 = -y0;
            y1 = -y1;
        }
        const cy0 = Math.cos(y0);
        const tany0 = tany(y0);
        this.n = y0 === y1 ? Math.sin(y0) : Math.log(cy0 / Math.cos(y1)) / Math.log(tany(y1) / tany0);
        this.f = cy0 * Math.pow(tany(y0), this.n) / this.n;
    }
    project(lng, lat) {
        lat = degToRad(lat);
        if (this.southernCenter)
            lat = -lat;
        lng = degToRad(lng - this.center[0]);
        const epsilon = 0.000001;
        const {n, f} = this;
        if (f > 0) {
            if (lat < -halfPi + epsilon)
                lat = -halfPi + epsilon;
        } else {
            if (lat > halfPi - epsilon)
                lat = halfPi - epsilon;
        }
        const r = f / Math.pow(tany(lat), n);
        let x = r * Math.sin(n * lng);
        let y = f - r * Math.cos(n * lng);
        x = (x / Math.PI + 0.5) * 0.5;
        y = (y / Math.PI + 0.5) * 0.5;
        return {
            x,
            y: this.southernCenter ? y : 1 - y,
            z: 0
        };
    }
    unproject(x, y) {
        x = (2 * x - 0.5) * Math.PI;
        if (this.southernCenter)
            y = 1 - y;
        y = (2 * (1 - y) - 0.5) * Math.PI;
        const {n, f} = this;
        const fy = f - y;
        const signFy = Math.sign(fy);
        const r = Math.sign(n) * Math.sqrt(x * x + fy * fy);
        let l = Math.atan2(x, Math.abs(fy)) * signFy;
        if (fy * n < 0)
            l -= Math.PI * Math.sign(x) * signFy;
        const lng = clamp(radToDeg(l / n) + this.center[0], -180, 180);
        const phi = 2 * Math.atan(Math.pow(f / r, 1 / n)) - halfPi;
        const lat = clamp(radToDeg(phi), -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
        return new LngLat$1(lng, this.southernCenter ? -lat : lat);
    }
}

//      
class Mercator extends Projection {
    constructor(options) {
        super(options);
        this.wrap = true;
        this.supportsWorldCopies = true;
        this.supportsTerrain = true;
        this.supportsFog = true;
        this.supportsFreeCamera = true;
        this.isReprojectedInTileSpace = false;
        this.unsupportedLayers = [];
        this.range = null;
    }
    project(lng, lat) {
        const x = mercatorXfromLng(lng);
        const y = mercatorYfromLat(lat);
        return {
            x,
            y,
            z: 0
        };
    }
    unproject(x, y) {
        const lng = lngFromMercatorX(x);
        const lat = latFromMercatorY(y);
        return new LngLat$1(lng, lat);
    }
}

//      
const maxPhi$1 = degToRad(MAX_MERCATOR_LATITUDE);
class NaturalEarth extends Projection {
    project(lng, lat) {
        // based on https://github.com/d3/d3-geo, MIT-licensed
        lat = degToRad(lat);
        lng = degToRad(lng);
        const phi2 = lat * lat;
        const phi4 = phi2 * phi2;
        const x = lng * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4)));
        const y = lat * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)));
        return {
            x: (x / Math.PI + 0.5) * 0.5,
            y: 1 - (y / Math.PI + 1) * 0.5,
            z: 0
        };
    }
    unproject(x, y) {
        // based on https://github.com/d3/d3-geo, MIT-licensed
        x = (2 * x - 0.5) * Math.PI;
        y = (2 * (1 - y) - 1) * Math.PI;
        const epsilon = 0.000001;
        let phi = y;
        let i = 25;
        let delta = 0;
        let phi2 = phi * phi;
        do {
            phi2 = phi * phi;
            const phi4 = phi2 * phi2;
            delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) / (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));
            phi = clamp(phi - delta, -maxPhi$1, maxPhi$1);
        } while (Math.abs(delta) > epsilon && --i > 0);
        phi2 = phi * phi;
        const lambda = x / (0.8707 + phi2 * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2))));
        const lng = clamp(radToDeg(lambda), -180, 180);
        const lat = radToDeg(phi);
        return new LngLat$1(lng, lat);
    }
}

//      
const maxPhi = degToRad(MAX_MERCATOR_LATITUDE);
class WinkelTripel extends Projection {
    project(lng, lat) {
        lat = degToRad(lat);
        lng = degToRad(lng);
        const cosLat = Math.cos(lat);
        const twoOverPi = 2 / Math.PI;
        const alpha = Math.acos(cosLat * Math.cos(lng / 2));
        const sinAlphaOverAlpha = Math.sin(alpha) / alpha;
        const x = 0.5 * (lng * twoOverPi + 2 * cosLat * Math.sin(lng / 2) / sinAlphaOverAlpha) || 0;
        const y = 0.5 * (lat + Math.sin(lat) / sinAlphaOverAlpha) || 0;
        return {
            x: (x / Math.PI + 0.5) * 0.5,
            y: 1 - (y / Math.PI + 1) * 0.5,
            z: 0
        };
    }
    unproject(x, y) {
        // based on https://github.com/d3/d3-geo-projection, MIT-licensed
        x = (2 * x - 0.5) * Math.PI;
        y = (2 * (1 - y) - 1) * Math.PI;
        let lambda = x;
        let phi = y;
        let i = 25;
        const epsilon = 0.000001;
        let dlambda = 0, dphi = 0;
        do {
            const cosphi = Math.cos(phi), sinphi = Math.sin(phi), sinphi2 = 2 * sinphi * cosphi, sin2phi = sinphi * sinphi, cos2phi = cosphi * cosphi, coslambda2 = Math.cos(lambda / 2), sinlambda2 = Math.sin(lambda / 2), sinlambda = 2 * coslambda2 * sinlambda2, sin2lambda2 = sinlambda2 * sinlambda2, C = 1 - cos2phi * coslambda2 * coslambda2, F = C ? 1 / C : 0, E = C ? Math.acos(cosphi * coslambda2) * Math.sqrt(1 / C) : 0, fx = 0.5 * (2 * E * cosphi * sinlambda2 + lambda * 2 / Math.PI) - x, fy = 0.5 * (E * sinphi + phi) - y, dxdlambda = 0.5 * F * (cos2phi * sin2lambda2 + E * cosphi * coslambda2 * sin2phi) + 1 / Math.PI, dxdphi = F * (sinlambda * sinphi2 / 4 - E * sinphi * sinlambda2), dydlambda = 0.125 * F * (sinphi2 * sinlambda2 - E * sinphi * cos2phi * sinlambda), dydphi = 0.5 * F * (sin2phi * coslambda2 + E * sin2lambda2 * cosphi) + 0.5, denominator = dxdphi * dydlambda - dydphi * dxdlambda;
            dlambda = (fy * dxdphi - fx * dydphi) / denominator;
            dphi = (fx * dydlambda - fy * dxdlambda) / denominator;
            lambda = clamp(lambda - dlambda, -Math.PI, Math.PI);
            phi = clamp(phi - dphi, -maxPhi, maxPhi);
        } while ((Math.abs(dlambda) > epsilon || Math.abs(dphi) > epsilon) && --i > 0);
        return new LngLat$1(radToDeg(lambda), radToDeg(phi));
    }
}

//      
class CylindricalEqualArea extends Projection {
    constructor(options) {
        super(options);
        this.center = options.center || [
            0,
            0
        ];
        this.parallels = options.parallels || [
            0,
            0
        ];
        this.cosPhi = Math.max(0.01, Math.cos(degToRad(this.parallels[0])));
        // scale coordinates between 0 and 1 to avoid constraint issues
        this.scale = 1 / (2 * Math.max(Math.PI * this.cosPhi, 1 / this.cosPhi));
        this.wrap = true;
        this.supportsWorldCopies = true;
    }
    project(lng, lat) {
        const {scale, cosPhi} = this;
        const x = degToRad(lng) * cosPhi;
        const y = Math.sin(degToRad(lat)) / cosPhi;
        return {
            x: x * scale + 0.5,
            y: -y * scale + 0.5,
            z: 0
        };
    }
    unproject(x, y) {
        const {scale, cosPhi} = this;
        const x_ = (x - 0.5) / scale;
        const y_ = -(y - 0.5) / scale;
        const lng = clamp(radToDeg(x_) / cosPhi, -180, 180);
        const y2 = y_ * cosPhi;
        const y3 = Math.asin(clamp(y2, -1, 1));
        const lat = clamp(radToDeg(y3), -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
        return new LngLat$1(lng, lat);
    }
}

//      
class Globe extends Mercator {
    constructor(options) {
        super(options);
        this.requiresDraping = true;
        this.supportsWorldCopies = false;
        this.supportsFog = true;
        this.zAxisUnit = 'pixels';
        this.unsupportedLayers = ['debug'];
        this.range = [
            3,
            5
        ];
    }
    projectTilePoint(x, y, id) {
        const pos = tileCoordToECEF(x, y, id);
        const bounds = globeTileBounds(id);
        const normalizationMatrix = globeNormalizeECEF(bounds);
        vec3_1.transformMat4(pos, pos, normalizationMatrix);
        return {
            x: pos[0],
            y: pos[1],
            z: pos[2]
        };
    }
    locationPoint(tr, lngLat) {
        const pos = latLngToECEF(lngLat.lat, lngLat.lng);
        const up = vec3_1.normalize([], pos);
        const elevation = tr.elevation ? tr.elevation.getAtPointOrZero(tr.locationCoordinate(lngLat), tr._centerAltitude) : tr._centerAltitude;
        const upScale = mercatorZfromAltitude(1, 0) * EXTENT * elevation;
        vec3_1.scaleAndAdd(pos, pos, up, upScale);
        const matrix = mat4_1.identity(new Float64Array(16));
        mat4_1.multiply(matrix, tr.pixelMatrix, tr.globeMatrix);
        vec3_1.transformMat4(pos, pos, matrix);
        return new Point$2(pos[0], pos[1]);
    }
    pixelsPerMeter(lat, worldSize) {
        return mercatorZfromAltitude(1, 0) * worldSize;
    }
    pixelSpaceConversion(lat, worldSize, interpolationT) {
        // Using only the center latitude to determine scale causes the globe to rapidly change
        // size as you pan up and down. As you approach the pole, the globe's size approaches infinity.
        // This is because zoom levels are based on mercator.
        //
        // Instead, use a fixed reference latitude at lower zoom levels. And transition between
        // this latitude and the center's latitude as you zoom in. This is a compromise that
        // makes globe view more usable with existing camera parameters, styles and data.
        const centerScale = mercatorZfromAltitude(1, lat) * worldSize;
        const referenceScale = mercatorZfromAltitude(1, GLOBE_SCALE_MATCH_LATITUDE) * worldSize;
        const combinedScale = number(referenceScale, centerScale, interpolationT);
        return this.pixelsPerMeter(lat, worldSize) / combinedScale;
    }
    createTileMatrix(tr, worldSize, id) {
        const decode = globeDenormalizeECEF(globeTileBounds(id.canonical));
        return mat4_1.multiply(new Float64Array(16), tr.globeMatrix, decode);
    }
    createInversionMatrix(tr, id) {
        const {center} = tr;
        const matrix = globeNormalizeECEF(globeTileBounds(id));
        mat4_1.rotateY(matrix, matrix, degToRad(center.lng));
        mat4_1.rotateX(matrix, matrix, degToRad(center.lat));
        mat4_1.scale(matrix, matrix, [
            tr._pixelsPerMercatorPixel,
            tr._pixelsPerMercatorPixel,
            1
        ]);
        return Float32Array.from(matrix);
    }
    pointCoordinate(tr, x, y, _) {
        const coord = globePointCoordinate(tr, x, y, true);
        if (!coord) {
            return new MercatorCoordinate(0, 0);
        }
        // This won't happen, is here for Flow
        return coord;
    }
    pointCoordinate3D(tr, x, y) {
        const coord = this.pointCoordinate(tr, x, y, 0);
        return [
            coord.x,
            coord.y,
            coord.z
        ];
    }
    isPointAboveHorizon(tr, p) {
        const raycastOnGlobe = globePointCoordinate(tr, p.x, p.y, false);
        return !raycastOnGlobe;
    }
    farthestPixelDistance(tr) {
        const pixelsPerMeter = this.pixelsPerMeter(tr.center.lat, tr.worldSize);
        const globePixelDistance = farthestPixelDistanceOnSphere(tr, pixelsPerMeter);
        const t = globeToMercatorTransition(tr.zoom);
        if (t > 0) {
            const mercatorPixelsPerMeter = mercatorZfromAltitude(1, tr.center.lat) * tr.worldSize;
            const mercatorPixelDistance = farthestPixelDistanceOnPlane(tr, mercatorPixelsPerMeter);
            const pixelRadius = tr.worldSize / (2 * Math.PI);
            const approxTileArcHalfAngle = Math.max(tr.width, tr.height) / tr.worldSize * Math.PI;
            const padding = pixelRadius * (1 - Math.cos(approxTileArcHalfAngle));
            // During transition to mercator we would like to keep
            // the far plane lower to ensure that geometries (e.g. circles) that are far away and are not supposed
            // to be rendered get culled out correctly. see https://github.com/mapbox/mapbox-gl-js/issues/11476
            // To achieve this we dampen the interpolation.
            return number(globePixelDistance, mercatorPixelDistance + padding, Math.pow(t, 10));
        }
        return globePixelDistance;
    }
    upVector(id, x, y) {
        return tileCoordToECEF(x, y, id, 1);
    }
    upVectorScale(id) {
        return { metersToTile: globeMetersToEcef(globeECEFNormalizationScale(globeTileBounds(id))) };
    }
}

//      
function getProjection(config) {
    const parallels = config.parallels;
    const isDegenerateConic = parallels ? Math.abs(parallels[0] + parallels[1]) < 0.01 : false;
    switch (config.name) {
    case 'mercator':
        return new Mercator(config);
    case 'equirectangular':
        return new Equirectangular(config);
    case 'naturalEarth':
        return new NaturalEarth(config);
    case 'equalEarth':
        return new EqualEarth(config);
    case 'winkelTripel':
        return new WinkelTripel(config);
    case 'albers':
        return isDegenerateConic ? new CylindricalEqualArea(config) : new Albers(config);
    case 'lambertConformalConic':
        return isDegenerateConic ? new CylindricalEqualArea(config) : new LambertConformalConic(config);
    case 'globe':
        return new Globe(config);
    }
    throw new Error(`Invalid projection name: ${ config.name }`);
}

//      
/**
 * Replace tokens in a string template with values in an object
 *
 * @param properties a key/value relationship between tokens and replacements
 * @param text the template string
 * @returns the template with tokens replaced
 * @private
 */
function resolveTokens(properties, text) {
    return text.replace(/{([^{}]+)}/g, (match, key) => {
        return key in properties ? String(properties[key]) : '';
    });
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$6 = new Properties({
    'symbol-placement': new DataConstantProperty(spec['layout_symbol']['symbol-placement']),
    'symbol-spacing': new DataConstantProperty(spec['layout_symbol']['symbol-spacing']),
    'symbol-avoid-edges': new DataConstantProperty(spec['layout_symbol']['symbol-avoid-edges']),
    'symbol-sort-key': new DataDrivenProperty(spec['layout_symbol']['symbol-sort-key']),
    'symbol-z-order': new DataConstantProperty(spec['layout_symbol']['symbol-z-order']),
    'symbol-z-elevate': new DataConstantProperty(spec['layout_symbol']['symbol-z-elevate']),
    'icon-allow-overlap': new DataConstantProperty(spec['layout_symbol']['icon-allow-overlap']),
    'icon-ignore-placement': new DataConstantProperty(spec['layout_symbol']['icon-ignore-placement']),
    'icon-optional': new DataConstantProperty(spec['layout_symbol']['icon-optional']),
    'icon-rotation-alignment': new DataConstantProperty(spec['layout_symbol']['icon-rotation-alignment']),
    'icon-size': new DataDrivenProperty(spec['layout_symbol']['icon-size']),
    'icon-text-fit': new DataDrivenProperty(spec['layout_symbol']['icon-text-fit']),
    'icon-text-fit-padding': new DataDrivenProperty(spec['layout_symbol']['icon-text-fit-padding']),
    'icon-image': new DataDrivenProperty(spec['layout_symbol']['icon-image']),
    'icon-rotate': new DataDrivenProperty(spec['layout_symbol']['icon-rotate']),
    'icon-padding': new DataConstantProperty(spec['layout_symbol']['icon-padding']),
    'icon-keep-upright': new DataConstantProperty(spec['layout_symbol']['icon-keep-upright']),
    'icon-offset': new DataDrivenProperty(spec['layout_symbol']['icon-offset']),
    'icon-anchor': new DataDrivenProperty(spec['layout_symbol']['icon-anchor']),
    'icon-pitch-alignment': new DataConstantProperty(spec['layout_symbol']['icon-pitch-alignment']),
    'text-pitch-alignment': new DataConstantProperty(spec['layout_symbol']['text-pitch-alignment']),
    'text-rotation-alignment': new DataConstantProperty(spec['layout_symbol']['text-rotation-alignment']),
    'text-field': new DataDrivenProperty(spec['layout_symbol']['text-field']),
    'text-font': new DataDrivenProperty(spec['layout_symbol']['text-font']),
    'text-size': new DataDrivenProperty(spec['layout_symbol']['text-size']),
    'text-max-width': new DataDrivenProperty(spec['layout_symbol']['text-max-width']),
    'text-line-height': new DataDrivenProperty(spec['layout_symbol']['text-line-height']),
    'text-letter-spacing': new DataDrivenProperty(spec['layout_symbol']['text-letter-spacing']),
    'text-justify': new DataDrivenProperty(spec['layout_symbol']['text-justify']),
    'text-radial-offset': new DataDrivenProperty(spec['layout_symbol']['text-radial-offset']),
    'text-variable-anchor': new DataConstantProperty(spec['layout_symbol']['text-variable-anchor']),
    'text-anchor': new DataDrivenProperty(spec['layout_symbol']['text-anchor']),
    'text-max-angle': new DataConstantProperty(spec['layout_symbol']['text-max-angle']),
    'text-writing-mode': new DataConstantProperty(spec['layout_symbol']['text-writing-mode']),
    'text-rotate': new DataDrivenProperty(spec['layout_symbol']['text-rotate']),
    'text-padding': new DataConstantProperty(spec['layout_symbol']['text-padding']),
    'text-keep-upright': new DataConstantProperty(spec['layout_symbol']['text-keep-upright']),
    'text-transform': new DataDrivenProperty(spec['layout_symbol']['text-transform']),
    'text-offset': new DataDrivenProperty(spec['layout_symbol']['text-offset']),
    'text-allow-overlap': new DataConstantProperty(spec['layout_symbol']['text-allow-overlap']),
    'text-ignore-placement': new DataConstantProperty(spec['layout_symbol']['text-ignore-placement']),
    'text-optional': new DataConstantProperty(spec['layout_symbol']['text-optional']),
    'visibility': new DataConstantProperty(spec['layout_symbol']['visibility'])
});
const paint$7 = new Properties({
    'icon-opacity': new DataDrivenProperty(spec['paint_symbol']['icon-opacity']),
    'icon-emissive-strength': new DataDrivenProperty(spec['paint_symbol']['icon-emissive-strength']),
    'text-emissive-strength': new DataDrivenProperty(spec['paint_symbol']['text-emissive-strength']),
    'icon-color': new DataDrivenProperty(spec['paint_symbol']['icon-color']),
    'icon-halo-color': new DataDrivenProperty(spec['paint_symbol']['icon-halo-color']),
    'icon-halo-width': new DataDrivenProperty(spec['paint_symbol']['icon-halo-width']),
    'icon-halo-blur': new DataDrivenProperty(spec['paint_symbol']['icon-halo-blur']),
    'icon-translate': new DataConstantProperty(spec['paint_symbol']['icon-translate']),
    'icon-translate-anchor': new DataConstantProperty(spec['paint_symbol']['icon-translate-anchor']),
    'icon-image-cross-fade': new DataDrivenProperty(spec['paint_symbol']['icon-image-cross-fade']),
    'text-opacity': new DataDrivenProperty(spec['paint_symbol']['text-opacity']),
    'text-color': new DataDrivenProperty(spec['paint_symbol']['text-color'], {
        runtimeType: ColorType,
        getOverride: o => o.textColor,
        hasOverride: o => !!o.textColor
    }),
    'text-halo-color': new DataDrivenProperty(spec['paint_symbol']['text-halo-color']),
    'text-halo-width': new DataDrivenProperty(spec['paint_symbol']['text-halo-width']),
    'text-halo-blur': new DataDrivenProperty(spec['paint_symbol']['text-halo-blur']),
    'text-translate': new DataConstantProperty(spec['paint_symbol']['text-translate']),
    'text-translate-anchor': new DataConstantProperty(spec['paint_symbol']['text-translate-anchor'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$b = {
    paint: paint$7,
    layout: layout$6
};

// This is an internal expression class. It is only used in GL JS and
// has GL JS dependencies which can break the standalone style-spec module
class FormatSectionOverride {
    constructor(defaultValue) {
        this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType;
        this.defaultValue = defaultValue;
    }
    evaluate(ctx) {
        if (ctx.formattedSection) {
            const overrides = this.defaultValue.property.overrides;
            if (overrides && overrides.hasOverride(ctx.formattedSection)) {
                return overrides.getOverride(ctx.formattedSection);
            }
        }
        if (ctx.feature && ctx.featureState) {
            return this.defaultValue.evaluate(ctx.feature, ctx.featureState);
        }
        // not sure how to make Flow refine the type properly here — will need investigation
        return this.defaultValue.property.specification.default;
    }
    eachChild(fn) {
        if (!this.defaultValue.isConstant()) {
            const expr = this.defaultValue.value;
            fn(expr._styleExpression.expression);
        }
    }
    // Cannot be statically evaluated, as the output depends on the evaluation context.
    outputDefined() {
        return false;
    }
    serialize() {
        return null;
    }
}
register(FormatSectionOverride, 'FormatSectionOverride', { omit: ['defaultValue'] });

//      
class SymbolStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$b, options);
    }
    recalculate(parameters, availableImages) {
        super.recalculate(parameters, availableImages);
        if (this.layout.get('icon-rotation-alignment') === 'auto') {
            if (this.layout.get('symbol-placement') !== 'point') {
                this.layout._values['icon-rotation-alignment'] = 'map';
            } else {
                this.layout._values['icon-rotation-alignment'] = 'viewport';
            }
        }
        if (this.layout.get('text-rotation-alignment') === 'auto') {
            if (this.layout.get('symbol-placement') !== 'point') {
                this.layout._values['text-rotation-alignment'] = 'map';
            } else {
                this.layout._values['text-rotation-alignment'] = 'viewport';
            }
        }
        // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment`
        if (this.layout.get('text-pitch-alignment') === 'auto') {
            this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment');
        }
        if (this.layout.get('icon-pitch-alignment') === 'auto') {
            this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment');
        }
        const writingModes = this.layout.get('text-writing-mode');
        if (writingModes) {
            // remove duplicates, preserving order
            const deduped = [];
            for (const m of writingModes) {
                if (deduped.indexOf(m) < 0)
                    deduped.push(m);
            }
            this.layout._values['text-writing-mode'] = deduped;
        } else if (this.layout.get('symbol-placement') === 'point') {
            // default value for 'point' placement symbols
            this.layout._values['text-writing-mode'] = ['horizontal'];
        } else {
            // default value for 'line' placement symbols
            this.layout._values['text-writing-mode'] = [
                'horizontal',
                'vertical'
            ];
        }
        this._setPaintOverrides();
    }
    getValueAndResolveTokens(name, feature, canonical, availableImages) {
        const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages);
        const unevaluated = this._unevaluatedLayout._values[name];
        if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) {
            return resolveTokens(feature.properties, value);
        }
        return value;
    }
    createBucket(parameters) {
        return new SymbolBucket$1(parameters);
    }
    // $FlowFixMe[method-unbinding]
    queryRadius() {
        return 0;
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature() {
        // Should take a different path in FeatureIndex
        return false;
    }
    _setPaintOverrides() {
        for (const overridable of properties$b.paint.overridableProperties) {
            if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) {
                continue;
            }
            const overriden = this.paint.get(overridable);
            const override = new FormatSectionOverride(overriden);
            const styleExpression = new StyleExpression(override, overriden.property.specification);
            let expression = null;
            // eslint-disable-next-line no-warning-comments
            // TODO: check why were the `isLightConstant` values omitted from the construction of these expressions
            if (overriden.value.kind === 'constant' || overriden.value.kind === 'source') {
                // $FlowFixMe[method-unbinding]
                expression = new ZoomConstantExpression('source', styleExpression);
            } else {
                // $FlowFixMe[method-unbinding]
                expression = new ZoomDependentExpression('composite', styleExpression, overriden.value.zoomStops, overriden.value._interpolationType);
            }
            // $FlowFixMe[prop-missing]
            this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property, expression, overriden.parameters);
        }
    }
    _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) {
        if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {
            return false;
        }
        return SymbolStyleLayer.hasPaintOverride(this.layout, name);
    }
    static hasPaintOverride(layout, propertyName) {
        const textField = layout.get('text-field');
        const property = properties$b.paint.properties[propertyName];
        let hasOverrides = false;
        const checkSections = sections => {
            for (const section of sections) {
                if (property.overrides && property.overrides.hasOverride(section)) {
                    hasOverrides = true;
                    return;
                }
            }
        };
        if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) {
            checkSections(textField.value.value.sections);
        } else if (textField.value.kind === 'source') {
            const checkExpression = expression => {
                if (hasOverrides)
                    return;
                if (expression instanceof Literal$1 && typeOf(expression.value) === FormattedType) {
                    const formatted = expression.value;
                    checkSections(formatted.sections);
                } else if (expression instanceof FormatExpression) {
                    checkSections(expression.sections);
                } else {
                    expression.eachChild(checkExpression);
                }
            };
            const expr = textField.value;
            if (expr._styleExpression) {
                checkExpression(expr._styleExpression.expression);
            }
        }
        return hasOverrides;
    }
    getProgramIds() {
        const hasIcon = this.paint.get('icon-opacity').constantOr(1) !== 0;
        const hasText = this.paint.get('text-opacity').constantOr(1) !== 0;
        const ids = [];
        if (hasIcon) {
            ids.push('symbolIcon');
        }
        if (hasText) {
            ids.push('symbolSDF');
        }
        return ids;
    }
    getDefaultProgramParams(name, zoom) {
        return {
            config: new ProgramConfiguration(this, zoom),
            overrideFog: false
        };
    }
}

//      
const vectorTileFeatureTypes$2 = VectorTileFeature.types;
// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them
// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph
// 7 bits are for the current opacity, and the lowest bit is the target opacity
// actually defined in symbol_attributes.js
// const placementOpacityAttributes = [
//     { name: 'a_fade_opacity', components: 1, type: 'Uint32' }
// ];
const shaderOpacityAttributes = [{
        name: 'a_fade_opacity',
        components: 1,
        type: 'Uint8',
        offset: 0
    }];
function addVertex$2(array, tileAnchorX, tileAnchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) {
    const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;
    const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;
    array.emplaceBack(// a_pos_offset
    tileAnchorX, tileAnchorY, Math.round(ox * 32), Math.round(oy * 32), // a_data
    tx, // x coordinate of symbol on glyph atlas texture
    ty, // y coordinate of symbol on glyph atlas texture
    (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256);
}
function addTransitioningVertex(array, tx, ty) {
    array.emplaceBack(tx, ty);
}
function addGlobeVertex(array, projAnchorX, projAnchorY, projAnchorZ, normX, normY, normZ) {
    array.emplaceBack(// a_globe_anchor
    projAnchorX, projAnchorY, projAnchorZ, // a_globe_normal
    normX, normY, normZ);
}
function updateGlobeVertexNormal(array, vertexIdx, normX, normY, normZ) {
    // Modify float32 array directly. 20 bytes per entry, 3xInt16 for position, 3xfloat32 for normal
    const offset = vertexIdx * 5 + 2;
    array.float32[offset + 0] = normX;
    array.float32[offset + 1] = normY;
    array.float32[offset + 2] = normZ;
}
function addDynamicAttributes(dynamicLayoutVertexArray, x, y, z, angle) {
    dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);
    dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);
    dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);
    dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);
}
function containsRTLText(formattedText) {
    for (const section of formattedText.sections) {
        if (stringContainsRTLText(section.text)) {
            return true;
        }
    }
    return false;
}
class SymbolBuffers {
    constructor(programConfigurations) {
        this.layoutVertexArray = new StructArrayLayout4i4ui4i24();
        this.indexArray = new StructArrayLayout3ui6();
        this.programConfigurations = programConfigurations;
        this.segments = new SegmentVector();
        this.dynamicLayoutVertexArray = new StructArrayLayout4f16();
        this.opacityVertexArray = new StructArrayLayout1ul4();
        this.placedSymbolArray = new PlacedSymbolArray();
        this.iconTransitioningVertexArray = new StructArrayLayout2ui4();
        this.globeExtVertexArray = new StructArrayLayout3i3f20();
        this.zOffsetVertexArray = new StructArrayLayout1f4();
    }
    isEmpty() {
        return this.layoutVertexArray.length === 0 && this.indexArray.length === 0 && this.dynamicLayoutVertexArray.length === 0 && this.opacityVertexArray.length === 0 && this.iconTransitioningVertexArray.length === 0;
    }
    upload(context, dynamicIndexBuffer, upload, update, createZOffsetBuffer) {
        if (this.isEmpty()) {
            return;
        }
        if (upload) {
            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);
            this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);
            this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);
            this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);
            if (this.iconTransitioningVertexArray.length > 0) {
                this.iconTransitioningVertexBuffer = context.createVertexBuffer(this.iconTransitioningVertexArray, iconTransitioningAttributes.members, true);
            }
            if (this.globeExtVertexArray.length > 0) {
                this.globeExtVertexBuffer = context.createVertexBuffer(this.globeExtVertexArray, symbolGlobeExtAttributes.members, true);
            }
            if (!this.zOffsetVertexBuffer && (this.zOffsetVertexArray.length > 0 || !!createZOffsetBuffer)) {
                this.zOffsetVertexBuffer = context.createVertexBuffer(this.zOffsetVertexArray, zOffsetAttributes.members, true);
            }
            // This is a performance hack so that we can write to opacityVertexArray with uint32s
            // even though the shaders read uint8s
            this.opacityVertexBuffer.itemSize = 1;
        }
        if (upload || update) {
            this.programConfigurations.upload(context);
        }
    }
    destroy() {
        if (!this.layoutVertexBuffer)
            return;
        this.layoutVertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.programConfigurations.destroy();
        this.segments.destroy();
        this.dynamicLayoutVertexBuffer.destroy();
        this.opacityVertexBuffer.destroy();
        if (this.iconTransitioningVertexBuffer) {
            this.iconTransitioningVertexBuffer.destroy();
        }
        if (this.globeExtVertexBuffer) {
            this.globeExtVertexBuffer.destroy();
        }
        if (this.zOffsetVertexBuffer) {
            this.zOffsetVertexBuffer.destroy();
        }
    }
}
register(SymbolBuffers, 'SymbolBuffers');
class CollisionBuffers {
    constructor(LayoutArray, layoutAttributes, IndexArray) {
        this.layoutVertexArray = new LayoutArray();
        this.layoutAttributes = layoutAttributes;
        this.indexArray = new IndexArray();
        this.segments = new SegmentVector();
        this.collisionVertexArray = new StructArrayLayout2ub2f12();
        this.collisionVertexArrayExt = new StructArrayLayout3f12();
    }
    upload(context) {
        this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);
        this.indexBuffer = context.createIndexBuffer(this.indexArray);
        this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);
        this.collisionVertexBufferExt = context.createVertexBuffer(this.collisionVertexArrayExt, collisionVertexAttributesExt.members, true);
    }
    destroy() {
        if (!this.layoutVertexBuffer)
            return;
        this.layoutVertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.segments.destroy();
        this.collisionVertexBuffer.destroy();
        this.collisionVertexBufferExt.destroy();
    }
}
register(CollisionBuffers, 'CollisionBuffers');
/**
 * Unlike other buckets, which simply implement #addFeature with type-specific
 * logic for (essentially) triangulating feature geometries, SymbolBucket
 * requires specialized behavior:
 *
 * 1. WorkerTile#parse(), the logical owner of the bucket creation process,
 *    calls SymbolBucket#populate(), which resolves text and icon tokens on
 *    each feature, adds each glyphs and symbols needed to the passed-in
 *    collections options.glyphDependencies and options.iconDependencies, and
 *    stores the feature data for use in subsequent step (this.features).
 *
 * 2. WorkerTile asynchronously requests from the main thread all of the glyphs
 *    and icons needed (by this bucket and any others). When glyphs and icons
 *    have been received, the WorkerTile creates a CollisionIndex and invokes:
 *
 * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and
 *    layout on a Symbol Bucket. This step populates:
 *      `this.symbolInstances`: metadata on generated symbols
 *      `collisionBoxArray`: collision data for use by foreground
 *      `this.text`: SymbolBuffers for text symbols
 *      `this.icons`: SymbolBuffers for icons
 *      `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes
 *      `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes
 *    The results are sent to the foreground for rendering
 *
 * 4. Placement.updateBucketOpacities() is run on the foreground,
 *    and uses the CollisionIndex along with current camera settings to determine
 *    which symbols can actually show on the map. Collided symbols are hidden
 *    using a dynamic "OpacityVertexArray".
 *
 * @private
 */
class SymbolBucket {
    constructor(options) {
        this.collisionBoxArray = options.collisionBoxArray;
        this.zoom = options.zoom;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.pixelRatio = options.pixelRatio;
        this.sourceLayerIndex = options.sourceLayerIndex;
        this.hasPattern = false;
        this.hasRTLText = false;
        this.fullyClipped = false;
        this.hasAnyIconTextFit = false;
        this.sortKeyRanges = [];
        this.collisionCircleArray = [];
        this.placementInvProjMatrix = mat4_1.identity([]);
        this.placementViewportMatrix = mat4_1.identity([]);
        const layer = this.layers[0];
        const unevaluatedLayoutValues = layer._unevaluatedLayout._values;
        this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']);
        this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']);
        const layout = this.layers[0].layout;
        const sortKey = layout.get('symbol-sort-key');
        const zOrder = layout.get('symbol-z-order');
        this.canOverlap = layout.get('text-allow-overlap') || layout.get('icon-allow-overlap') || layout.get('text-ignore-placement') || layout.get('icon-ignore-placement');
        this.sortFeaturesByKey = zOrder !== 'viewport-y' && sortKey.constantOr(1) !== undefined;
        const zOrderByViewportY = zOrder === 'viewport-y' || zOrder === 'auto' && !this.sortFeaturesByKey;
        this.sortFeaturesByY = zOrderByViewportY && this.canOverlap;
        this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]);
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.sourceID = options.sourceID;
        this.projection = options.projection;
        this.hasAnyZOffset = false;
        this.zOffsetSortDirty = false;
        this.zOffsetBuffersNeedUpload = layout.get('symbol-z-elevate');
    }
    createArrays() {
        this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property)));
        this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property)));
        this.glyphOffsetArray = new GlyphOffsetArray();
        this.lineVertexArray = new SymbolLineVertexArray();
        this.symbolInstances = new SymbolInstanceArray();
    }
    calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) {
        for (let i = 0; i < text.length; i++) {
            const codePoint = text.codePointAt(i);
            if (codePoint === undefined)
                break;
            stack[codePoint] = true;
            if (allowVerticalPlacement && doesAllowVerticalWritingMode && codePoint <= 65535) {
                const verticalChar = verticalizedCharacterMap[text.charAt(i)];
                if (verticalChar) {
                    stack[verticalChar.charCodeAt(0)] = true;
                }
            }
        }
    }
    populate(features, options, canonical, tileTransform) {
        const layer = this.layers[0];
        const layout = layer.layout;
        const isGlobe = this.projection.name === 'globe';
        const textFont = layout.get('text-font');
        const textField = layout.get('text-field');
        const iconImage = layout.get('icon-image');
        const hasText = (textField.value.kind !== 'constant' || textField.value.value instanceof Formatted && !textField.value.value.isEmpty() || textField.value.value.toString().length > 0) && (textFont.value.kind !== 'constant' || textFont.value.value.length > 0);
        // we should always resolve the icon-image value if the property was defined in the style
        // this allows us to fire the styleimagemissing event if image evaluation returns null
        // the only way to distinguish between null returned from a coalesce statement with no valid images
        // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object
        const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0;
        const symbolSortKey = layout.get('symbol-sort-key');
        this.features = [];
        if (!hasText && !hasIcon) {
            return;
        }
        const icons = options.iconDependencies;
        const stacks = options.glyphDependencies;
        const availableImages = options.availableImages;
        const globalProperties = new EvaluationParameters(this.zoom);
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = layer._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            // $FlowFixMe[method-unbinding]
            if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {
                continue;
            }
            if (!needGeometry)
                evaluationFeature.geometry = loadGeometry(feature, canonical, tileTransform);
            if (isGlobe && feature.type !== 1 && canonical.z <= 5) {
                // Resample long lines and polygons in globe view so that their length wont exceed ~0.19 radians (360/32 degrees).
                // Otherwise lines could clip through the globe as the resolution is not enough to represent curved paths.
                // The threshold value follows subdivision size used with fill extrusions
                const geom = evaluationFeature.geometry;
                // cos(11.25 degrees) = 0.98078528056
                const cosAngleThreshold = 0.98078528056;
                const predicate = (a, b) => {
                    const v0 = tileCoordToECEF(a.x, a.y, canonical, 1);
                    const v1 = tileCoordToECEF(b.x, b.y, canonical, 1);
                    return vec3_1.dot(v0, v1) < cosAngleThreshold;
                };
                for (let i = 0; i < geom.length; i++) {
                    geom[i] = resamplePred(geom[i], predicate);
                }
            }
            let text;
            if (hasText) {
                // Expression evaluation will automatically coerce to Formatted
                // but plain string token evaluation skips that pathway so do the
                // conversion here.
                const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages);
                const formattedText = Formatted.factory(resolvedTokens);
                if (containsRTLText(formattedText)) {
                    this.hasRTLText = true;
                }
                if (!this.hasRTLText || // non-rtl text so can proceed safely
                    getRTLTextPluginStatus() === 'unavailable' || this.hasRTLText && plugin.isParsed()    // Use the rtlText plugin to shape text
) {
                    text = transformText$1(formattedText, layer, evaluationFeature);
                }
            }
            let icon;
            if (hasIcon) {
                // Expression evaluation will automatically coerce to Image
                // but plain string token evaluation skips that pathway so do the
                // conversion here.
                const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages);
                if (resolvedTokens instanceof ResolvedImage) {
                    icon = resolvedTokens;
                } else {
                    icon = ResolvedImage.fromString(resolvedTokens);
                }
            }
            if (!text && !icon) {
                continue;
            }
            const sortKey = this.sortFeaturesByKey ? symbolSortKey.evaluate(evaluationFeature, {}, canonical) : undefined;
            const symbolFeature = {
                id,
                text,
                icon,
                index,
                sourceLayerIndex,
                geometry: evaluationFeature.geometry,
                properties: feature.properties,
                type: vectorTileFeatureTypes$2[feature.type],
                sortKey
            };
            this.features.push(symbolFeature);
            if (icon) {
                icons[icon.namePrimary] = true;
                if (icon.nameSecondary) {
                    icons[icon.nameSecondary] = true;
                }
            }
            if (text) {
                const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(',');
                const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';
                this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0;
                for (const section of text.sections) {
                    if (!section.image) {
                        const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString());
                        const sectionFont = section.fontStack || fontStack;
                        const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {};
                        this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode);
                    } else {
                        // Add section image to the list of dependencies.
                        icons[section.image.namePrimary] = true;
                    }
                }
            }
        }
        if (layout.get('symbol-placement') === 'line') {
            // Merge adjacent lines with the same text to improve labelling.
            // It's better to place labels on one long line than on many short segments.
            this.features = mergeLines(this.features);
        }
        if (this.sortFeaturesByKey) {
            this.features.sort((a, b) => {
                // a.sortKey is always a number when sortFeaturesByKey is true
                return a.sortKey - b.sortKey;
            });
        }
    }
    update(states, vtLayer, availableImages, imagePositions, brightness) {
        const withStateUpdates = Object.keys(states).length !== 0;
        if (withStateUpdates && !this.stateDependentLayers.length)
            return;
        const layers = withStateUpdates ? this.stateDependentLayers : this.layers;
        this.text.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
        this.icon.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
    }
    updateZOffset() {
        // z offset is expected to change less frequently than the placement opacity and, if values are the same,
        // avoid uploading arrays to buffers.
        const addZOffsetTextVertex = (array, numVertices, value) => {
            currentTextZOffsetVertex += numVertices;
            if (currentTextZOffsetVertex > array.length) {
                array.resize(currentTextZOffsetVertex);
            }
            for (let i = -numVertices; i < 0; i++) {
                array.emplace(i + currentTextZOffsetVertex, value);
            }
        };
        const addZOffsetIconVertex = (array, numVertices, value) => {
            currentIconZOffsetVertex += numVertices;
            if (currentIconZOffsetVertex > array.length) {
                array.resize(currentIconZOffsetVertex);
            }
            for (let i = -numVertices; i < 0; i++) {
                array.emplace(i + currentIconZOffsetVertex, value);
            }
        };
        const updateZOffset = this.zOffsetBuffersNeedUpload;
        if (!updateZOffset)
            return;
        this.zOffsetBuffersNeedUpload = false;
        let currentTextZOffsetVertex = 0;
        let currentIconZOffsetVertex = 0;
        for (let s = 0; s < this.symbolInstances.length; s++) {
            const symbolInstance = this.symbolInstances.get(s);
            const {numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices} = symbolInstance;
            const zOffset = symbolInstance.zOffset;
            const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;
            const hasIcon = numIconVertices > 0;
            if (hasText) {
                addZOffsetTextVertex(this.text.zOffsetVertexArray, numHorizontalGlyphVertices, zOffset);
                addZOffsetTextVertex(this.text.zOffsetVertexArray, numVerticalGlyphVertices, zOffset);
            }
            if (hasIcon) {
                const {placedIconSymbolIndex, verticalPlacedIconSymbolIndex} = symbolInstance;
                if (placedIconSymbolIndex >= 0) {
                    addZOffsetIconVertex(this.icon.zOffsetVertexArray, numIconVertices, zOffset);
                }
                if (verticalPlacedIconSymbolIndex >= 0) {
                    addZOffsetIconVertex(this.icon.zOffsetVertexArray, symbolInstance.numVerticalIconVertices, zOffset);
                }
            }
        }
        if (this.text.zOffsetVertexBuffer) {
            this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray);
        }
        if (this.icon.zOffsetVertexBuffer) {
            this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray);
        }
    }
    isEmpty() {
        // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created.
        // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary.
        return this.symbolInstances.length === 0 && !this.hasRTLText;
    }
    uploadPending() {
        return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;
    }
    upload(context) {
        if (!this.uploaded && this.hasDebugData()) {
            this.textCollisionBox.upload(context);
            this.iconCollisionBox.upload(context);
        }
        this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload, this.zOffsetBuffersNeedUpload);
        this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload, this.zOffsetBuffersNeedUpload);
        this.uploaded = true;
    }
    destroyDebugData() {
        this.textCollisionBox.destroy();
        this.iconCollisionBox.destroy();
    }
    getProjection() {
        if (!this.projectionInstance) {
            this.projectionInstance = getProjection(this.projection);
        }
        return this.projectionInstance;
    }
    destroy() {
        this.text.destroy();
        this.icon.destroy();
        if (this.hasDebugData()) {
            this.destroyDebugData();
        }
    }
    addToLineVertexArray(anchor, line) {
        const lineStartIndex = this.lineVertexArray.length;
        if (anchor.segment !== undefined) {
            for (const {x, y} of line) {
                this.lineVertexArray.emplaceBack(x, y);
            }
        }
        return {
            lineStartIndex,
            lineLength: this.lineVertexArray.length - lineStartIndex
        };
    }
    addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, globe, tileAnchor, lineStartIndex, lineLength, associatedIconIndex, availableImages, canonical, brightness, hasAnySecondaryIcon) {
        const indexArray = arrays.indexArray;
        const layoutVertexArray = arrays.layoutVertexArray;
        const globeExtVertexArray = arrays.globeExtVertexArray;
        const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : undefined);
        const glyphOffsetArrayStart = this.glyphOffsetArray.length;
        const vertexStartIndex = segment.vertexLength;
        const angle = this.allowVerticalPlacement && writingMode === WritingMode.vertical ? Math.PI / 2 : 0;
        const sections = feature.text && feature.text.sections;
        for (let i = 0; i < quads.length; i++) {
            const {tl, tr, bl, br, texPrimary, texSecondary, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex} = quads[i];
            const index = segment.vertexLength;
            const y = glyphOffset[1];
            addVertex$2(layoutVertexArray, tileAnchor.x, tileAnchor.y, tl.x, y + tl.y, texPrimary.x, texPrimary.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
            addVertex$2(layoutVertexArray, tileAnchor.x, tileAnchor.y, tr.x, y + tr.y, texPrimary.x + texPrimary.w, texPrimary.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
            addVertex$2(layoutVertexArray, tileAnchor.x, tileAnchor.y, bl.x, y + bl.y, texPrimary.x, texPrimary.y + texPrimary.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);
            addVertex$2(layoutVertexArray, tileAnchor.x, tileAnchor.y, br.x, y + br.y, texPrimary.x + texPrimary.w, texPrimary.y + texPrimary.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);
            if (globe) {
                const {x, y, z} = globe.anchor;
                const [ux, uy, uz] = globe.up;
                addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);
                addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);
                addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);
                addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);
                addDynamicAttributes(arrays.dynamicLayoutVertexArray, x, y, z, angle);
            } else {
                addDynamicAttributes(arrays.dynamicLayoutVertexArray, tileAnchor.x, tileAnchor.y, tileAnchor.z, angle);
            }
            // For data-driven cases if at least of one the icon has a transitionable variant
            // we have to load the main variant in cases where the secondary image is not specified
            if (hasAnySecondaryIcon) {
                const tex = texSecondary ? texSecondary : texPrimary;
                addTransitioningVertex(arrays.iconTransitioningVertexArray, tex.x, tex.y);
                addTransitioningVertex(arrays.iconTransitioningVertexArray, tex.x + tex.w, tex.y);
                addTransitioningVertex(arrays.iconTransitioningVertexArray, tex.x, tex.y + tex.h);
                addTransitioningVertex(arrays.iconTransitioningVertexArray, tex.x + tex.w, tex.y + tex.h);
            }
            indexArray.emplaceBack(index, index + 1, index + 2);
            indexArray.emplaceBack(index + 1, index + 2, index + 3);
            segment.vertexLength += 4;
            segment.primitiveLength += 2;
            this.glyphOffsetArray.emplaceBack(glyphOffset[0]);
            if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) {
                arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, availableImages, canonical, brightness, sections && sections[sectionIndex]);
            }
        }
        const projectedAnchor = globe ? globe.anchor : tileAnchor;
        arrays.placedSymbolArray.emplaceBack(projectedAnchor.x, projectedAnchor.y, projectedAnchor.z, tileAnchor.x, tileAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, tileAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed
        0, false, // The crossTileID is only filled/used on the foreground for dynamic text anchors
        0, associatedIconIndex, // flipState is unknown initially; will be updated to flipRequired(1)/flipNotRequired(2) during line label reprojection
        0);
    }
    _commitLayoutVertex(array, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, tileAnchorX, tileAnchorY, extrude) {
        array.emplaceBack(// pos
        boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, // a_anchor_pos
        tileAnchorX, tileAnchorY, // extrude
        Math.round(extrude.x), Math.round(extrude.y));
    }
    _addCollisionDebugVertices(box, scale, arrays, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolInstance) {
        const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);
        const index = segment.vertexLength;
        const symbolTileAnchorX = symbolInstance.tileAnchorX;
        const symbolTileAnchorY = symbolInstance.tileAnchorY;
        for (let i = 0; i < 4; i++) {
            arrays.collisionVertexArray.emplaceBack(0, 0, 0, 0);
        }
        arrays.collisionVertexArrayExt.emplaceBack(scale, -box.padding, -box.padding);
        arrays.collisionVertexArrayExt.emplaceBack(scale, box.padding, -box.padding);
        arrays.collisionVertexArrayExt.emplaceBack(scale, box.padding, box.padding);
        arrays.collisionVertexArrayExt.emplaceBack(scale, -box.padding, box.padding);
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point$2(box.x1, box.y1));
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point$2(box.x2, box.y1));
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point$2(box.x2, box.y2));
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point$2(box.x1, box.y2));
        segment.vertexLength += 4;
        const indexArray = arrays.indexArray;
        indexArray.emplaceBack(index, index + 1);
        indexArray.emplaceBack(index + 1, index + 2);
        indexArray.emplaceBack(index + 2, index + 3);
        indexArray.emplaceBack(index + 3, index);
        segment.primitiveLength += 4;
    }
    _addTextDebugCollisionBoxes(size, zoom, collisionBoxArray, startIndex, endIndex, instance) {
        for (let b = startIndex; b < endIndex; b++) {
            const box = collisionBoxArray.get(b);
            const scale = this.getSymbolInstanceTextSize(size, instance, zoom, b);
            this._addCollisionDebugVertices(box, scale, this.textCollisionBox, box.projectedAnchorX, box.projectedAnchorY, box.projectedAnchorZ, instance);
        }
    }
    _addIconDebugCollisionBoxes(size, zoom, collisionBoxArray, startIndex, endIndex, instance) {
        for (let b = startIndex; b < endIndex; b++) {
            const box = collisionBoxArray.get(b);
            const scale = this.getSymbolInstanceIconSize(size, zoom, instance.placedIconSymbolIndex);
            this._addCollisionDebugVertices(box, scale, this.iconCollisionBox, box.projectedAnchorX, box.projectedAnchorY, box.projectedAnchorZ, instance);
        }
    }
    generateCollisionDebugBuffers(zoom, collisionBoxArray) {
        if (this.hasDebugData()) {
            this.destroyDebugData();
        }
        this.textCollisionBox = new CollisionBuffers(StructArrayLayout3i2i2i16, collisionBoxLayout.members, StructArrayLayout2ui4);
        this.iconCollisionBox = new CollisionBuffers(StructArrayLayout3i2i2i16, collisionBoxLayout.members, StructArrayLayout2ui4);
        const iconSize = evaluateSizeForZoom(this.iconSizeData, zoom);
        const textSize = evaluateSizeForZoom(this.textSizeData, zoom);
        for (let i = 0; i < this.symbolInstances.length; i++) {
            const symbolInstance = this.symbolInstances.get(i);
            this._addTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance);
            this._addTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);
            this._addIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance);
            this._addIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance);
        }
    }
    getSymbolInstanceTextSize(textSize, instance, zoom, boxIndex) {
        const symbolIndex = instance.rightJustifiedTextSymbolIndex >= 0 ? instance.rightJustifiedTextSymbolIndex : instance.centerJustifiedTextSymbolIndex >= 0 ? instance.centerJustifiedTextSymbolIndex : instance.leftJustifiedTextSymbolIndex >= 0 ? instance.leftJustifiedTextSymbolIndex : instance.verticalPlacedTextSymbolIndex >= 0 ? instance.verticalPlacedTextSymbolIndex : boxIndex;
        const symbol = this.text.placedSymbolArray.get(symbolIndex);
        const featureSize = evaluateSizeForFeature(this.textSizeData, textSize, symbol) / ONE_EM;
        return this.tilePixelRatio * featureSize;
    }
    getSymbolInstanceIconSize(iconSize, zoom, iconIndex) {
        const symbol = this.icon.placedSymbolArray.get(iconIndex);
        const featureSize = evaluateSizeForFeature(this.iconSizeData, iconSize, symbol);
        return this.tilePixelRatio * featureSize;
    }
    _commitDebugCollisionVertexUpdate(array, scale, padding) {
        array.emplaceBack(scale, -padding, -padding);
        array.emplaceBack(scale, padding, -padding);
        array.emplaceBack(scale, padding, padding);
        array.emplaceBack(scale, -padding, padding);
    }
    _updateTextDebugCollisionBoxes(size, zoom, collisionBoxArray, startIndex, endIndex, instance) {
        for (let b = startIndex; b < endIndex; b++) {
            const box = collisionBoxArray.get(b);
            const scale = this.getSymbolInstanceTextSize(size, instance, zoom, b);
            const array = this.textCollisionBox.collisionVertexArrayExt;
            this._commitDebugCollisionVertexUpdate(array, scale, box.padding);
        }
    }
    _updateIconDebugCollisionBoxes(size, zoom, collisionBoxArray, startIndex, endIndex, symbolIndex) {
        for (let b = startIndex; b < endIndex; b++) {
            const box = collisionBoxArray.get(b);
            const scale = this.getSymbolInstanceIconSize(size, zoom, symbolIndex);
            const array = this.iconCollisionBox.collisionVertexArrayExt;
            this._commitDebugCollisionVertexUpdate(array, scale, box.padding);
        }
    }
    updateCollisionDebugBuffers(zoom, collisionBoxArray) {
        if (!this.hasDebugData()) {
            return;
        }
        if (this.hasTextCollisionBoxData())
            this.textCollisionBox.collisionVertexArrayExt.clear();
        if (this.hasIconCollisionBoxData())
            this.iconCollisionBox.collisionVertexArrayExt.clear();
        const iconSize = evaluateSizeForZoom(this.iconSizeData, zoom);
        const textSize = evaluateSizeForZoom(this.textSizeData, zoom);
        for (let i = 0; i < this.symbolInstances.length; i++) {
            const symbolInstance = this.symbolInstances.get(i);
            this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance);
            this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);
            this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.placedIconSymbolIndex);
            this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance.placedIconSymbolIndex);
        }
        if (this.hasTextCollisionBoxData() && this.textCollisionBox.collisionVertexBufferExt) {
            this.textCollisionBox.collisionVertexBufferExt.updateData(this.textCollisionBox.collisionVertexArrayExt);
        }
        if (this.hasIconCollisionBoxData() && this.iconCollisionBox.collisionVertexBufferExt) {
            this.iconCollisionBox.collisionVertexBufferExt.updateData(this.iconCollisionBox.collisionVertexArrayExt);
        }
    }
    // These flat arrays are meant to be quicker to iterate over than the source
    // CollisionBoxArray
    _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) {
        // Only one box allowed per instance
        const collisionArrays = {};
        if (textStartIndex < textEndIndex) {
            const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(textStartIndex);
            collisionArrays.textBox = {
                x1,
                y1,
                x2,
                y2,
                padding,
                projectedAnchorX,
                projectedAnchorY,
                projectedAnchorZ,
                tileAnchorX,
                tileAnchorY
            };
            collisionArrays.textFeatureIndex = featureIndex;
        }
        if (verticalTextStartIndex < verticalTextEndIndex) {
            const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(verticalTextStartIndex);
            collisionArrays.verticalTextBox = {
                x1,
                y1,
                x2,
                y2,
                padding,
                projectedAnchorX,
                projectedAnchorY,
                projectedAnchorZ,
                tileAnchorX,
                tileAnchorY
            };
            collisionArrays.verticalTextFeatureIndex = featureIndex;
        }
        if (iconStartIndex < iconEndIndex) {
            const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(iconStartIndex);
            collisionArrays.iconBox = {
                x1,
                y1,
                x2,
                y2,
                padding,
                projectedAnchorX,
                projectedAnchorY,
                projectedAnchorZ,
                tileAnchorX,
                tileAnchorY
            };
            collisionArrays.iconFeatureIndex = featureIndex;
        }
        if (verticalIconStartIndex < verticalIconEndIndex) {
            const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(verticalIconStartIndex);
            collisionArrays.verticalIconBox = {
                x1,
                y1,
                x2,
                y2,
                padding,
                projectedAnchorX,
                projectedAnchorY,
                projectedAnchorZ,
                tileAnchorX,
                tileAnchorY
            };
            collisionArrays.verticalIconFeatureIndex = featureIndex;
        }
        return collisionArrays;
    }
    deserializeCollisionBoxes(collisionBoxArray) {
        this.collisionArrays = [];
        for (let i = 0; i < this.symbolInstances.length; i++) {
            const symbolInstance = this.symbolInstances.get(i);
            this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex));
        }
    }
    hasTextData() {
        return this.text.segments.get().length > 0;
    }
    hasIconData() {
        return this.icon.segments.get().length > 0;
    }
    hasDebugData() {
        return this.textCollisionBox && this.iconCollisionBox;
    }
    hasTextCollisionBoxData() {
        return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;
    }
    hasIconCollisionBoxData() {
        return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;
    }
    hasIconTextFit() {
        return this.hasAnyIconTextFit;
    }
    addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) {
        const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex);
        const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;
        for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {
            iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);
            iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);
        }
    }
    getSortedSymbolIndexes(angle) {
        if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) {
            return this.symbolInstanceIndexes;
        }
        const sin = Math.sin(angle);
        const cos = Math.cos(angle);
        const rotatedYs = [];
        const featureIndexes = [];
        const result = [];
        for (let i = 0; i < this.symbolInstances.length; ++i) {
            result.push(i);
            const symbolInstance = this.symbolInstances.get(i);
            rotatedYs.push(Math.round(sin * symbolInstance.tileAnchorX + cos * symbolInstance.tileAnchorY) | 0);
            featureIndexes.push(symbolInstance.featureIndex);
        }
        result.sort((aIndex, bIndex) => rotatedYs[aIndex] - rotatedYs[bIndex] || featureIndexes[bIndex] - featureIndexes[aIndex]);
        return result;
    }
    getSortedIndexesByZOffset() {
        if (!this.zOffsetSortDirty) {
            return this.symbolInstanceIndexesSortedZOffset;
        }
        if (!this.symbolInstanceIndexesSortedZOffset) {
            this.symbolInstanceIndexesSortedZOffset = [];
            for (let i = 0; i < this.symbolInstances.length; ++i) {
                this.symbolInstanceIndexesSortedZOffset.push(i);
            }
        }
        this.zOffsetSortDirty = false;
        return this.symbolInstanceIndexesSortedZOffset.sort((aIndex, bIndex) => this.symbolInstances.get(bIndex).zOffset - this.symbolInstances.get(aIndex).zOffset);
    }
    addToSortKeyRanges(symbolInstanceIndex, sortKey) {
        const last = this.sortKeyRanges[this.sortKeyRanges.length - 1];
        if (last && last.sortKey === sortKey) {
            last.symbolInstanceEnd = symbolInstanceIndex + 1;
        } else {
            this.sortKeyRanges.push({
                sortKey,
                symbolInstanceStart: symbolInstanceIndex,
                symbolInstanceEnd: symbolInstanceIndex + 1
            });
        }
    }
    sortFeatures(angle) {
        if (!this.sortFeaturesByY)
            return;
        if (this.sortedAngle === angle)
            return;
        // The current approach to sorting doesn't sort across segments so don't try.
        // Sorting within segments separately seemed not to be worth the complexity.
        if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1)
            return;
        // If the symbols are allowed to overlap sort them by their vertical screen position.
        // The index array buffer is rewritten to reference the (unchanged) vertices in the
        // sorted order.
        // To avoid sorting the actual symbolInstance array we sort an array of indexes.
        this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle);
        this.sortedAngle = angle;
        this.text.indexArray.clear();
        this.icon.indexArray.clear();
        this.featureSortOrder = [];
        for (const i of this.symbolInstanceIndexes) {
            const symbol = this.symbolInstances.get(i);
            this.featureSortOrder.push(symbol.featureIndex);
            const {
                rightJustifiedTextSymbolIndex: right,
                centerJustifiedTextSymbolIndex: center,
                leftJustifiedTextSymbolIndex: left,
                verticalPlacedTextSymbolIndex: vertical,
                placedIconSymbolIndex: icon,
                verticalPlacedIconSymbolIndex: iconVertical
            } = symbol;
            // Only add a given index the first time it shows up, to avoid duplicate
            // opacity entries when multiple justifications share the same glyphs.
            if (right >= 0)
                this.addIndicesForPlacedSymbol(this.text, right);
            if (center >= 0 && center !== right)
                this.addIndicesForPlacedSymbol(this.text, center);
            if (left >= 0 && left !== center && left !== right)
                this.addIndicesForPlacedSymbol(this.text, left);
            if (vertical >= 0)
                this.addIndicesForPlacedSymbol(this.text, vertical);
            if (icon >= 0)
                this.addIndicesForPlacedSymbol(this.icon, icon);
            if (iconVertical >= 0)
                this.addIndicesForPlacedSymbol(this.icon, iconVertical);
        }
        if (this.text.indexBuffer)
            this.text.indexBuffer.updateData(this.text.indexArray);
        if (this.icon.indexBuffer)
            this.icon.indexBuffer.updateData(this.icon.indexArray);
    }
}
register(SymbolBucket, 'SymbolBucket', {
    omit: [
        'layers',
        'collisionBoxArray',
        'features',
        'compareText'
    ]
});
// this constant is based on the size of StructArray indexes used in a symbol
// bucket--namely, glyphOffsetArrayStart
// eg the max valid UInt16 is 65,535
// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation
// lineStartIndex and textBoxStartIndex could potentially be concerns
// but we expect there to be many fewer boxes/lines than glyphs
SymbolBucket.MAX_GLYPHS = 65535;
SymbolBucket.addDynamicAttributes = addDynamicAttributes;
var SymbolBucket$1 = SymbolBucket;

//      
const lineLayoutAttributes = createLayout([
    {
        name: 'a_pos_normal',
        components: 2,
        type: 'Int16'
    },
    {
        name: 'a_data',
        components: 4,
        type: 'Uint8'
    },
    {
        name: 'a_linesofar',
        components: 1,
        type: 'Float32'
    }
], 4);
const {members: members$2, size: size$2, alignment: alignment$2} = lineLayoutAttributes;

//      
const lineLayoutAttributesExt = createLayout([{
        name: 'a_packed',
        components: 4,
        type: 'Float32'
    }]);
const {members: members$1, size: size$1, alignment: alignment$1} = lineLayoutAttributesExt;

//      
const vectorTileFeatureTypes$1 = VectorTileFeature.types;
// NOTE ON EXTRUDE SCALE:
// scale the extrusion vector so that the normal length is this value.
// contains the "texture" normals (-1..1). this is distinct from the extrude
// normals for line joins, because the x-value remains 0 for the texture
// normal array, while the extrude normal actually moves the vertex to create
// the acute/bevelled line join.
const EXTRUDE_SCALE = 63;
/*
 * Sharp corners cause dashed lines to tilt because the distance along the line
 * is the same at both the inner and outer corners. To improve the appearance of
 * dashed lines we add extra points near sharp corners so that a smaller part
 * of the line is tilted.
 *
 * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an
 * extra vertex. The default is 75 degrees.
 *
 * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner.
 */
const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));
const SHARP_CORNER_OFFSET = 15;
// Angle per triangle for approximating round line joins.
const DEG_PER_TRIANGLE = 20;
/**
 * @private
 */
class LineBucket {
    constructor(options) {
        this.zoom = options.zoom;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.projection = options.projection;
        this.hasPattern = false;
        this.patternFeatures = [];
        this.lineClipsArray = [];
        this.gradients = {};
        this.layers.forEach(layer => {
            this.gradients[layer.id] = {};
        });
        this.layoutVertexArray = new StructArrayLayout2i4ub1f12();
        this.layoutVertexArray2 = new StructArrayLayout4f16();
        this.indexArray = new StructArrayLayout3ui6();
        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
        this.segments = new SegmentVector();
        this.maxLineLength = 0;
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
    }
    populate(features, options, canonical, tileTransform) {
        this.hasPattern = hasPattern('line', this.layers, options);
        const lineSortKey = this.layers[0].layout.get('line-sort-key');
        const bucketFeatures = [];
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            // $FlowFixMe[method-unbinding]
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const sortKey = lineSortKey ? lineSortKey.evaluate(evaluationFeature, {}, canonical) : undefined;
            const bucketFeature = {
                id,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),
                patterns: {},
                sortKey
            };
            bucketFeatures.push(bucketFeature);
        }
        if (lineSortKey) {
            bucketFeatures.sort((a, b) => {
                // a.sortKey is always a number when in use
                return a.sortKey - b.sortKey;
            });
        }
        const {lineAtlas, featureIndex} = options;
        const hasFeatureDashes = this.addConstantDashes(lineAtlas);
        for (const bucketFeature of bucketFeatures) {
            const {geometry, index, sourceLayerIndex} = bucketFeature;
            if (hasFeatureDashes) {
                this.addFeatureDashes(bucketFeature, lineAtlas);
            }
            if (this.hasPattern) {
                const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options);
                // pattern features are added only once the pattern is loaded into the image atlas
                // so are stored during populate until later updated with positions by tile worker in addFeatures
                this.patternFeatures.push(patternBucketFeature);
            } else {
                this.addFeature(bucketFeature, geometry, index, canonical, lineAtlas.positions, options.availableImages, options.brightness);
            }
            const feature = features[index].feature;
            featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);
        }
    }
    addConstantDashes(lineAtlas) {
        let hasFeatureDashes = false;
        for (const layer of this.layers) {
            const dashPropertyValue = layer.paint.get('line-dasharray').value;
            const capPropertyValue = layer.layout.get('line-cap').value;
            if (dashPropertyValue.kind !== 'constant' || capPropertyValue.kind !== 'constant') {
                hasFeatureDashes = true;
            } else {
                const constCap = capPropertyValue.value;
                const constDash = dashPropertyValue.value;
                if (!constDash)
                    continue;
                lineAtlas.addDash(constDash, constCap);
            }
        }
        return hasFeatureDashes;
    }
    addFeatureDashes(feature, lineAtlas) {
        const zoom = this.zoom;
        for (const layer of this.layers) {
            const dashPropertyValue = layer.paint.get('line-dasharray').value;
            const capPropertyValue = layer.layout.get('line-cap').value;
            if (dashPropertyValue.kind === 'constant' && capPropertyValue.kind === 'constant')
                continue;
            let dashArray, cap;
            if (dashPropertyValue.kind === 'constant') {
                dashArray = dashPropertyValue.value;
                if (!dashArray)
                    continue;
            } else {
                dashArray = dashPropertyValue.evaluate({ zoom }, feature);
            }
            if (capPropertyValue.kind === 'constant') {
                cap = capPropertyValue.value;
            } else {
                cap = capPropertyValue.evaluate({ zoom }, feature);
            }
            lineAtlas.addDash(dashArray, cap);
            // save positions for paint array
            feature.patterns[layer.id] = lineAtlas.getKey(dashArray, cap);
        }
    }
    update(states, vtLayer, availableImages, imagePositions, brightness) {
        const withStateUpdates = Object.keys(states).length !== 0;
        if (withStateUpdates && !this.stateDependentLayers.length)
            return;
        const layers = withStateUpdates ? this.stateDependentLayers : this.layers;
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
    }
    addFeatures(options, canonical, imagePositions, availableImages, _, brightness) {
        for (const feature of this.patternFeatures) {
            this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions, availableImages, brightness);
        }
    }
    isEmpty() {
        return this.layoutVertexArray.length === 0;
    }
    uploadPending() {
        return !this.uploaded || this.programConfigurations.needsUpload;
    }
    upload(context) {
        if (!this.uploaded) {
            if (this.layoutVertexArray2.length !== 0) {
                this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members$1);
            }
            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2);
            this.indexBuffer = context.createIndexBuffer(this.indexArray);
        }
        this.programConfigurations.upload(context);
        this.uploaded = true;
    }
    destroy() {
        if (!this.layoutVertexBuffer)
            return;
        this.layoutVertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.programConfigurations.destroy();
        this.segments.destroy();
    }
    lineFeatureClips(feature) {
        if (!!feature.properties && feature.properties.hasOwnProperty('mapbox_clip_start') && feature.properties.hasOwnProperty('mapbox_clip_end')) {
            const start = +feature.properties['mapbox_clip_start'];
            const end = +feature.properties['mapbox_clip_end'];
            return {
                start,
                end
            };
        }
    }
    addFeature(feature, geometry, index, canonical, imagePositions, availableImages, brightness) {
        const layout = this.layers[0].layout;
        const join = layout.get('line-join').evaluate(feature, {});
        const cap = layout.get('line-cap').evaluate(feature, {});
        const miterLimit = layout.get('line-miter-limit');
        const roundLimit = layout.get('line-round-limit');
        this.lineClips = this.lineFeatureClips(feature);
        for (const line of geometry) {
            this.addLine(line, feature, join, cap, miterLimit, roundLimit);
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical, brightness);
    }
    addLine(vertices, feature, join, cap, miterLimit, roundLimit) {
        this.distance = 0;
        this.scaledDistance = 0;
        this.totalDistance = 0;
        this.lineSoFar = 0;
        if (this.lineClips) {
            this.lineClipsArray.push(this.lineClips);
            // Calculate the total distance, in tile units, of this tiled line feature
            for (let i = 0; i < vertices.length - 1; i++) {
                this.totalDistance += vertices[i].dist(vertices[i + 1]);
            }
            this.updateScaledDistance();
            this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);
        }
        const isPolygon = vectorTileFeatureTypes$1[feature.type] === 'Polygon';
        // If the line has duplicate vertices at the ends, adjust start/length to remove them.
        let len = vertices.length;
        while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {
            len--;
        }
        let first = 0;
        while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {
            first++;
        }
        // Ignore invalid geometry.
        if (len < (isPolygon ? 3 : 2))
            return;
        if (join === 'bevel')
            miterLimit = 1.05;
        const sharpCornerOffset = this.overscaling <= 16 ? SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) : 0;
        // we could be more precise, but it would only save a negligible amount of space
        const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);
        let currentVertex;
        let prevVertex = undefined;
        let nextVertex = undefined;
        let prevNormal = undefined;
        let nextNormal = undefined;
        // the last two vertices added
        this.e1 = this.e2 = -1;
        if (isPolygon) {
            currentVertex = vertices[len - 2];
            nextNormal = vertices[first].sub(currentVertex)._unit()._perp();
        }
        for (let i = first; i < len; i++) {
            nextVertex = i === len - 1 ? isPolygon ? vertices[first + 1] : undefined : // if it's a polygon, treat the last vertex like the first
            vertices[i + 1];
            // just the next vertex
            // if two consecutive vertices exist, skip the current one
            if (nextVertex && vertices[i].equals(nextVertex))
                continue;
            if (nextNormal)
                prevNormal = nextNormal;
            if (currentVertex)
                prevVertex = currentVertex;
            currentVertex = vertices[i];
            // Calculate the normal towards the next vertex in this line. In case
            // there is no next vertex, pretend that the line is continuing straight,
            // meaning that we are just using the previous normal.
            nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;
            // If we still don't have a previous normal, this is the beginning of a
            // non-closed line, so we're doing a straight "join".
            prevNormal = prevNormal || nextNormal;
            // Determine the normal of the join extrusion. It is the angle bisector
            // of the segments between the previous line and the next line.
            // In the case of 180° angles, the prev and next normals cancel each other out:
            // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be
            // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle
            // below will also become 0 and miterLength will become Infinity.
            let joinNormal = prevNormal.add(nextNormal);
            if (joinNormal.x !== 0 || joinNormal.y !== 0) {
                joinNormal._unit();
            }
            /*  joinNormal     prevNormal
             *             ↖      ↑
             *                .________. prevVertex
             *                |
             * nextNormal  ←  |  currentVertex
             *                |
             *     nextVertex !
             *
             */
            // calculate cosines of the angle (and its half) using dot product
            const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;
            const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
            // Calculate the length of the miter (the ratio of the miter to the width)
            // as the inverse of cosine of the angle between next and join normals
            const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;
            // approximate angle from cosine
            const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle);
            const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;
            const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;
            if (isSharpCorner && i > first) {
                const prevSegmentLength = currentVertex.dist(prevVertex);
                if (prevSegmentLength > 2 * sharpCornerOffset) {
                    const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());
                    this.updateDistance(prevVertex, newPrevVertex);
                    this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment);
                    prevVertex = newPrevVertex;
                }
            }
            // The join if a middle vertex, otherwise the cap.
            const middleVertex = prevVertex && nextVertex;
            let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap;
            if (middleVertex && currentJoin === 'round') {
                if (miterLength < roundLimit) {
                    currentJoin = 'miter';
                } else if (miterLength <= 2) {
                    currentJoin = 'fakeround';
                }
            }
            if (currentJoin === 'miter' && miterLength > miterLimit) {
                currentJoin = 'bevel';
            }
            if (currentJoin === 'bevel') {
                // The maximum extrude length is 128 / 63 = 2 times the width of the line
                // so if miterLength >= 2 we need to draw a different type of bevel here.
                if (miterLength > 2)
                    currentJoin = 'flipbevel';
                // If the miterLength is really small and the line bevel wouldn't be visible,
                // just draw a miter join to save a triangle.
                if (miterLength < miterLimit)
                    currentJoin = 'miter';
            }
            // Calculate how far along the line the currentVertex is
            if (prevVertex)
                this.updateDistance(prevVertex, currentVertex);
            if (currentJoin === 'miter') {
                joinNormal._mult(miterLength);
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);
            } else if (currentJoin === 'flipbevel') {
                // miter is too big, flip the direction to make a beveled join
                if (miterLength > 100) {
                    // Almost parallel lines
                    joinNormal = nextNormal.mult(-1);
                } else {
                    const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();
                    joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1));
                }
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);
                this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment);
            } else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {
                const offset = -Math.sqrt(miterLength * miterLength - 1);
                const offsetA = lineTurnsLeft ? offset : 0;
                const offsetB = lineTurnsLeft ? 0 : offset;
                // Close previous segment with a bevel
                if (prevVertex) {
                    this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment);
                }
                if (currentJoin === 'fakeround') {
                    // The join angle is sharp enough that a round join would be visible.
                    // Bevel joins fill the gap between segments with a single pie slice triangle.
                    // Create a round join by adding multiple pie slices. The join isn't actually round, but
                    // it looks like it is at the sizes we render lines at.
                    // pick the number of triangles for approximating round join by based on the angle between normals
                    const n = Math.round(approxAngle * 180 / Math.PI / DEG_PER_TRIANGLE);
                    for (let m = 1; m < n; m++) {
                        let t = m / n;
                        if (t !== 0.5) {
                            // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp
                            const t2 = t - 0.5;
                            const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519));
                            const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638);
                            t = t + t * t2 * (t - 1) * (A * t2 * t2 + B);
                        }
                        const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1);
                        this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment);
                    }
                }
                if (nextVertex) {
                    // Start next segment
                    this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment);
                }
            } else if (currentJoin === 'butt') {
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);    // butt cap
            } else if (currentJoin === 'square') {
                const offset = prevVertex ? 1 : -1;
                // closing or starting square cap
                if (!prevVertex) {
                    this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment);
                }
                // make the cap it's own quad to avoid the cap affecting the line distance
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);
                if (prevVertex) {
                    this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment);
                }
            } else if (currentJoin === 'round') {
                if (prevVertex) {
                    // Close previous segment with butt
                    this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment);
                    // Add round cap or linejoin at end of segment
                    this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true);
                }
                if (nextVertex) {
                    // Add round cap before first segment
                    this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true);
                    // Start next segment with a butt
                    this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment);
                }
            }
            if (isSharpCorner && i < len - 1) {
                const nextSegmentLength = currentVertex.dist(nextVertex);
                if (nextSegmentLength > 2 * sharpCornerOffset) {
                    const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round());
                    this.updateDistance(currentVertex, newCurrentVertex);
                    this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment);
                    currentVertex = newCurrentVertex;
                }
            }
        }
    }
    /**
     * Add two vertices to the buffers.
     *
     * @param p the line vertex to add buffer vertices for
     * @param normal vertex normal
     * @param endLeft extrude to shift the left vertex along the line
     * @param endRight extrude to shift the left vertex along the line
     * @param segment the segment object to add the vertex to
     * @param round whether this is a round cap
     * @private
     */
    addCurrentVertex(p, normal, endLeft, endRight, segment, round = false) {
        // left and right extrude vectors, perpendicularly shifted by endLeft/endRight
        const leftX = normal.x + normal.y * endLeft;
        const leftY = normal.y - normal.x * endLeft;
        const rightX = -normal.x + normal.y * endRight;
        const rightY = -normal.y - normal.x * endRight;
        this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment);
        this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment);
    }
    addHalfVertex({x, y}, extrudeX, extrudeY, round, up, dir, segment) {
        this.layoutVertexArray.emplaceBack(// a_pos_normal
        // Encode round/up the least significant bits
        (x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), // a_data
        // add 128 to store a byte in an unsigned byte
        Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, (dir === 0 ? 0 : dir < 0 ? -1 : 1) + 1, 0, // unused
        // a_linesofar
        this.lineSoFar);
        // Constructs a second vertex buffer with higher precision line progress
        if (this.lineClips) {
            this.layoutVertexArray2.emplaceBack(this.scaledDistance, this.lineClipsArray.length, this.lineClips.start, this.lineClips.end);
        }
        const e = segment.vertexLength++;
        if (this.e1 >= 0 && this.e2 >= 0) {
            this.indexArray.emplaceBack(this.e1, this.e2, e);
            segment.primitiveLength++;
        }
        if (up) {
            this.e2 = e;
        } else {
            this.e1 = e;
        }
    }
    updateScaledDistance() {
        // Knowing the ratio of the full linestring covered by this tiled feature, as well
        // as the total distance (in tile units) of this tiled feature, and the distance
        // (in tile units) of the current vertex, we can determine the relative distance
        // of this vertex along the full linestring feature.
        if (this.lineClips) {
            const featureShare = this.lineClips.end - this.lineClips.start;
            const totalFeatureLength = this.totalDistance / featureShare;
            this.scaledDistance = this.distance / this.totalDistance;
            this.lineSoFar = totalFeatureLength * this.lineClips.start + this.distance;
        } else {
            this.lineSoFar = this.distance;
        }
    }
    updateDistance(prev, next) {
        this.distance += prev.dist(next);
        this.updateScaledDistance();
    }
}
register(LineBucket, 'LineBucket', {
    omit: [
        'layers',
        'patternFeatures'
    ]
});

//      
class Texture {
    constructor(context, image, format, options) {
        this.context = context;
        this.format = format;
        this.texture = context.gl.createTexture();
        this.update(image, options);
    }
    update(image, options, position) {
        const {width, height} = image;
        const {context} = this;
        const {gl} = context;
        const {HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap} = window$1;
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        context.pixelStoreUnpackFlipY.set(false);
        context.pixelStoreUnpack.set(1);
        context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false));
        if (!position && (!this.size || this.size[0] !== width || this.size[1] !== height)) {
            this.size = [
                width,
                height
            ];
            if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || ImageBitmap && image instanceof ImageBitmap) {
                let baseFormat = this.format;
                // $FlowFixMe[prop-missing] - Flow cannot check for gl.R8
                if (this.format === gl.R8) {
                    // $FlowFixMe[prop-missing] - Flow cannot check for gl.RED
                    baseFormat = gl.RED;
                }
                gl.texImage2D(gl.TEXTURE_2D, 0, this.format, baseFormat, gl.UNSIGNED_BYTE, image);
            } else {
                let internalFormat = this.format;
                let format = this.format;
                let type = gl.UNSIGNED_BYTE;
                if (this.format === gl.DEPTH_COMPONENT) {
                    // $FlowFixMe[incompatible-type]
                    internalFormat = gl.DEPTH_COMPONENT16;
                    // $FlowFixMe[incompatible-type]
                    type = gl.UNSIGNED_SHORT;
                }
                if (this.format === gl.R32F) {
                    type = gl.FLOAT;
                    format = gl.RED;
                }
                // $FlowFixMe prop-missing - Flow can't refine image type here
                gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, image.data);
            }
        } else {
            const {x, y} = position || {
                x: 0,
                y: 0
            };
            if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || ImageBitmap && image instanceof ImageBitmap) {
                gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image);
            } else {
                let format = this.format;
                let type = gl.UNSIGNED_BYTE;
                if (this.format === gl.R32F) {
                    format = gl.RED;
                    type = gl.FLOAT;
                }
                // $FlowFixMe prop-missing - Flow can't refine image type here
                gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, format, type, image.data);
            }
        }
        this.useMipmap = Boolean(options && options.useMipmap);
        if (this.useMipmap) {
            gl.generateMipmap(gl.TEXTURE_2D);
        }
    }
    bind(filter, wrap) {
        const {context} = this;
        const {gl} = context;
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        if (filter !== this.minFilter) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.useMipmap ? filter === gl.NEAREST ? gl.NEAREST_MIPMAP_NEAREST : gl.LINEAR_MIPMAP_NEAREST : filter);
            this.minFilter = filter;
        }
        if (wrap !== this.wrapS) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
            this.wrapS = wrap;
        }
    }
    bindExtraParam(minFilter, magFilter, wrapS, wrapT) {
        const {context} = this;
        const {gl} = context;
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        if (magFilter !== this.magFilter) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
            this.magFilter = magFilter;
        }
        if (minFilter !== this.minFilter) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.useMipmap ? minFilter === gl.NEAREST ? gl.NEAREST_MIPMAP_NEAREST : gl.LINEAR_MIPMAP_NEAREST : minFilter);
            this.minFilter = minFilter;
        }
        if (wrapS !== this.wrapS) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
            this.wrapS = wrapS;
        }
        if (wrapT !== this.wrapT) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
            this.wrapT = wrapT;
        }
    }
    destroy() {
        const {gl} = this.context;
        gl.deleteTexture(this.texture);
        this.texture = null;
    }
}
class UserManagedTexture {
    constructor(context, texture) {
        this.context = context;
        this.texture = texture;
    }
    bind(filter, wrap) {
        const {context} = this;
        const {gl} = context;
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        if (filter !== this.minFilter) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
            this.minFilter = filter;
        }
        if (wrap !== this.wrapS) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
            this.wrapS = wrap;
        }
    }
}

//      
// logic for generating non-Mercator adaptive raster tile reprojection meshes with MARTINI
const meshSize = 32;
const gridSize = meshSize + 1;
const numTriangles = meshSize * meshSize * 2 - 2;
const numParentTriangles = numTriangles - meshSize * meshSize;
const coords = new Uint16Array(numTriangles * 4);
// precalculate RTIN triangle coordinates
for (let i = 0; i < numTriangles; i++) {
    let id = i + 2;
    let ax = 0, ay = 0, bx = 0, by = 0, cx = 0, cy = 0;
    if (id & 1) {
        bx = by = cx = meshSize;    // bottom-left triangle
    } else {
        ax = ay = cy = meshSize;    // top-right triangle
    }
    while ((id >>= 1) > 1) {
        const mx = ax + bx >> 1;
        const my = ay + by >> 1;
        if (id & 1) {
            // left half
            bx = ax;
            by = ay;
            ax = cx;
            ay = cy;
        } else {
            // right half
            ax = bx;
            ay = by;
            bx = cx;
            by = cy;
        }
        cx = mx;
        cy = my;
    }
    const k = i * 4;
    coords[k + 0] = ax;
    coords[k + 1] = ay;
    coords[k + 2] = bx;
    coords[k + 3] = by;
}
// temporary arrays we'll reuse for MARTINI mesh code
const reprojectedCoords = new Uint16Array(gridSize * gridSize * 2);
const used = new Uint8Array(gridSize * gridSize);
const indexMap = new Uint16Array(gridSize * gridSize);
// There can be visible seams between neighbouring tiles because of precision issues
// and resampling differences. Adding a bit of padding around the edges of tiles hides
// most of these issues.
const commonRasterTileSize = 256;
const paddingSize = meshSize / commonRasterTileSize / 4;
function seamPadding(n) {
    if (n === 0)
        return -paddingSize;
    else if (n === gridSize - 1)
        return paddingSize;
    else
        return 0;
}
function getTileMesh(canonical, projection) {
    const cs = tileTransform(canonical, projection);
    const z2 = Math.pow(2, canonical.z);
    for (let y = 0; y < gridSize; y++) {
        for (let x = 0; x < gridSize; x++) {
            const lng = lngFromMercatorX((canonical.x + (x + seamPadding(x)) / meshSize) / z2);
            const lat = latFromMercatorY((canonical.y + (y + seamPadding(y)) / meshSize) / z2);
            const p = projection.project(lng, lat);
            const k = y * gridSize + x;
            reprojectedCoords[2 * k + 0] = Math.round((p.x * cs.scale - cs.x) * EXTENT);
            reprojectedCoords[2 * k + 1] = Math.round((p.y * cs.scale - cs.y) * EXTENT);
        }
    }
    used.fill(0);
    indexMap.fill(0);
    // iterate over all possible triangles, starting from the smallest level
    for (let i = numTriangles - 1; i >= 0; i--) {
        const k = i * 4;
        const ax = coords[k + 0];
        const ay = coords[k + 1];
        const bx = coords[k + 2];
        const by = coords[k + 3];
        const mx = ax + bx >> 1;
        const my = ay + by >> 1;
        const cx = mx + my - ay;
        const cy = my + ax - mx;
        const aIndex = ay * gridSize + ax;
        const bIndex = by * gridSize + bx;
        const mIndex = my * gridSize + mx;
        // calculate error in the middle of the long edge of the triangle
        const rax = reprojectedCoords[2 * aIndex + 0];
        const ray = reprojectedCoords[2 * aIndex + 1];
        const rbx = reprojectedCoords[2 * bIndex + 0];
        const rby = reprojectedCoords[2 * bIndex + 1];
        const rmx = reprojectedCoords[2 * mIndex + 0];
        const rmy = reprojectedCoords[2 * mIndex + 1];
        // raster tiles are typically 512px, and we use 1px as an error threshold; 8192 / 512 = 16
        const isUsed = Math.hypot((rax + rbx) / 2 - rmx, (ray + rby) / 2 - rmy) >= 16;
        used[mIndex] = used[mIndex] || (isUsed ? 1 : 0);
        if (i < numParentTriangles) {
            // bigger triangles; accumulate error with children
            const leftChildIndex = (ay + cy >> 1) * gridSize + (ax + cx >> 1);
            const rightChildIndex = (by + cy >> 1) * gridSize + (bx + cx >> 1);
            used[mIndex] = used[mIndex] || used[leftChildIndex] || used[rightChildIndex];
        }
    }
    const vertices = new StructArrayLayout4i8();
    const indices = new StructArrayLayout3ui6();
    let numVertices = 0;
    function addVertex(x, y) {
        const k = y * gridSize + x;
        if (indexMap[k] === 0) {
            vertices.emplaceBack(reprojectedCoords[2 * k + 0], reprojectedCoords[2 * k + 1], x * EXTENT / meshSize, y * EXTENT / meshSize);
            // save new vertex index so that we can reuse it
            indexMap[k] = ++numVertices;
        }
        return indexMap[k] - 1;
    }
    function addTriangles(ax, ay, bx, by, cx, cy) {
        const mx = ax + bx >> 1;
        const my = ay + by >> 1;
        if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && used[my * gridSize + mx]) {
            // triangle doesn't approximate the surface well enough; drill down further
            addTriangles(cx, cy, ax, ay, mx, my);
            addTriangles(bx, by, cx, cy, mx, my);
        } else {
            const ai = addVertex(ax, ay);
            const bi = addVertex(bx, by);
            const ci = addVertex(cx, cy);
            indices.emplaceBack(ai, bi, ci);
        }
    }
    addTriangles(0, 0, meshSize, meshSize, meshSize, 0);
    addTriangles(meshSize, meshSize, 0, 0, 0, meshSize);
    return {
        vertices,
        indices
    };
}

//      
var boundsAttributes = createLayout([
    {
        name: 'a_pos',
        type: 'Int16',
        components: 2
    },
    {
        name: 'a_texture_pos',
        type: 'Int16',
        components: 2
    }
]);

//      
const CLOCK_SKEW_RETRY_TIMEOUT = 30000;
/* Tile data was previously loaded, but has expired per its
                   * HTTP headers and is in the process of refreshing. */
// a tile bounds outline used for getting reprojected tile geometry in non-mercator projections
const BOUNDS_FEATURE = ((() => {
    return {
        type: 2,
        extent: EXTENT,
        loadGeometry() {
            return [[
                    new Point$2(0, 0),
                    new Point$2(EXTENT + 1, 0),
                    new Point$2(EXTENT + 1, EXTENT + 1),
                    new Point$2(0, EXTENT + 1),
                    new Point$2(0, 0)
                ]];
        }
    };
})());
/**
 * A tile object is the combination of a Coordinate, which defines
 * its place, as well as a unique ID and data tracking for its content
 *
 * @private
 */
class Tile {
    /**
     * @param {OverscaledTileID} tileID
     * @param size
     * @private
     */
    constructor(tileID, size, tileZoom, painter, isRaster) {
        this.tileID = tileID;
        this.uid = uniqueId();
        this.uses = 0;
        this.tileSize = size;
        this.tileZoom = tileZoom;
        this.buckets = {};
        this.expirationTime = null;
        this.queryPadding = 0;
        this.hasSymbolBuckets = false;
        this.hasRTLText = false;
        this.dependencies = {};
        this.isRaster = isRaster;
        if (painter && painter.style) {
            this._lastUpdatedBrightness = painter.style.getBrightness();
        }
        // Counts the number of times a response was already expired when
        // received. We're using this to add a delay when making a new request
        // so we don't have to keep retrying immediately in case of a server
        // serving expired tiles.
        this.expiredRequestCount = 0;
        this.state = 'loading';
        if (painter && painter.transform) {
            this.projection = painter.transform.projection;
        }
    }
    registerFadeDuration(duration) {
        const fadeEndTime = duration + this.timeAdded;
        if (fadeEndTime < exported$1.now())
            return;
        if (this.fadeEndTime && fadeEndTime < this.fadeEndTime)
            return;
        this.fadeEndTime = fadeEndTime;
    }
    wasRequested() {
        return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';
    }
    get tileTransform() {
        if (!this._tileTransform) {
            this._tileTransform = tileTransform(this.tileID.canonical, this.projection);
        }
        return this._tileTransform;
    }
    /**
     * Given a data object with a 'buffers' property, load it into
     * this tile's elementGroups and buffers properties and set loaded
     * to true. If the data is null, like in the case of an empty
     * GeoJSON tile, no-op but still set loaded to true.
     * @param {Object} data
     * @param painter
     * @returns {undefined}
     * @private
     */
    loadVectorData(data, painter, justReloaded) {
        this.unloadVectorData();
        this.state = 'loaded';
        // empty GeoJSON tile
        if (!data) {
            this.collisionBoxArray = new CollisionBoxArray();
            return;
        }
        if (data.featureIndex) {
            this.latestFeatureIndex = data.featureIndex;
            if (data.rawTileData) {
                // Only vector tiles have rawTileData, and they won't update it for
                // 'reloadTile'
                this.latestRawTileData = data.rawTileData;
                this.latestFeatureIndex.rawTileData = data.rawTileData;
            } else if (this.latestRawTileData) {
                // If rawTileData hasn't updated, hold onto a pointer to the last
                // one we received
                this.latestFeatureIndex.rawTileData = this.latestRawTileData;
            }
        }
        this.collisionBoxArray = data.collisionBoxArray;
        this.buckets = deserialize(data.buckets, painter.style);
        this.hasSymbolBuckets = false;
        for (const id in this.buckets) {
            const bucket = this.buckets[id];
            if (bucket instanceof SymbolBucket$1) {
                this.hasSymbolBuckets = true;
                if (justReloaded) {
                    bucket.justReloaded = true;
                } else {
                    break;
                }
            }
        }
        this.hasRTLText = false;
        if (this.hasSymbolBuckets) {
            for (const id in this.buckets) {
                const bucket = this.buckets[id];
                if (bucket instanceof SymbolBucket$1) {
                    if (bucket.hasRTLText) {
                        this.hasRTLText = true;
                        lazyLoadRTLTextPlugin();
                        break;
                    }
                }
            }
        }
        this.queryPadding = 0;
        for (const id in this.buckets) {
            const bucket = this.buckets[id];
            const layer = painter.style.getOwnLayer(id);
            if (!layer)
                continue;
            const queryRadius = layer.queryRadius(bucket);
            this.queryPadding = Math.max(this.queryPadding, queryRadius);
        }
        if (data.imageAtlas) {
            this.imageAtlas = data.imageAtlas;
        }
        if (data.glyphAtlasImage) {
            this.glyphAtlasImage = data.glyphAtlasImage;
        }
        if (data.lineAtlas) {
            this.lineAtlas = data.lineAtlas;
        }
        this._lastUpdatedBrightness = data.brightness;
    }
    /**
     * Release any data or WebGL resources referenced by this tile.
     * @returns {undefined}
     * @private
     */
    unloadVectorData() {
        if (!this.hasData())
            return;
        for (const id in this.buckets) {
            this.buckets[id].destroy();
        }
        this.buckets = {};
        if (this.imageAtlas) {
            this.imageAtlas = null;
        }
        if (this.lineAtlas) {
            this.lineAtlas = null;
        }
        if (this.imageAtlasTexture) {
            this.imageAtlasTexture.destroy();
        }
        if (this.glyphAtlasTexture) {
            this.glyphAtlasTexture.destroy();
        }
        if (this.lineAtlasTexture) {
            this.lineAtlasTexture.destroy();
        }
        if (this._tileBoundsBuffer) {
            this._tileBoundsBuffer.destroy();
            this._tileBoundsIndexBuffer.destroy();
            this._tileBoundsSegments.destroy();
            this._tileBoundsBuffer = null;
        }
        if (this._tileDebugBuffer) {
            this._tileDebugBuffer.destroy();
            this._tileDebugSegments.destroy();
            this._tileDebugBuffer = null;
        }
        if (this._tileDebugIndexBuffer) {
            this._tileDebugIndexBuffer.destroy();
            this._tileDebugIndexBuffer = null;
        }
        if (this._globeTileDebugBorderBuffer) {
            this._globeTileDebugBorderBuffer.destroy();
            this._globeTileDebugBorderBuffer = null;
        }
        if (this._tileDebugTextBuffer) {
            this._tileDebugTextBuffer.destroy();
            this._tileDebugTextSegments.destroy();
            this._tileDebugTextIndexBuffer.destroy();
            this._tileDebugTextBuffer = null;
        }
        if (this._globeTileDebugTextBuffer) {
            this._globeTileDebugTextBuffer.destroy();
            this._globeTileDebugTextBuffer = null;
        }
        this.latestFeatureIndex = null;
        this.state = 'unloaded';
    }
    getBucket(layer) {
        return this.buckets[layer.fqid];
    }
    upload(context) {
        for (const id in this.buckets) {
            const bucket = this.buckets[id];
            if (bucket.uploadPending()) {
                bucket.upload(context);
            }
        }
        const gl = context.gl;
        if (this.imageAtlas && !this.imageAtlas.uploaded) {
            this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);
            this.imageAtlas.uploaded = true;
        }
        if (this.glyphAtlasImage) {
            this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);
            this.glyphAtlasImage = null;
        }
        if (this.lineAtlas && !this.lineAtlas.uploaded) {
            this.lineAtlasTexture = new Texture(context, this.lineAtlas.image, gl.ALPHA);
            this.lineAtlas.uploaded = true;
        }
    }
    prepare(imageManager, painter, scope) {
        if (this.imageAtlas) {
            this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture, scope);
        }
        if (!painter || !this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) {
            return;
        }
        const brightness = painter.style.getBrightness();
        if (!this._lastUpdatedBrightness && !brightness) {
            return;
        }
        if (this._lastUpdatedBrightness && brightness && Math.abs(this._lastUpdatedBrightness - brightness) < 0.001) {
            return;
        }
        this._lastUpdatedBrightness = brightness;
        this.updateBuckets(undefined, painter);
    }
    // Queries non-symbol features rendered for this tile.
    // Symbol features are queried globally
    queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, tileResult, params, transform, pixelPosMatrix, visualizeQueryGeometry) {
        if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData)
            return {};
        return this.latestFeatureIndex.query({
            tileResult,
            pixelPosMatrix,
            transform,
            params,
            tileTransform: this.tileTransform
        }, layers, serializedLayers, sourceFeatureState);
    }
    querySourceFeatures(result, params) {
        const featureIndex = this.latestFeatureIndex;
        if (!featureIndex || !featureIndex.rawTileData)
            return;
        const vtLayers = featureIndex.loadVTLayers();
        const sourceLayer = params ? params.sourceLayer : '';
        const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer];
        if (!layer)
            return;
        const filter = createFilter(params && params.filter);
        const {z, x, y} = this.tileID.canonical;
        const coord = {
            z,
            x,
            y
        };
        for (let i = 0; i < layer.length; i++) {
            const feature = layer.feature(i);
            if (filter.needGeometry) {
                const evaluationFeature = toEvaluationFeature(feature, true);
                // $FlowFixMe[method-unbinding]
                if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical))
                    continue;    // $FlowFixMe[method-unbinding]
            } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
                continue;
            }
            const id = featureIndex.getId(feature, sourceLayer);
            const geojsonFeature = new Feature(feature, z, x, y, id);
            geojsonFeature.tile = coord;
            result.push(geojsonFeature);
        }
    }
    hasData() {
        return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';
    }
    bucketsLoaded() {
        for (const id in this.buckets) {
            if (this.buckets[id].uploadPending())
                return false;
        }
        return true;
    }
    patternsLoaded() {
        return !!this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;
    }
    setExpiryData(data) {
        const prior = this.expirationTime;
        if (data.cacheControl) {
            const parsedCC = parseCacheControl(data.cacheControl);
            if (parsedCC['max-age'])
                this.expirationTime = Date.now() + parsedCC['max-age'] * 1000;
        } else if (data.expires) {
            this.expirationTime = new Date(data.expires).getTime();
        }
        if (this.expirationTime) {
            const now = Date.now();
            let isExpired = false;
            if (this.expirationTime > now) {
                isExpired = false;
            } else if (!prior) {
                isExpired = true;
            } else if (this.expirationTime < prior) {
                // Expiring date is going backwards:
                // fall back to exponential backoff
                isExpired = true;
            } else {
                const delta = this.expirationTime - prior;
                if (!delta) {
                    // Server is serving the same expired resource over and over: fall
                    // back to exponential backoff.
                    isExpired = true;
                } else {
                    // Assume that either the client or the server clock is wrong and
                    // try to interpolate a valid expiration date (from the client POV)
                    // observing a minimum timeout.
                    this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);
                }
            }
            if (isExpired) {
                this.expiredRequestCount++;
                this.state = 'expired';
            } else {
                this.expiredRequestCount = 0;
            }
        }
    }
    getExpiryTimeout() {
        if (this.expirationTime) {
            if (this.expiredRequestCount) {
                return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31));
            } else {
                // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly
                return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);
            }
        }
    }
    setFeatureState(states, painter) {
        if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData || Object.keys(states).length === 0 || !painter) {
            return;
        }
        this.updateBuckets(states, painter);
    }
    updateBuckets(states, painter) {
        if (!this.latestFeatureIndex)
            return;
        const vtLayers = this.latestFeatureIndex.loadVTLayers();
        const availableImages = painter.style.listImages();
        const brightness = painter.style.getBrightness();
        for (const id in this.buckets) {
            if (!painter.style.hasLayer(id))
                continue;
            const bucket = this.buckets[id];
            // Buckets are grouped by common source-layer
            const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer';
            const sourceLayer = vtLayers[sourceLayerId];
            let sourceLayerStates = {};
            if (states) {
                sourceLayerStates = states[sourceLayerId];
                if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0)
                    continue;
            }
            // $FlowFixMe[incompatible-type] Flow can't interpret ImagePosition as SpritePosition for some reason here
            const imagePositions = this.imageAtlas && this.imageAtlas.patternPositions || {};
            bucket.update(sourceLayerStates, sourceLayer, availableImages, imagePositions, brightness);
            if (bucket instanceof LineBucket || bucket instanceof FillBucket) {
                const sourceCache = painter.style.getOwnSourceCache(bucket.layers[0].source);
                if (painter._terrain && painter._terrain.enabled && sourceCache && bucket.programConfigurations.needsUpload) {
                    painter._terrain._clearRenderCacheForTile(sourceCache.id, this.tileID);
                }
            }
            const layer = painter && painter.style && painter.style.getOwnLayer(id);
            if (layer) {
                this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));
            }
        }
    }
    holdingForFade() {
        return this.symbolFadeHoldUntil !== undefined;
    }
    symbolFadeFinished() {
        return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < exported$1.now();
    }
    clearFadeHold() {
        this.symbolFadeHoldUntil = undefined;
    }
    setHoldDuration(duration) {
        this.symbolFadeHoldUntil = exported$1.now() + duration;
    }
    setTexture(img, painter) {
        const context = painter.context;
        const gl = context.gl;
        this.texture = this.texture || painter.getTileTexture(img.width);
        if (this.texture) {
            this.texture.update(img, { useMipmap: true });
        } else {
            this.texture = new Texture(context, img, gl.RGBA, { useMipmap: true });
            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        }
    }
    setDependencies(namespace, dependencies) {
        const index = {};
        for (const dep of dependencies) {
            index[dep] = true;
        }
        this.dependencies[namespace] = index;
    }
    hasDependency(namespaces, keys) {
        for (const namespace of namespaces) {
            const dependencies = this.dependencies[namespace];
            if (dependencies) {
                for (const key of keys) {
                    if (dependencies[key]) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    clearQueryDebugViz() {
    }
    _makeDebugTileBoundsBuffers(context, projection) {
        if (!projection || projection.name === 'mercator' || this._tileDebugBuffer)
            return;
        // reproject tile outline with adaptive resampling
        const boundsLine = loadGeometry(BOUNDS_FEATURE, this.tileID.canonical, this.tileTransform)[0];
        // generate vertices for debugging tile boundaries
        const debugVertices = new StructArrayLayout2i4();
        const debugIndices = new StructArrayLayout1ui2();
        for (let i = 0; i < boundsLine.length; i++) {
            const {x, y} = boundsLine[i];
            debugVertices.emplaceBack(x, y);
            debugIndices.emplaceBack(i);
        }
        debugIndices.emplaceBack(0);
        this._tileDebugIndexBuffer = context.createIndexBuffer(debugIndices);
        this._tileDebugBuffer = context.createVertexBuffer(debugVertices, posAttributes.members);
        this._tileDebugSegments = SegmentVector.simpleSegment(0, 0, debugVertices.length, debugIndices.length);
    }
    _makeTileBoundsBuffers(context, projection) {
        if (this._tileBoundsBuffer || !projection || projection.name === 'mercator')
            return;
        // reproject tile outline with adaptive resampling
        const boundsLine = loadGeometry(BOUNDS_FEATURE, this.tileID.canonical, this.tileTransform)[0];
        let boundsVertices, boundsIndices;
        if (this.isRaster) {
            // for raster tiles, generate an adaptive MARTINI mesh
            const mesh = getTileMesh(this.tileID.canonical, projection);
            boundsVertices = mesh.vertices;
            boundsIndices = mesh.indices;
        } else {
            // for vector tiles, generate an Earcut triangulation of the outline
            boundsVertices = new StructArrayLayout4i8();
            boundsIndices = new StructArrayLayout3ui6();
            for (const {x, y} of boundsLine) {
                boundsVertices.emplaceBack(x, y, 0, 0);
            }
            const indices = earcut$1(boundsVertices.int16, undefined, 4);
            for (let i = 0; i < indices.length; i += 3) {
                boundsIndices.emplaceBack(indices[i], indices[i + 1], indices[i + 2]);
            }
        }
        this._tileBoundsBuffer = context.createVertexBuffer(boundsVertices, boundsAttributes.members);
        this._tileBoundsIndexBuffer = context.createIndexBuffer(boundsIndices);
        this._tileBoundsSegments = SegmentVector.simpleSegment(0, 0, boundsVertices.length, boundsIndices.length);
    }
    _makeGlobeTileDebugBuffers(context, transform) {
        const projection = transform.projection;
        if (!projection || projection.name !== 'globe' || transform.freezeTileCoverage)
            return;
        const id = this.tileID.canonical;
        const bounds = transitionTileAABBinECEF(id, transform);
        const normalizationMatrix = globeNormalizeECEF(bounds);
        const phase = globeToMercatorTransition(transform.zoom);
        let worldToECEFMatrix;
        if (phase > 0) {
            worldToECEFMatrix = mat4_1.invert(new Float64Array(16), transform.globeMatrix);
        }
        this._makeGlobeTileDebugBorderBuffer(context, id, transform, normalizationMatrix, worldToECEFMatrix, phase);
        this._makeGlobeTileDebugTextBuffer(context, id, transform, normalizationMatrix, worldToECEFMatrix, phase);
    }
    _globePoint(x, y, id, tr, normalizationMatrix, worldToECEFMatrix, phase) {
        // The following is equivalent to doing globe.projectTilePoint.
        // This way we don't recompute the normalization matrix everytime since it remains the same for all points.
        let ecef = tileCoordToECEF(x, y, id);
        if (worldToECEFMatrix) {
            // When in globe-to-Mercator transition, interpolate between globe and Mercator positions in ECEF
            const tileCount = 1 << id.z;
            // Wrap tiles to ensure that that Mercator interpolation is in the right direction
            const camX = mercatorXfromLng(tr.center.lng);
            const camY = mercatorYfromLat(tr.center.lat);
            const tileCenterX = (id.x + 0.5) / tileCount;
            const dx = tileCenterX - camX;
            let wrap = 0;
            if (dx > 0.5) {
                wrap = -1;
            } else if (dx < -0.5) {
                wrap = 1;
            }
            let mercatorX = (x / EXTENT + id.x) / tileCount + wrap;
            let mercatorY = (y / EXTENT + id.y) / tileCount;
            mercatorX = (mercatorX - camX) * tr._pixelsPerMercatorPixel + camX;
            mercatorY = (mercatorY - camY) * tr._pixelsPerMercatorPixel + camY;
            const mercatorPos = [
                mercatorX * tr.worldSize,
                mercatorY * tr.worldSize,
                0
            ];
            vec3_1.transformMat4(mercatorPos, mercatorPos, worldToECEFMatrix);
            ecef = interpolateVec3(ecef, mercatorPos, phase);
        }
        const gp = vec3_1.transformMat4(ecef, ecef, normalizationMatrix);
        return gp;
    }
    _makeGlobeTileDebugBorderBuffer(context, id, tr, normalizationMatrix, worldToECEFMatrix, phase) {
        const vertices = new StructArrayLayout2i4();
        const indices = new StructArrayLayout1ui2();
        const extraGlobe = new StructArrayLayout3i6();
        const addLine = (sx, sy, ex, ey, pointCount) => {
            const stepX = (ex - sx) / (pointCount - 1);
            const stepY = (ey - sy) / (pointCount - 1);
            const vOffset = vertices.length;
            for (let i = 0; i < pointCount; i++) {
                const x = sx + i * stepX;
                const y = sy + i * stepY;
                vertices.emplaceBack(x, y);
                const gp = this._globePoint(x, y, id, tr, normalizationMatrix, worldToECEFMatrix, phase);
                extraGlobe.emplaceBack(gp[0], gp[1], gp[2]);
                indices.emplaceBack(vOffset + i);
            }
        };
        const e = EXTENT;
        addLine(0, 0, e, 0, 16);
        addLine(e, 0, e, e, 16);
        addLine(e, e, 0, e, 16);
        addLine(0, e, 0, 0, 16);
        this._tileDebugIndexBuffer = context.createIndexBuffer(indices);
        this._tileDebugBuffer = context.createVertexBuffer(vertices, posAttributes.members);
        this._globeTileDebugBorderBuffer = context.createVertexBuffer(extraGlobe, posAttributesGlobeExt.members);
        this._tileDebugSegments = SegmentVector.simpleSegment(0, 0, vertices.length, indices.length);
    }
    _makeGlobeTileDebugTextBuffer(context, id, tr, normalizationMatrix, worldToECEFMatrix, phase) {
        const SEGMENTS = 4;
        const numVertices = SEGMENTS + 1;
        const step = EXTENT / SEGMENTS;
        const vertices = new StructArrayLayout2i4();
        const indices = new StructArrayLayout3ui6();
        const extraGlobe = new StructArrayLayout3i6();
        const totalVertices = numVertices * numVertices;
        const totalTriangles = SEGMENTS * SEGMENTS * 2;
        indices.reserve(totalTriangles);
        vertices.reserve(totalVertices);
        extraGlobe.reserve(totalVertices);
        const toIndex = (j, i) => {
            return totalVertices * j + i;
        };
        // add vertices.
        for (let j = 0; j < totalVertices; j++) {
            const y = j * step;
            for (let i = 0; i < totalVertices; i++) {
                const x = i * step;
                vertices.emplaceBack(x, y);
                const gp = this._globePoint(x, y, id, tr, normalizationMatrix, worldToECEFMatrix, phase);
                extraGlobe.emplaceBack(gp[0], gp[1], gp[2]);
            }
        }
        // add indices.
        for (let j = 0; j < SEGMENTS; j++) {
            for (let i = 0; i < SEGMENTS; i++) {
                const tl = toIndex(j, i);
                const tr = toIndex(j, i + 1);
                const bl = toIndex(j + 1, i);
                const br = toIndex(j + 1, i + 1);
                // first triangle of the sub-patch.
                indices.emplaceBack(tl, tr, bl);
                // second triangle of the sub-patch.
                indices.emplaceBack(bl, tr, br);
            }
        }
        this._tileDebugTextIndexBuffer = context.createIndexBuffer(indices);
        this._tileDebugTextBuffer = context.createVertexBuffer(vertices, posAttributes.members);
        this._globeTileDebugTextBuffer = context.createVertexBuffer(extraGlobe, posAttributesGlobeExt.members);
        this._tileDebugTextSegments = SegmentVector.simpleSegment(0, 0, totalVertices, totalTriangles);
    }
}

//      
/**
 * A [least-recently-used cache](http://en.wikipedia.org/wiki/Cache_algorithms)
 * with hash lookup made possible by keeping a list of keys in parallel to
 * an array of dictionary of values
 *
 * @private
 */
class TileCache {
    /**
     * @param {number} max The max number of permitted values.
     * @private
     * @param {Function} onRemove The callback called with items when they expire.
     */
    constructor(max, onRemove) {
        this.max = max;
        this.onRemove = onRemove;
        this.reset();
    }
    /**
     * Clear the cache.
     *
     * @returns {TileCache} Returns itself to allow for method chaining.
     * @private
     */
    reset() {
        for (const key in this.data) {
            for (const removedData of this.data[key]) {
                if (removedData.timeout)
                    clearTimeout(removedData.timeout);
                this.onRemove(removedData.value);
            }
        }
        this.data = {};
        this.order = [];
        return this;
    }
    /**
     * Add a key, value combination to the cache, trimming its size if this pushes
     * it over max length.
     *
     * @param {OverscaledTileID} tileID lookup key for the item
     * @param {*} data any value
     *
     * @returns {TileCache} Returns itself to allow for method chaining.
     * @private
     */
    add(tileID, data, expiryTimeout) {
        const key = tileID.wrapped().key;
        if (this.data[key] === undefined) {
            this.data[key] = [];
        }
        const dataWrapper = {
            value: data,
            timeout: undefined
        };
        if (expiryTimeout !== undefined) {
            dataWrapper.timeout = setTimeout(() => {
                this.remove(tileID, dataWrapper);
            }, expiryTimeout);
        }
        this.data[key].push(dataWrapper);
        this.order.push(key);
        if (this.order.length > this.max) {
            const removedData = this._getAndRemoveByKey(this.order[0]);
            if (removedData)
                this.onRemove(removedData);
        }
        return this;
    }
    /**
     * Determine whether the value attached to `key` is present
     *
     * @param {OverscaledTileID} tileID the key to be looked-up
     * @returns {boolean} whether the cache has this value
     * @private
     */
    has(tileID) {
        return tileID.wrapped().key in this.data;
    }
    /**
     * Get the value attached to a specific key and remove data from cache.
     * If the key is not found, returns `null`
     *
     * @param {OverscaledTileID} tileID the key to look up
     * @returns {*} the data, or null if it isn't found
     * @private
     */
    getAndRemove(tileID) {
        if (!this.has(tileID)) {
            return null;
        }
        return this._getAndRemoveByKey(tileID.wrapped().key);
    }
    /*
     * Get and remove the value with the specified key.
     */
    _getAndRemoveByKey(key) {
        const data = this.data[key].shift();
        if (data.timeout)
            clearTimeout(data.timeout);
        if (this.data[key].length === 0) {
            delete this.data[key];
        }
        this.order.splice(this.order.indexOf(key), 1);
        return data.value;
    }
    /*
     * Get the value with the specified (wrapped tile) key.
     */
    getByKey(key) {
        const data = this.data[key];
        return data ? data[0].value : null;
    }
    /**
     * Get the value attached to a specific key without removing data
     * from the cache. If the key is not found, returns `null`
     *
     * @param {OverscaledTileID} tileID the key to look up
     * @returns {*} the data, or null if it isn't found
     * @private
     */
    get(tileID) {
        if (!this.has(tileID)) {
            return null;
        }
        const data = this.data[tileID.wrapped().key][0];
        return data.value;
    }
    /**
     * Remove a key/value combination from the cache.
     *
     * @param {OverscaledTileID} tileID the key for the pair to delete
     * @param {Tile} value If a value is provided, remove that exact version of the value.
     * @returns {TileCache} this cache
     * @private
     */
    remove(tileID, value) {
        if (!this.has(tileID)) {
            return this;
        }
        const key = tileID.wrapped().key;
        const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value);
        const data = this.data[key][dataIndex];
        this.data[key].splice(dataIndex, 1);
        if (data.timeout)
            clearTimeout(data.timeout);
        if (this.data[key].length === 0) {
            delete this.data[key];
        }
        this.onRemove(data.value);
        this.order.splice(this.order.indexOf(key), 1);
        return this;
    }
    /**
     * Change the max size of the cache.
     *
     * @param {number} max the max size of the cache
     * @returns {TileCache} this cache
     * @private
     */
    setMaxSize(max) {
        this.max = max;
        while (this.order.length > this.max) {
            const removedData = this._getAndRemoveByKey(this.order[0]);
            if (removedData)
                this.onRemove(removedData);
        }
        return this;
    }
    /**
     * Remove entries that do not pass a filter function. Used for removing
     * stale tiles from the cache.
     *
     * @private
     * @param {function} filterFn Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out.
     */
    filter(filterFn) {
        const removed = [];
        for (const key in this.data) {
            for (const entry of this.data[key]) {
                if (!filterFn(entry.value)) {
                    removed.push(entry);
                }
            }
        }
        for (const r of removed) {
            this.remove(r.value.tileID, r);
        }
    }
}

class IndexBuffer {
    // Unique ID, iterated on construction and data upload
    constructor(context, array, dynamicDraw, noDestroy) {
        this.id = IndexBuffer.uniqueIdxCounter;
        IndexBuffer.uniqueIdxCounter++;
        this.context = context;
        const gl = context.gl;
        this.buffer = gl.createBuffer();
        this.dynamicDraw = Boolean(dynamicDraw);
        // The bound index buffer is part of vertex array object state. We don't want to
        // modify whatever VAO happens to be currently bound, so make sure the default
        // vertex array provided by the context is bound instead.
        this.context.unbindVAO();
        context.bindElementBuffer.set(this.buffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);
        if (!this.dynamicDraw && !noDestroy) {
            array.destroy();
        }
    }
    bind() {
        this.context.bindElementBuffer.set(this.buffer);
    }
    updateData(array) {
        this.id = IndexBuffer.uniqueIdxCounter;
        IndexBuffer.uniqueIdxCounter++;
        const gl = this.context.gl;
        // The right VAO will get this buffer re-bound later in VertexArrayObject#bind
        // See https://github.com/mapbox/mapbox-gl-js/issues/5620
        this.context.unbindVAO();
        this.bind();
        gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);
    }
    destroy() {
        const gl = this.context.gl;
        if (this.buffer) {
            gl.deleteBuffer(this.buffer);
            delete this.buffer;
        }
    }
}
IndexBuffer.uniqueIdxCounter = 0;

/**
 * @enum {string} AttributeType
 * @private
 * @readonly
 */
const AttributeType = {
    Int8: 'BYTE',
    Uint8: 'UNSIGNED_BYTE',
    Int16: 'SHORT',
    Uint16: 'UNSIGNED_SHORT',
    Int32: 'INT',
    Uint32: 'UNSIGNED_INT',
    Float32: 'FLOAT'
};
/**
 * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's
 * Struct type is converted to a WebGL atribute.
 * @private
 */
class VertexBuffer {
    /**
     * @param dynamicDraw Whether this buffer will be repeatedly updated.
     * @private
     */
    constructor(context, array, attributes, dynamicDraw, noDestroy, instanceCount) {
        this.length = array.length;
        this.attributes = attributes;
        this.itemSize = array.bytesPerElement;
        this.dynamicDraw = dynamicDraw;
        this.instanceCount = instanceCount;
        this.context = context;
        const gl = context.gl;
        this.buffer = gl.createBuffer();
        context.bindVertexBuffer.set(this.buffer);
        gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);
        if (!this.dynamicDraw && !noDestroy) {
            array.destroy();
        }
    }
    bind() {
        this.context.bindVertexBuffer.set(this.buffer);
    }
    updateData(array) {
        const gl = this.context.gl;
        this.bind();
        gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer);
    }
    enableAttributes(gl, program) {
        for (let j = 0; j < this.attributes.length; j++) {
            const member = this.attributes[j];
            const attribIndex = program.attributes[member.name];
            if (attribIndex !== undefined) {
                gl.enableVertexAttribArray(attribIndex);
            }
        }
    }
    /**
     * Set the attribute pointers in a WebGL context.
     * @param gl The WebGL context.
     * @param program The active WebGL program.
     * @param vertexOffset Index of the starting vertex of the segment.
     */
    setVertexAttribPointers(gl, program, vertexOffset) {
        for (let j = 0; j < this.attributes.length; j++) {
            const member = this.attributes[j];
            const attribIndex = program.attributes[member.name];
            if (attribIndex !== undefined) {
                gl.vertexAttribPointer(attribIndex, member.components, gl[AttributeType[member.type]], false, this.itemSize, member.offset + this.itemSize * (vertexOffset || 0));
            }
        }
    }
    setVertexAttribDivisor(gl, program, value) {
        for (let j = 0; j < this.attributes.length; j++) {
            const member = this.attributes[j];
            const attribIndex = program.attributes[member.name];
            if (attribIndex !== undefined && this.instanceCount && this.instanceCount > 0) {
                gl.vertexAttribDivisor(attribIndex, value);
            }
        }
    }
    /**
     * Destroy the GL buffer bound to the given WebGL context.
     */
    destroy() {
        const gl = this.context.gl;
        if (this.buffer) {
            gl.deleteBuffer(this.buffer);
            delete this.buffer;
        }
    }
}

//      
class BaseValue {
    constructor(context) {
        this.gl = context.gl;
        this.default = this.getDefault();
        this.current = this.default;
        this.dirty = false;
    }
    get() {
        return this.current;
    }
    set(value) {
    }
    getDefault() {
        return this.default;    // overriden in child classes
    }
    setDefault() {
        this.set(this.default);
    }
}
class ClearColor extends BaseValue {
    getDefault() {
        return Color$1.transparent;
    }
    set(v) {
        const c = this.current;
        if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty)
            return;
        this.gl.clearColor(v.r, v.g, v.b, v.a);
        this.current = v;
        this.dirty = false;
    }
}
class ClearDepth extends BaseValue {
    getDefault() {
        return 1;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.clearDepth(v);
        this.current = v;
        this.dirty = false;
    }
}
class ClearStencil extends BaseValue {
    getDefault() {
        return 0;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.clearStencil(v);
        this.current = v;
        this.dirty = false;
    }
}
class ColorMask extends BaseValue {
    getDefault() {
        return [
            true,
            true,
            true,
            true
        ];
    }
    set(v) {
        const c = this.current;
        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty)
            return;
        this.gl.colorMask(v[0], v[1], v[2], v[3]);
        this.current = v;
        this.dirty = false;
    }
}
class DepthMask extends BaseValue {
    getDefault() {
        return true;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.depthMask(v);
        this.current = v;
        this.dirty = false;
    }
}
class StencilMask extends BaseValue {
    getDefault() {
        return 255;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.stencilMask(v);
        this.current = v;
        this.dirty = false;
    }
}
class StencilFunc extends BaseValue {
    getDefault() {
        return {
            func: this.gl.ALWAYS,
            ref: 0,
            mask: 255
        };
    }
    set(v) {
        const c = this.current;
        if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty)
            return;
        this.gl.stencilFunc(v.func, v.ref, v.mask);
        this.current = v;
        this.dirty = false;
    }
}
class StencilOp extends BaseValue {
    getDefault() {
        const gl = this.gl;
        return [
            gl.KEEP,
            gl.KEEP,
            gl.KEEP
        ];
    }
    set(v) {
        const c = this.current;
        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty)
            return;
        this.gl.stencilOp(v[0], v[1], v[2]);
        this.current = v;
        this.dirty = false;
    }
}
class StencilTest extends BaseValue {
    getDefault() {
        return false;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        if (v) {
            gl.enable(gl.STENCIL_TEST);
        } else {
            gl.disable(gl.STENCIL_TEST);
        }
        this.current = v;
        this.dirty = false;
    }
}
class DepthRange extends BaseValue {
    getDefault() {
        return [
            0,
            1
        ];
    }
    set(v) {
        const c = this.current;
        if (v[0] === c[0] && v[1] === c[1] && !this.dirty)
            return;
        this.gl.depthRange(v[0], v[1]);
        this.current = v;
        this.dirty = false;
    }
}
class DepthTest extends BaseValue {
    getDefault() {
        return false;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        if (v) {
            gl.enable(gl.DEPTH_TEST);
        } else {
            gl.disable(gl.DEPTH_TEST);
        }
        this.current = v;
        this.dirty = false;
    }
}
class DepthFunc extends BaseValue {
    getDefault() {
        return this.gl.LESS;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.depthFunc(v);
        this.current = v;
        this.dirty = false;
    }
}
class Blend extends BaseValue {
    getDefault() {
        return false;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        if (v) {
            gl.enable(gl.BLEND);
        } else {
            gl.disable(gl.BLEND);
        }
        this.current = v;
        this.dirty = false;
    }
}
class BlendFunc extends BaseValue {
    getDefault() {
        const gl = this.gl;
        return [
            gl.ONE,
            gl.ZERO,
            gl.ONE,
            gl.ZERO
        ];
    }
    set(v) {
        const c = this.current;
        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty)
            return;
        this.gl.blendFuncSeparate(v[0], v[1], v[2], v[3]);
        this.current = v;
        this.dirty = false;
    }
}
class BlendColor extends BaseValue {
    getDefault() {
        return Color$1.transparent;
    }
    set(v) {
        const c = this.current;
        if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty)
            return;
        this.gl.blendColor(v.r, v.g, v.b, v.a);
        this.current = v;
        this.dirty = false;
    }
}
class BlendEquation extends BaseValue {
    getDefault() {
        return this.gl.FUNC_ADD;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.blendEquationSeparate(v, v);
        this.current = v;
        this.dirty = false;
    }
}
class CullFace extends BaseValue {
    getDefault() {
        return false;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        if (v) {
            gl.enable(gl.CULL_FACE);
        } else {
            gl.disable(gl.CULL_FACE);
        }
        this.current = v;
        this.dirty = false;
    }
}
class CullFaceSide extends BaseValue {
    getDefault() {
        return this.gl.BACK;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.cullFace(v);
        this.current = v;
        this.dirty = false;
    }
}
class FrontFace extends BaseValue {
    getDefault() {
        return this.gl.CCW;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.frontFace(v);
        this.current = v;
        this.dirty = false;
    }
}
let Program$1 = class Program extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.useProgram(v);
        this.current = v;
        this.dirty = false;
    }
};
class ActiveTextureUnit extends BaseValue {
    getDefault() {
        return this.gl.TEXTURE0;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.gl.activeTexture(v);
        this.current = v;
        this.dirty = false;
    }
}
class Viewport extends BaseValue {
    getDefault() {
        const gl = this.gl;
        return [
            0,
            0,
            gl.drawingBufferWidth,
            gl.drawingBufferHeight
        ];
    }
    set(v) {
        const c = this.current;
        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty)
            return;
        this.gl.viewport(v[0], v[1], v[2], v[3]);
        this.current = v;
        this.dirty = false;
    }
}
class BindFramebuffer extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.bindFramebuffer(gl.FRAMEBUFFER, v);
        this.current = v;
        this.dirty = false;
    }
}
class BindRenderbuffer extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.bindRenderbuffer(gl.RENDERBUFFER, v);
        this.current = v;
        this.dirty = false;
    }
}
class BindTexture extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.bindTexture(gl.TEXTURE_2D, v);
        this.current = v;
        this.dirty = false;
    }
}
class BindVertexBuffer extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.bindBuffer(gl.ARRAY_BUFFER, v);
        this.current = v;
        this.dirty = false;
    }
}
class BindElementBuffer extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        // Always rebind
        const gl = this.gl;
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v);
        this.current = v;
        this.dirty = false;
    }
}
class BindVertexArrayOES extends BaseValue {
    getDefault() {
        return null;
    }
    set(v) {
        if (!this.gl || v === this.current && !this.dirty)
            return;
        this.gl.bindVertexArray(v);
        this.current = v;
        this.dirty = false;
    }
}
class PixelStoreUnpack extends BaseValue {
    getDefault() {
        return 4;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.pixelStorei(gl.UNPACK_ALIGNMENT, v);
        this.current = v;
        this.dirty = false;
    }
}
class PixelStoreUnpackPremultiplyAlpha extends BaseValue {
    getDefault() {
        return false;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, v);
        this.current = v;
        this.dirty = false;
    }
}
class PixelStoreUnpackFlipY extends BaseValue {
    getDefault() {
        return false;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        const gl = this.gl;
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, v);
        this.current = v;
        this.dirty = false;
    }
}
class FramebufferAttachment extends BaseValue {
    constructor(context, parent) {
        super(context);
        this.context = context;
        this.parent = parent;
    }
    getDefault() {
        return null;
    }
}
class ColorAttachment extends FramebufferAttachment {
    setDirty() {
        this.dirty = true;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.context.bindFramebuffer.set(this.parent);
        // note: it's possible to attach a renderbuffer to the color
        // attachment point, but thus far MBGL only uses textures for color
        const gl = this.gl;
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0);
        this.current = v;
        this.dirty = false;
    }
}
class DepthRenderbufferAttachment extends FramebufferAttachment {
    attachment() {
        return this.gl.DEPTH_ATTACHMENT;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.context.bindFramebuffer.set(this.parent);
        const gl = this.gl;
        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, this.attachment(), gl.RENDERBUFFER, v);
        this.current = v;
        this.dirty = false;
    }
}
class DepthTextureAttachment extends FramebufferAttachment {
    attachment() {
        return this.gl.DEPTH_ATTACHMENT;
    }
    set(v) {
        if (v === this.current && !this.dirty)
            return;
        this.context.bindFramebuffer.set(this.parent);
        const gl = this.gl;
        gl.framebufferTexture2D(gl.FRAMEBUFFER, this.attachment(), gl.TEXTURE_2D, v, 0);
        this.current = v;
        this.dirty = false;
    }
}
class DepthStencilAttachment extends DepthRenderbufferAttachment {
    attachment() {
        return this.gl.DEPTH_STENCIL_ATTACHMENT;
    }
}

//      
class Framebuffer {
    constructor(context, width, height, hasColor, depthType) {
        this.context = context;
        this.width = width;
        this.height = height;
        const gl = context.gl;
        const fbo = this.framebuffer = gl.createFramebuffer();
        if (hasColor) {
            this.colorAttachment = new ColorAttachment(context, fbo);
        }
        if (depthType) {
            this.depthAttachmentType = depthType;
            if (depthType === 'renderbuffer') {
                this.depthAttachment = new DepthRenderbufferAttachment(context, fbo);
            } else {
                this.depthAttachment = new DepthTextureAttachment(context, fbo);
            }
        }
    }
    destroy() {
        const gl = this.context.gl;
        if (this.colorAttachment) {
            const texture = this.colorAttachment.get();
            if (texture)
                gl.deleteTexture(texture);
        }
        if (this.depthAttachment && this.depthAttachmentType) {
            if (this.depthAttachmentType === 'renderbuffer') {
                const renderbuffer = this.depthAttachment.get();
                if (renderbuffer)
                    gl.deleteRenderbuffer(renderbuffer);
            } else {
                const texture = this.depthAttachment.get();
                if (texture)
                    gl.deleteTexture(texture);
            }
        }
        gl.deleteFramebuffer(this.framebuffer);
    }
}

//      
const ALWAYS$1 = 519;
class DepthMode {
    // DepthMask enums
    constructor(depthFunc, depthMask, depthRange) {
        this.func = depthFunc;
        this.mask = depthMask;
        this.range = depthRange;
    }
}
DepthMode.ReadOnly = false;
DepthMode.ReadWrite = true;
DepthMode.disabled = new DepthMode(ALWAYS$1, DepthMode.ReadOnly, [
    0,
    1
]);

//      
const ALWAYS = 519;
const KEEP = 7680;
class StencilMode {
    constructor(test, ref, mask, fail, depthFail, pass) {
        this.test = test;
        this.ref = ref;
        this.mask = mask;
        this.fail = fail;
        this.depthFail = depthFail;
        this.pass = pass;
    }
}
StencilMode.disabled = new StencilMode({
    func: ALWAYS,
    mask: 0
}, 0, 0, KEEP, KEEP, KEEP);

//      
const ZERO = 0;
const ONE = 1;
const ONE_MINUS_SRC_ALPHA = 771;
const DST_COLOR = 774;
class ColorMode {
    constructor(blendFunction, blendColor, mask, blendEquation) {
        this.blendFunction = blendFunction;
        this.blendColor = blendColor;
        this.mask = mask;
        this.blendEquation = blendEquation;
    }
}
ColorMode.Replace = [
    ONE,
    ZERO,
    ONE,
    ZERO
];
ColorMode.disabled = new ColorMode(ColorMode.Replace, Color$1.transparent, [
    false,
    false,
    false,
    false
]);
ColorMode.unblended = new ColorMode(ColorMode.Replace, Color$1.transparent, [
    true,
    true,
    true,
    true
]);
ColorMode.alphaBlended = new ColorMode([
    ONE,
    ONE_MINUS_SRC_ALPHA,
    ONE,
    ONE_MINUS_SRC_ALPHA
], Color$1.transparent, [
    true,
    true,
    true,
    true
]);
ColorMode.multiply = new ColorMode([
    DST_COLOR,
    ZERO,
    DST_COLOR,
    ZERO
], Color$1.transparent, [
    true,
    true,
    true,
    true
]);

//      
const BACK = 1029;
const FRONT = 1028;
const CCW = 2305;
const CW = 2304;
class CullFaceMode {
    constructor(enable, mode, frontFace) {
        this.enable = enable;
        this.mode = mode;
        this.frontFace = frontFace;
    }
}
CullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);
CullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);
CullFaceMode.backCW = new CullFaceMode(true, BACK, CW);
CullFaceMode.frontCW = new CullFaceMode(true, FRONT, CW);
CullFaceMode.frontCCW = new CullFaceMode(true, FRONT, CCW);

//      
class Context {
    constructor(gl) {
        this.gl = gl;
        this.clearColor = new ClearColor(this);
        this.clearDepth = new ClearDepth(this);
        this.clearStencil = new ClearStencil(this);
        this.colorMask = new ColorMask(this);
        this.depthMask = new DepthMask(this);
        this.stencilMask = new StencilMask(this);
        this.stencilFunc = new StencilFunc(this);
        this.stencilOp = new StencilOp(this);
        this.stencilTest = new StencilTest(this);
        this.depthRange = new DepthRange(this);
        this.depthTest = new DepthTest(this);
        this.depthFunc = new DepthFunc(this);
        this.blend = new Blend(this);
        this.blendFunc = new BlendFunc(this);
        this.blendColor = new BlendColor(this);
        this.blendEquation = new BlendEquation(this);
        this.cullFace = new CullFace(this);
        this.cullFaceSide = new CullFaceSide(this);
        this.frontFace = new FrontFace(this);
        this.program = new Program$1(this);
        this.activeTexture = new ActiveTextureUnit(this);
        this.viewport = new Viewport(this);
        this.bindFramebuffer = new BindFramebuffer(this);
        this.bindRenderbuffer = new BindRenderbuffer(this);
        this.bindTexture = new BindTexture(this);
        this.bindVertexBuffer = new BindVertexBuffer(this);
        this.bindElementBuffer = new BindElementBuffer(this);
        this.bindVertexArrayOES = new BindVertexArrayOES(this);
        this.pixelStoreUnpack = new PixelStoreUnpack(this);
        this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);
        this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this);
        this.extTextureFilterAnisotropic = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
        if (this.extTextureFilterAnisotropic) {
            this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
        }
        this.extTextureFilterAnisotropicForceOff = false;
        this.extStandardDerivativesForceOff = false;
        this.extDebugRendererInfo = gl.getExtension('WEBGL_debug_renderer_info');
        if (this.extDebugRendererInfo) {
            this.renderer = gl.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL);
            this.vendor = gl.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL);
        }
        this.extTextureFloatLinear = gl.getExtension('OES_texture_float_linear');
        this.extRenderToTextureHalfFloat = gl.getExtension('EXT_color_buffer_half_float');
        this.extTimerQuery = gl.getExtension('EXT_disjoint_timer_query_webgl2');
        this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
    }
    setDefault() {
        this.unbindVAO();
        this.clearColor.setDefault();
        this.clearDepth.setDefault();
        this.clearStencil.setDefault();
        this.colorMask.setDefault();
        this.depthMask.setDefault();
        this.stencilMask.setDefault();
        this.stencilFunc.setDefault();
        this.stencilOp.setDefault();
        this.stencilTest.setDefault();
        this.depthRange.setDefault();
        this.depthTest.setDefault();
        this.depthFunc.setDefault();
        this.blend.setDefault();
        this.blendFunc.setDefault();
        this.blendColor.setDefault();
        this.blendEquation.setDefault();
        this.cullFace.setDefault();
        this.cullFaceSide.setDefault();
        this.frontFace.setDefault();
        this.program.setDefault();
        this.activeTexture.setDefault();
        this.bindFramebuffer.setDefault();
        this.pixelStoreUnpack.setDefault();
        this.pixelStoreUnpackPremultiplyAlpha.setDefault();
        this.pixelStoreUnpackFlipY.setDefault();
    }
    setDirty() {
        this.clearColor.dirty = true;
        this.clearDepth.dirty = true;
        this.clearStencil.dirty = true;
        this.colorMask.dirty = true;
        this.depthMask.dirty = true;
        this.stencilMask.dirty = true;
        this.stencilFunc.dirty = true;
        this.stencilOp.dirty = true;
        this.stencilTest.dirty = true;
        this.depthRange.dirty = true;
        this.depthTest.dirty = true;
        this.depthFunc.dirty = true;
        this.blend.dirty = true;
        this.blendFunc.dirty = true;
        this.blendColor.dirty = true;
        this.blendEquation.dirty = true;
        this.cullFace.dirty = true;
        this.cullFaceSide.dirty = true;
        this.frontFace.dirty = true;
        this.program.dirty = true;
        this.activeTexture.dirty = true;
        this.viewport.dirty = true;
        this.bindFramebuffer.dirty = true;
        this.bindRenderbuffer.dirty = true;
        this.bindTexture.dirty = true;
        this.bindVertexBuffer.dirty = true;
        this.bindElementBuffer.dirty = true;
        this.bindVertexArrayOES.dirty = true;
        this.pixelStoreUnpack.dirty = true;
        this.pixelStoreUnpackPremultiplyAlpha.dirty = true;
        this.pixelStoreUnpackFlipY.dirty = true;
    }
    createIndexBuffer(array, dynamicDraw, noDestroy) {
        return new IndexBuffer(this, array, dynamicDraw, noDestroy);
    }
    createVertexBuffer(array, attributes, dynamicDraw, noDestroy, instanceCount) {
        return new VertexBuffer(this, array, attributes, dynamicDraw, noDestroy, instanceCount);
    }
    createRenderbuffer(storageFormat, width, height) {
        const gl = this.gl;
        const rbo = gl.createRenderbuffer();
        this.bindRenderbuffer.set(rbo);
        gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height);
        this.bindRenderbuffer.set(null);
        return rbo;
    }
    createFramebuffer(width, height, hasColor, depthType) {
        return new Framebuffer(this, width, height, hasColor, depthType);
    }
    clear({color, depth, stencil, colorMask}) {
        const gl = this.gl;
        let mask = 0;
        if (color) {
            mask |= gl.COLOR_BUFFER_BIT;
            this.clearColor.set(color);
            if (colorMask) {
                this.colorMask.set(colorMask);
            } else {
                this.colorMask.set([
                    true,
                    true,
                    true,
                    true
                ]);
            }
        }
        if (typeof depth !== 'undefined') {
            mask |= gl.DEPTH_BUFFER_BIT;
            // Workaround for platforms where clearDepth doesn't seem to work
            // without reseting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437
            this.depthRange.set([
                0,
                1
            ]);
            this.clearDepth.set(depth);
            this.depthMask.set(true);
        }
        if (typeof stencil !== 'undefined') {
            mask |= gl.STENCIL_BUFFER_BIT;
            this.clearStencil.set(stencil);
            this.stencilMask.set(255);
        }
        gl.clear(mask);
    }
    setCullFace(cullFaceMode) {
        if (cullFaceMode.enable === false) {
            this.cullFace.set(false);
        } else {
            this.cullFace.set(true);
            this.cullFaceSide.set(cullFaceMode.mode);
            this.frontFace.set(cullFaceMode.frontFace);
        }
    }
    setDepthMode(depthMode) {
        if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) {
            this.depthTest.set(false);
        } else {
            this.depthTest.set(true);
            this.depthFunc.set(depthMode.func);
            this.depthMask.set(depthMode.mask);
            this.depthRange.set(depthMode.range);
        }
    }
    setStencilMode(stencilMode) {
        if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) {
            this.stencilTest.set(false);
        } else {
            this.stencilTest.set(true);
            this.stencilMask.set(stencilMode.mask);
            this.stencilOp.set([
                stencilMode.fail,
                stencilMode.depthFail,
                stencilMode.pass
            ]);
            this.stencilFunc.set({
                func: stencilMode.test.func,
                ref: stencilMode.ref,
                mask: stencilMode.test.mask
            });
        }
    }
    setColorMode(colorMode) {
        if (deepEqual(colorMode.blendFunction, ColorMode.Replace)) {
            this.blend.set(false);
        } else {
            this.blend.set(true);
            this.blendFunc.set(colorMode.blendFunction);
            this.blendColor.set(colorMode.blendColor);
            if (colorMode.blendEquation) {
                this.blendEquation.set(colorMode.blendEquation);
            } else {
                this.blendEquation.setDefault();
            }
        }
        this.colorMask.set(colorMode.mask);
    }
    unbindVAO() {
        // Unbinding the VAO prevents other things (custom layers, new buffer creation) from
        // unintentionally changing the state of the last VAO used.
        this.bindVertexArrayOES.set(null);
    }
}

//      
/**
 * `SourceCache` is responsible for
 *
 *  - creating an instance of `Source`
 *  - forwarding events from `Source`
 *  - caching tiles loaded from an instance of `Source`
 *  - loading the tiles needed to render a given viewport
 *  - unloading the cached tiles not needed to render a given viewport
 *
 * @private
 */
class SourceCache extends Evented {
    constructor(id, source, onlySymbols) {
        super();
        this.id = id;
        this._onlySymbols = onlySymbols;
        source.on('data', e => {
            // this._sourceLoaded signifies that the TileJSON is loaded if applicable.
            // if the source type does not come with a TileJSON, the flag signifies the
            // source data has loaded (in other words, GeoJSON has been tiled on the worker and is ready)
            if (e.dataType === 'source' && e.sourceDataType === 'metadata')
                this._sourceLoaded = true;
            // for sources with mutable data, this event fires when the underlying data
            // to a source is changed (for example, using [GeoJSONSource#setData](https://docs.mapbox.com/mapbox-gl-js/api/sources/#geojsonsource#setdata) or [ImageSource#setCoordinates](https://docs.mapbox.com/mapbox-gl-js/api/sources/#imagesource#setcoordinates))
            if (this._sourceLoaded && !this._paused && e.dataType === 'source' && e.sourceDataType === 'content') {
                this.reload();
                if (this.transform) {
                    this.update(this.transform);
                }
            }
        });
        source.on('error', () => {
            this._sourceErrored = true;
        });
        this._source = source;
        this._tiles = {};
        // $FlowFixMe[method-unbinding]
        this._cache = new TileCache(0, this._unloadTile.bind(this));
        this._timers = {};
        this._cacheTimers = {};
        this._minTileCacheSize = source.minTileCacheSize;
        this._maxTileCacheSize = source.maxTileCacheSize;
        this._loadedParentTiles = {};
        this.castsShadows = false;
        this._coveredTiles = {};
        this._shadowCasterTiles = {};
        this._state = new SourceFeatureState();
        this._isRaster = this._source.type === 'raster' || this._source.type === 'raster-dem' || this._source.type === 'custom' && this._source._dataType === 'raster';
    }
    onAdd(map) {
        this.map = map;
        this._minTileCacheSize = this._minTileCacheSize === undefined && map ? map._minTileCacheSize : this._minTileCacheSize;
        this._maxTileCacheSize = this._maxTileCacheSize === undefined && map ? map._maxTileCacheSize : this._maxTileCacheSize;
    }
    /**
     * Return true if no tile data is pending, tiles will not change unless
     * an additional API call is received.
     * @private
     */
    loaded() {
        if (this._sourceErrored) {
            return true;
        }
        if (!this._sourceLoaded) {
            return false;
        }
        if (!this._source.loaded()) {
            return false;
        }
        for (const t in this._tiles) {
            const tile = this._tiles[t];
            if (tile.state !== 'errored' && (tile.state !== 'loaded' || !tile.bucketsLoaded()))
                return false;
        }
        return true;
    }
    getSource() {
        return this._source;
    }
    pause() {
        this._paused = true;
    }
    resume() {
        if (!this._paused)
            return;
        const shouldReload = this._shouldReloadOnResume;
        this._paused = false;
        this._shouldReloadOnResume = false;
        if (shouldReload)
            this.reload();
        if (this.transform)
            this.update(this.transform);
    }
    _loadTile(tile, callback) {
        tile.isSymbolTile = this._onlySymbols;
        tile.isExtraShadowCaster = this._shadowCasterTiles[tile.tileID.key];
        return this._source.loadTile(tile, callback);
    }
    _unloadTile(tile) {
        if (this._source.unloadTile)
            return this._source.unloadTile(tile, () => {
            });
    }
    _abortTile(tile) {
        if (this._source.abortTile)
            return this._source.abortTile(tile, () => {
            });
    }
    serialize() {
        return this._source.serialize();
    }
    prepare(context) {
        if (this._source.prepare) {
            this._source.prepare();
        }
        this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);
        for (const i in this._tiles) {
            const tile = this._tiles[i];
            tile.upload(context);
            tile.prepare(this.map.style.imageManager, this.map ? this.map.painter : null, this._source.scope);
        }
    }
    /**
     * Return all tile ids ordered with z-order, and cast to numbers
     * @private
     */
    getIds() {
        return values(this._tiles).map(tile => tile.tileID).sort(compareTileId).map(id => id.key);
    }
    getRenderableIds(symbolLayer, includeShadowCasters) {
        const renderables = [];
        for (const id in this._tiles) {
            if (this._isIdRenderable(+id, symbolLayer, includeShadowCasters))
                renderables.push(this._tiles[id]);
        }
        if (symbolLayer) {
            return renderables.sort((a_, b_) => {
                const a = a_.tileID;
                const b = b_.tileID;
                const rotatedA = new Point$2(a.canonical.x, a.canonical.y)._rotate(this.transform.angle);
                const rotatedB = new Point$2(b.canonical.x, b.canonical.y)._rotate(this.transform.angle);
                return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;
            }).map(tile => tile.tileID.key);
        }
        return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);
    }
    hasRenderableParent(tileID) {
        const parentTile = this.findLoadedParent(tileID, 0);
        if (parentTile) {
            return this._isIdRenderable(parentTile.tileID.key);
        }
        return false;
    }
    _isIdRenderable(id, symbolLayer, includeShadowCasters) {
        return this._tiles[id] && this._tiles[id].hasData() && !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade()) && (includeShadowCasters || !this._shadowCasterTiles[id]);
    }
    reload() {
        if (this._paused) {
            this._shouldReloadOnResume = true;
            return;
        }
        this._cache.reset();
        for (const i in this._tiles) {
            if (this._tiles[i].state !== 'errored')
                this._reloadTile(+i, 'reloading');
        }
    }
    _reloadTile(id, state) {
        const tile = this._tiles[id];
        // this potentially does not address all underlying
        // issues https://github.com/mapbox/mapbox-gl-js/issues/4252
        // - hard to tell without repro steps
        if (!tile)
            return;
        // The difference between "loading" tiles and "reloading" or "expired"
        // tiles is that "reloading"/"expired" tiles are "renderable".
        // Therefore, a "loading" tile cannot become a "reloading" tile without
        // first becoming a "loaded" tile.
        if (tile.state !== 'loading') {
            tile.state = state;
        }
        // $FlowFixMe[method-unbinding]
        this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));
    }
    _tileLoaded(tile, id, previousState, err) {
        if (err) {
            tile.state = 'errored';
            if (err.status !== 404)
                this._source.fire(new ErrorEvent(err, { tile }));
            else {
                // continue to try loading parent/children tiles if a tile doesn't exist (404)
                const updateForTerrain = this._source.type === 'raster-dem' && this.usedForTerrain;
                if (updateForTerrain && this.map.painter.terrain) {
                    const terrain = this.map.painter.terrain;
                    this.update(this.transform, terrain.getScaledDemTileSize(), true);
                    terrain.resetTileLookupCache(this.id);
                } else {
                    this.update(this.transform);
                }
            }
            return;
        }
        tile.timeAdded = exported$1.now();
        if (previousState === 'expired')
            tile.refreshedUponExpiration = true;
        this._setTileReloadTimer(id, tile);
        if (this._source.type === 'raster-dem' && tile.dem)
            this._backfillDEM(tile);
        this._state.initializeTileState(tile, this.map ? this.map.painter : null);
        this._source.fire(new Event('data', {
            dataType: 'source',
            tile,
            coord: tile.tileID,
            'sourceCacheId': this.id
        }));
    }
    /**
    * For raster terrain source, backfill DEM to eliminate visible tile boundaries
    * @private
    */
    _backfillDEM(tile) {
        const renderables = this.getRenderableIds();
        for (let i = 0; i < renderables.length; i++) {
            const borderId = renderables[i];
            if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {
                const borderTile = this.getTileByID(borderId);
                fillBorder(tile, borderTile);
                fillBorder(borderTile, tile);
            }
        }
        function fillBorder(tile, borderTile) {
            if (!tile.dem || tile.dem.borderReady)
                return;
            tile.needsHillshadePrepare = true;
            tile.needsDEMTextureUpload = true;
            let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;
            const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;
            const dim = Math.pow(2, tile.tileID.canonical.z);
            const borderId = borderTile.tileID.key;
            if (dx === 0 && dy === 0)
                return;
            if (Math.abs(dy) > 1) {
                return;
            }
            if (Math.abs(dx) > 1) {
                // Adjust the delta coordinate for world wraparound.
                if (Math.abs(dx + dim) === 1) {
                    dx += dim;
                } else if (Math.abs(dx - dim) === 1) {
                    dx -= dim;
                }
            }
            if (!borderTile.dem || !tile.dem)
                return;
            tile.dem.backfillBorder(borderTile.dem, dx, dy);
            if (tile.neighboringTiles && tile.neighboringTiles[borderId])
                tile.neighboringTiles[borderId].backfilled = true;
        }
    }
    /**
     * Get a specific tile by TileID
     * @private
     */
    getTile(tileID) {
        return this.getTileByID(tileID.key);
    }
    /**
     * Get a specific tile by id
     * @private
     */
    getTileByID(id) {
        return this._tiles[id];
    }
    /**
     * For a given set of tiles, retain children that are loaded and have a zoom
     * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive)
     * @private
     */
    _retainLoadedChildren(idealTiles, zoom, maxCoveringZoom, retain) {
        for (const id in this._tiles) {
            let tile = this._tiles[id];
            // only consider renderable tiles up to maxCoveringZoom
            if (retain[id] || !tile.hasData() || tile.tileID.overscaledZ <= zoom || tile.tileID.overscaledZ > maxCoveringZoom)
                continue;
            // loop through parents and retain the topmost loaded one if found
            let topmostLoadedID = tile.tileID;
            while (tile && tile.tileID.overscaledZ > zoom + 1) {
                const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1);
                tile = this._tiles[parentID.key];
                if (tile && tile.hasData()) {
                    topmostLoadedID = parentID;
                }
            }
            // loop through ancestors of the topmost loaded child to see if there's one that needed it
            let tileID = topmostLoadedID;
            while (tileID.overscaledZ > zoom) {
                tileID = tileID.scaledTo(tileID.overscaledZ - 1);
                if (idealTiles[tileID.key]) {
                    // found a parent that needed a loaded child; retain that child
                    retain[topmostLoadedID.key] = topmostLoadedID;
                    break;
                }
            }
        }
    }
    /**
     * Find a loaded parent of the given tile (up to minCoveringZoom)
     * @private
     */
    findLoadedParent(tileID, minCoveringZoom) {
        if (tileID.key in this._loadedParentTiles) {
            const parent = this._loadedParentTiles[tileID.key];
            if (parent && parent.tileID.overscaledZ >= minCoveringZoom) {
                return parent;
            } else {
                return null;
            }
        }
        for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {
            const parentTileID = tileID.scaledTo(z);
            const tile = this._getLoadedTile(parentTileID);
            if (tile) {
                return tile;
            }
        }
    }
    _getLoadedTile(tileID) {
        const tile = this._tiles[tileID.key];
        if (tile && tile.hasData()) {
            return tile;
        }
        // TileCache ignores wrap in lookup.
        const cachedTile = this._cache.getByKey(this._source.reparseOverscaled ? tileID.wrapped().key : tileID.canonical.key);
        return cachedTile;
    }
    /**
     * Resizes the tile cache based on the current viewport's size
     * or the minTileCacheSize and maxTileCacheSize options passed during map creation
     *
     * Larger viewports use more tiles and need larger caches. Larger viewports
     * are more likely to be found on devices with more memory and on pages where
     * the map is more important.
     * @private
     */
    updateCacheSize(transform, tileSize) {
        tileSize = tileSize || this._source.tileSize;
        const widthInTiles = Math.ceil(transform.width / tileSize) + 1;
        const heightInTiles = Math.ceil(transform.height / tileSize) + 1;
        const approxTilesInView = widthInTiles * heightInTiles;
        const commonZoomRange = 5;
        const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);
        const minSize = typeof this._minTileCacheSize === 'number' ? Math.max(this._minTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;
        const maxSize = typeof this._maxTileCacheSize === 'number' ? Math.min(this._maxTileCacheSize, minSize) : minSize;
        this._cache.setMaxSize(maxSize);
    }
    handleWrapJump(lng) {
        // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify
        // which copy of the world the tile belongs to. For example, at `lng: 10` you
        // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1.
        //
        // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect
        // to see the same thing on the screen (370 degrees and 10 degrees is the same
        // place in the world) but all the TileIDs will have different wrap values.
        //
        // In order to make this transition seamless, we calculate the rounded difference of
        // "worlds" between the last frame and the current frame. If the map panned by
        // a world, then we can assign all the tiles new TileIDs with updated wrap values.
        // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered
        // in a different position.
        //
        // This enables us to reuse the tiles at more ideal locations and prevent flickering.
        const prevLng = this._prevLng === undefined ? lng : this._prevLng;
        const lngDifference = lng - prevLng;
        const worldDifference = lngDifference / 360;
        const wrapDelta = Math.round(worldDifference);
        this._prevLng = lng;
        if (wrapDelta) {
            const tiles = {};
            for (const key in this._tiles) {
                const tile = this._tiles[key];
                tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);
                tiles[tile.tileID.key] = tile;
            }
            this._tiles = tiles;
            // Reset tile reload timers
            for (const id in this._timers) {
                clearTimeout(this._timers[id]);
                delete this._timers[id];
            }
            for (const id in this._tiles) {
                const tile = this._tiles[id];
                this._setTileReloadTimer(+id, tile);
            }
        }
    }
    /**
     * Removes tiles that are outside the viewport and adds new tiles that
     * are inside the viewport.
     * @private
     * @param {boolean} updateForTerrain Signals to update tiles even if the
     * source is not used (this.used) by layers: it is used for terrain.
     * @param {tileSize} tileSize If needed to get lower resolution ideal cover,
     * override source.tileSize used in tile cover calculation.
     */
    update(transform, tileSize, updateForTerrain, directionalLight) {
        this.transform = transform;
        if (!this._sourceLoaded || this._paused || this.transform.freezeTileCoverage) {
            return;
        }
        if (this.usedForTerrain && !updateForTerrain) {
            // If source is used for both terrain and hillshade, don't update it twice.
            return;
        }
        this.updateCacheSize(transform, tileSize);
        if (this.transform.projection.name !== 'globe') {
            this.handleWrapJump(this.transform.center.lng);
        }
        // Tiles acting as shadow casters can be included in the ideal set
        // even though they might not be visible on the screen.
        this._shadowCasterTiles = {};
        // Covered is a list of retained tiles who's areas are fully covered by other,
        // better, retained tiles. They are not drawn separately.
        this._coveredTiles = {};
        let idealTileIDs;
        if (!this.used && !this.usedForTerrain) {
            idealTileIDs = [];
        } else if (this._source.tileID) {
            idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID).map(unwrapped => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));
        } else {
            idealTileIDs = transform.coveringTiles({
                tileSize: tileSize || this._source.tileSize,
                minzoom: this._source.minzoom,
                maxzoom: this._source.maxzoom,
                roundZoom: this._source.roundZoom && !updateForTerrain,
                reparseOverscaled: this._source.reparseOverscaled,
                isTerrainDEM: this.usedForTerrain
            });
            if (this._source.hasTile) {
                idealTileIDs = idealTileIDs.filter(coord => this._source.hasTile(coord));
            }
        }
        if (idealTileIDs.length > 0 && this.castsShadows && directionalLight && this.transform.projection.name !== 'globe' && !this.usedForTerrain && !isRasterType(this._source.type)) {
            // compute desired max zoom level
            const coveringZoom = transform.coveringZoomLevel({
                tileSize: tileSize || this._source.tileSize,
                roundZoom: this._source.roundZoom && !updateForTerrain
            });
            const idealZoom = Math.min(coveringZoom, this._source.maxzoom);
            // find shadowCasterTiles
            const shadowCasterTileIDs = transform.extendTileCoverForShadows(idealTileIDs, directionalLight, idealZoom);
            for (const id of shadowCasterTileIDs) {
                this._shadowCasterTiles[id.key] = true;
                idealTileIDs.push(id);
            }
        }
        // Retain is a list of tiles that we shouldn't delete, even if they are not
        // the most ideal tile for the current viewport. This may include tiles like
        // parent or child tiles that are *already* loaded.
        const retain = this._updateRetainedTiles(idealTileIDs);
        if (isRasterType(this._source.type) && idealTileIDs.length !== 0) {
            const parentsForFading = {};
            const fadingTiles = {};
            const ids = Object.keys(retain);
            for (const id of ids) {
                const tileID = retain[id];
                const tile = this._tiles[id];
                if (!tile || tile.fadeEndTime && tile.fadeEndTime <= exported$1.now())
                    continue;
                // if the tile is loaded but still fading in, find parents to cross-fade with it
                const parentTile = this.findLoadedParent(tileID, Math.max(tileID.overscaledZ - SourceCache.maxOverzooming, this._source.minzoom));
                if (parentTile) {
                    this._addTile(parentTile.tileID);
                    parentsForFading[parentTile.tileID.key] = parentTile.tileID;
                }
                fadingTiles[id] = tileID;
            }
            // for children tiles with parent tiles still fading in,
            // retain the children so the parent can fade on top
            const minZoom = idealTileIDs[idealTileIDs.length - 1].overscaledZ;
            for (const id in this._tiles) {
                const childTile = this._tiles[id];
                if (retain[id] || !childTile.hasData()) {
                    continue;
                }
                let parentID = childTile.tileID;
                while (parentID.overscaledZ > minZoom) {
                    parentID = parentID.scaledTo(parentID.overscaledZ - 1);
                    const tile = this._tiles[parentID.key];
                    if (tile && tile.hasData() && fadingTiles[parentID.key]) {
                        retain[id] = childTile.tileID;
                        break;
                    }
                }
            }
            for (const id in parentsForFading) {
                if (!retain[id]) {
                    // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own.
                    this._coveredTiles[id] = true;
                    retain[id] = parentsForFading[id];
                }
            }
        }
        for (const retainedId in retain) {
            // Make sure retained tiles always clear any existing fade holds
            // so that if they're removed again their fade timer starts fresh.
            this._tiles[retainedId].clearFadeHold();
        }
        // Remove the tiles we don't need anymore.
        const remove = keysDifference(this._tiles, retain);
        for (const tileID of remove) {
            const tile = this._tiles[tileID];
            if (tile.hasSymbolBuckets && !tile.holdingForFade()) {
                tile.setHoldDuration(this.map._fadeDuration);
            } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) {
                this._removeTile(+tileID);
            }
        }
        // Construct a cache of loaded parents
        this._updateLoadedParentTileCache();
        if (this._onlySymbols && this._source.afterUpdate) {
            this._source.afterUpdate();
        }
    }
    releaseSymbolFadeTiles() {
        for (const id in this._tiles) {
            if (this._tiles[id].holdingForFade()) {
                this._removeTile(+id);
            }
        }
    }
    _updateRetainedTiles(idealTileIDs) {
        const retain = {};
        if (idealTileIDs.length === 0) {
            return retain;
        }
        const checked = {};
        const minZoom = idealTileIDs.reduce((min, id) => Math.min(min, id.overscaledZ), Infinity);
        const maxZoom = idealTileIDs[0].overscaledZ;
        const minCoveringZoom = Math.max(maxZoom - SourceCache.maxOverzooming, this._source.minzoom);
        const maxCoveringZoom = Math.max(maxZoom + SourceCache.maxUnderzooming, this._source.minzoom);
        const missingTiles = {};
        for (const tileID of idealTileIDs) {
            const tile = this._addTile(tileID);
            // retain the tile even if it's not loaded because it's an ideal tile.
            retain[tileID.key] = tileID;
            if (tile.hasData())
                continue;
            if (minZoom < this._source.maxzoom) {
                // save missing tiles that potentially have loaded children
                missingTiles[tileID.key] = tileID;
            }
        }
        // retain any loaded children of ideal tiles up to maxCoveringZoom
        this._retainLoadedChildren(missingTiles, minZoom, maxCoveringZoom, retain);
        for (const tileID of idealTileIDs) {
            let tile = this._tiles[tileID.key];
            if (tile.hasData())
                continue;
            // The tile we require is not yet loaded or does not exist;
            // Attempt to find children that fully cover it.
            if (tileID.canonical.z >= this._source.maxzoom) {
                // We're looking for an overzoomed child tile.
                const childCoord = tileID.children(this._source.maxzoom)[0];
                const childTile = this.getTile(childCoord);
                if (!!childTile && childTile.hasData()) {
                    retain[childCoord.key] = childCoord;
                    continue;    // tile is covered by overzoomed child
                }
            } else {
                // Check if all 4 immediate children are loaded (in other words, the missing ideal tile is covered)
                const children = tileID.children(this._source.maxzoom);
                if (retain[children[0].key] && retain[children[1].key] && retain[children[2].key] && retain[children[3].key])
                    continue;    // tile is covered by children
            }
            // We couldn't find child tiles that entirely cover the ideal tile; look for parents now.
            // As we ascend up the tile pyramid of the ideal tile, we check whether the parent
            // tile has been previously requested (and errored because we only loop over tiles with no data)
            // in order to determine if we need to request its parent.
            let parentWasRequested = tile.wasRequested();
            for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {
                const parentId = tileID.scaledTo(overscaledZ);
                // Break parent tile ascent if this route has been previously checked by another child.
                if (checked[parentId.key])
                    break;
                checked[parentId.key] = true;
                tile = this.getTile(parentId);
                if (!tile && parentWasRequested) {
                    tile = this._addTile(parentId);
                }
                if (tile) {
                    retain[parentId.key] = parentId;
                    // Save the current values, since they're the parent of the next iteration
                    // of the parent tile ascent loop.
                    parentWasRequested = tile.wasRequested();
                    if (tile.hasData())
                        break;
                }
            }
        }
        return retain;
    }
    _updateLoadedParentTileCache() {
        this._loadedParentTiles = {};
        for (const tileKey in this._tiles) {
            const path = [];
            let parentTile;
            let currentId = this._tiles[tileKey].tileID;
            // Find the closest loaded ancestor by traversing the tile tree towards the root and
            // caching results along the way
            while (currentId.overscaledZ > 0) {
                // Do we have a cached result from previous traversals?
                if (currentId.key in this._loadedParentTiles) {
                    parentTile = this._loadedParentTiles[currentId.key];
                    break;
                }
                path.push(currentId.key);
                // Is the parent loaded?
                const parentId = currentId.scaledTo(currentId.overscaledZ - 1);
                parentTile = this._getLoadedTile(parentId);
                if (parentTile) {
                    break;
                }
                currentId = parentId;
            }
            // Cache the result of this traversal to all newly visited tiles
            for (const key of path) {
                this._loadedParentTiles[key] = parentTile;
            }
        }
    }
    /**
     * Add a tile, given its coordinate, to the pyramid.
     * @private
     */
    _addTile(tileID) {
        let tile = this._tiles[tileID.key];
        const isExtraShadowCaster = !!this._shadowCasterTiles[tileID.key];
        if (tile) {
            if (tile.isExtraShadowCaster === true && !isExtraShadowCaster) {
                // If the tile changed shadow visibility we need to relayout
                this._reloadTile(tileID.key, 'reloading');
            }
            return tile;
        }
        tile = this._cache.getAndRemove(tileID);
        if (tile) {
            this._setTileReloadTimer(tileID.key, tile);
            // set the tileID because the cached tile could have had a different wrap value
            tile.tileID = tileID;
            this._state.initializeTileState(tile, this.map ? this.map.painter : null);
            if (this._cacheTimers[tileID.key]) {
                clearTimeout(this._cacheTimers[tileID.key]);
                delete this._cacheTimers[tileID.key];
                this._setTileReloadTimer(tileID.key, tile);
            }
        }
        const cached = Boolean(tile);
        if (!cached) {
            const painter = this.map ? this.map.painter : null;
            tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), this.transform.tileZoom, painter, this._isRaster);
            // $FlowFixMe[method-unbinding]
            this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));
        }
        // Impossible, but silence flow.
        if (!tile)
            return null;
        tile.uses++;
        this._tiles[tileID.key] = tile;
        if (!cached)
            this._source.fire(new Event('dataloading', {
                tile,
                coord: tile.tileID,
                dataType: 'source'
            }));
        return tile;
    }
    _setTileReloadTimer(id, tile) {
        if (id in this._timers) {
            clearTimeout(this._timers[id]);
            delete this._timers[id];
        }
        const expiryTimeout = tile.getExpiryTimeout();
        if (expiryTimeout) {
            this._timers[id] = setTimeout(() => {
                this._reloadTile(id, 'expired');
                delete this._timers[id];
            }, expiryTimeout);
        }
    }
    /**
     * Remove a tile, given its id, from the pyramid
     * @private
     */
    _removeTile(id) {
        const tile = this._tiles[id];
        if (!tile)
            return;
        tile.uses--;
        delete this._tiles[id];
        if (this._timers[id]) {
            clearTimeout(this._timers[id]);
            delete this._timers[id];
        }
        if (tile.uses > 0)
            return;
        if (tile.hasData() && tile.state !== 'reloading') {
            this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());
        } else {
            tile.aborted = true;
            this._abortTile(tile);
            this._unloadTile(tile);
        }
    }
    /**
     * Remove all tiles from this pyramid.
     * @private
     */
    clearTiles() {
        this._shouldReloadOnResume = false;
        this._paused = false;
        for (const id in this._tiles)
            this._removeTile(+id);
        if (this._source._clear)
            this._source._clear();
        this._cache.reset();
        if (this.map && this.usedForTerrain && this.map.painter.terrain) {
            this.map.painter.terrain.resetTileLookupCache(this.id);
        }
    }
    /**
     * Search through our current tiles and attempt to find the tiles that cover the given `queryGeometry`.
     *
     * @param {QueryGeometry} queryGeometry
     * @param {boolean} [visualizeQueryGeometry=false]
     * @param {boolean} use3DQuery
     * @returns
     * @private
     */
    tilesIn(queryGeometry, use3DQuery, visualizeQueryGeometry) {
        const tileResults = [];
        const transform = this.transform;
        if (!transform)
            return tileResults;
        const isGlobe = transform.projection.name === 'globe';
        const centerX = mercatorXfromLng(transform.center.lng);
        for (const tileID in this._tiles) {
            const tile = this._tiles[tileID];
            if (visualizeQueryGeometry) {
                tile.clearQueryDebugViz();
            }
            if (tile.holdingForFade()) {
                // Tiles held for fading are covered by tiles that are closer to ideal
                continue;
            }
            // An array of wrap values for the tile [-1, 0, 1]. The default value is 0 but -1 or 1 wrapping
            // might be required in globe view due to globe's surface being continuous.
            let tilesToCheck;
            if (isGlobe) {
                // Compare distances to copies of the tile to see if a wrapped one should be used.
                const id = tile.tileID.canonical;
                if (id.z === 0) {
                    // Render the zoom level 0 tile twice as the query polygon might span over the antimeridian
                    const distances = [
                        Math.abs(clamp(centerX, ...tileBoundsX(id, -1)) - centerX),
                        Math.abs(clamp(centerX, ...tileBoundsX(id, 1)) - centerX)
                    ];
                    tilesToCheck = [
                        0,
                        distances.indexOf(Math.min(...distances)) * 2 - 1
                    ];
                } else {
                    const distances = [
                        Math.abs(clamp(centerX, ...tileBoundsX(id, -1)) - centerX),
                        Math.abs(clamp(centerX, ...tileBoundsX(id, 0)) - centerX),
                        Math.abs(clamp(centerX, ...tileBoundsX(id, 1)) - centerX)
                    ];
                    tilesToCheck = [distances.indexOf(Math.min(...distances)) - 1];
                }
            } else {
                tilesToCheck = [0];
            }
            for (const wrap of tilesToCheck) {
                const tileResult = queryGeometry.containsTile(tile, transform, use3DQuery, wrap);
                if (tileResult) {
                    tileResults.push(tileResult);
                }
            }
        }
        return tileResults;
    }
    getShadowCasterCoordinates() {
        return this._getRenderableCoordinates(false, true);
    }
    getVisibleCoordinates(symbolLayer) {
        return this._getRenderableCoordinates(symbolLayer);
    }
    _getRenderableCoordinates(symbolLayer, includeShadowCasters) {
        const coords = this.getRenderableIds(symbolLayer, includeShadowCasters).map(id => this._tiles[id].tileID);
        for (const coord of coords) {
            coord.projMatrix = this.transform.calculateProjMatrix(coord.toUnwrapped());
        }
        return coords;
    }
    sortCoordinatesByDistance(coords) {
        const sortedCoords = coords.slice();
        const camPos = this.transform._camera.position;
        const camFwd = this.transform._camera.forward();
        const precomputedDistances = {};
        // Precompute distances of tile center points to the camera plane
        for (const id of sortedCoords) {
            const invTiles = 1 / (1 << id.canonical.z);
            const centerX = (id.canonical.x + 0.5) * invTiles + id.wrap;
            const centerY = (id.canonical.y + 0.5) * invTiles;
            precomputedDistances[id.key] = (centerX - camPos[0]) * camFwd[0] + (centerY - camPos[1]) * camFwd[1] - camPos[2] * camFwd[2];
        }
        sortedCoords.sort((a, b) => {
            return precomputedDistances[a.key] - precomputedDistances[b.key];
        });
        return sortedCoords;
    }
    hasTransition() {
        if (this._source.hasTransition()) {
            return true;
        }
        if (isRasterType(this._source.type)) {
            for (const id in this._tiles) {
                const tile = this._tiles[id];
                if (tile.fadeEndTime !== undefined && tile.fadeEndTime >= exported$1.now()) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * Set the value of a particular state for a feature
     * @private
     */
    setFeatureState(sourceLayer, featureId, state) {
        sourceLayer = sourceLayer || '_geojsonTileLayer';
        this._state.updateState(sourceLayer, featureId, state);
    }
    /**
     * Resets the value of a particular state key for a feature
     * @private
     */
    removeFeatureState(sourceLayer, featureId, key) {
        sourceLayer = sourceLayer || '_geojsonTileLayer';
        this._state.removeFeatureState(sourceLayer, featureId, key);
    }
    /**
     * Get the entire state object for a feature
     * @private
     */
    getFeatureState(sourceLayer, featureId) {
        sourceLayer = sourceLayer || '_geojsonTileLayer';
        return this._state.getState(sourceLayer, featureId);
    }
    /**
     * Sets the set of keys that the tile depends on. This allows tiles to
     * be reloaded when their dependencies change.
     * @private
     */
    setDependencies(tileKey, namespace, dependencies) {
        const tile = this._tiles[tileKey];
        if (tile) {
            tile.setDependencies(namespace, dependencies);
        }
    }
    /**
     * Reloads all tiles that depend on the given keys.
     * @private
     */
    reloadTilesForDependencies(namespaces, keys) {
        for (const id in this._tiles) {
            const tile = this._tiles[id];
            if (tile.hasDependency(namespaces, keys)) {
                this._reloadTile(+id, 'reloading');
            }
        }
        this._cache.filter(tile => !tile.hasDependency(namespaces, keys));
    }
    /**
     * Preloads all tiles that will be requested for one or a series of transformations
     *
     * @private
     * @returns {Object} Returns `this` | Promise.
     */
    _preloadTiles(transform, callback) {
        if (!this._sourceLoaded) {
            const waitUntilSourceLoaded = () => {
                if (!this._sourceLoaded)
                    return;
                this._source.off('data', waitUntilSourceLoaded);
                this._preloadTiles(transform, callback);
            };
            this._source.on('data', waitUntilSourceLoaded);
            return;
        }
        const coveringTilesIDs = new Map();
        const transforms = Array.isArray(transform) ? transform : [transform];
        const terrain = this.map.painter.terrain;
        const tileSize = this.usedForTerrain && terrain ? terrain.getScaledDemTileSize() : this._source.tileSize;
        for (const tr of transforms) {
            const tileIDs = tr.coveringTiles({
                tileSize,
                minzoom: this._source.minzoom,
                maxzoom: this._source.maxzoom,
                roundZoom: this._source.roundZoom && !this.usedForTerrain,
                reparseOverscaled: this._source.reparseOverscaled,
                isTerrainDEM: this.usedForTerrain
            });
            for (const tileID of tileIDs) {
                coveringTilesIDs.set(tileID.key, tileID);
            }
            if (this.usedForTerrain) {
                tr.updateElevation(false);
            }
        }
        const tileIDs = Array.from(coveringTilesIDs.values());
        asyncAll(tileIDs, (tileID, done) => {
            const tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), this.transform.tileZoom, this.map.painter, this._isRaster);
            this._loadTile(tile, err => {
                if (this._source.type === 'raster-dem' && tile.dem)
                    this._backfillDEM(tile);
                done(err, tile);
            });
        }, callback);
    }
}
SourceCache.maxOverzooming = 10;
SourceCache.maxUnderzooming = 3;
function compareTileId(a, b) {
    // Different copies of the world are sorted based on their distance to the center.
    // Wrap values are converted to unsigned distances by reserving odd number for copies
    // with negative wrap and even numbers for copies with positive wrap.
    const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);
    const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);
    return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;
}
function isRasterType(type) {
    return type === 'raster' || type === 'image' || type === 'video' || type === 'custom';
}
function tileBoundsX(id, wrap) {
    const tiles = 1 << id.z;
    return [
        id.x / tiles + wrap,
        (id.x + 1) / tiles + wrap
    ];
}

//      
const modelAttributes = createLayout([{
        name: 'a_pos_3f',
        components: 3,
        type: 'Float32'
    }]);
const color3fAttributes = createLayout([{
        name: 'a_color_3f',
        components: 3,
        type: 'Float32'
    }]);
const color4fAttributes = createLayout([{
        name: 'a_color_4f',
        components: 4,
        type: 'Float32'
    }]);
const texcoordAttributes = createLayout([{
        name: 'a_uv_2f',
        components: 2,
        type: 'Float32'
    }]);
const normalAttributes = createLayout([{
        name: 'a_normal_3f',
        components: 3,
        type: 'Float32'
    }]);
const instanceAttributes = createLayout([
    {
        name: 'a_normal_matrix0',
        components: 4,
        type: 'Float32'
    },
    {
        name: 'a_normal_matrix1',
        components: 4,
        type: 'Float32'
    },
    {
        name: 'a_normal_matrix2',
        components: 4,
        type: 'Float32'
    },
    {
        name: 'a_normal_matrix3',
        components: 4,
        type: 'Float32'
    }
]);
const featureAttributes = createLayout([
    // pbr encoding: | color.rgba (4 bytes) | emissivity (a byte) | roughness (a nibble) | metallic (a nibble)
    {
        name: 'a_pbr',
        components: 4,
        type: 'Uint16'
    },
    {
        name: 'a_heightBasedEmissiveStrength',
        components: 3,
        type: 'Float32'
    }
]);

//      
/**
 * @private
 * An `EdgeInset` object represents screen space padding applied to the edges of the viewport.
 * This shifts the apparent center or the vanishing point of the map. This is useful for adding floating UI elements
 * on top of the map and having the vanishing point shift as UI elements resize.
 *
 * @param {number} [top=0]
 * @param {number} [bottom=0]
 * @param {number} [left=0]
 * @param {number} [right=0]
 */
class EdgeInsets {
    constructor(top = 0, bottom = 0, left = 0, right = 0) {
        if (isNaN(top) || top < 0 || isNaN(bottom) || bottom < 0 || isNaN(left) || left < 0 || isNaN(right) || right < 0) {
            throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers');
        }
        this.top = top;
        this.bottom = bottom;
        this.left = left;
        this.right = right;
    }
    /**
     * Interpolates the inset in-place.
     * This maintains the current inset value for any inset not present in `target`.
     *
     * @private
     * @param {PaddingOptions | EdgeInsets} start The initial padding options.
     * @param {PaddingOptions} target The target padding options.
     * @param {number} t The interpolation variable.
     * @returns {EdgeInsets} The interpolated edge insets.
     * @memberof EdgeInsets
     */
    interpolate(start, target, t) {
        if (target.top != null && start.top != null)
            this.top = number(start.top, target.top, t);
        if (target.bottom != null && start.bottom != null)
            this.bottom = number(start.bottom, target.bottom, t);
        if (target.left != null && start.left != null)
            this.left = number(start.left, target.left, t);
        if (target.right != null && start.right != null)
            this.right = number(start.right, target.right, t);
        return this;
    }
    /**
     * Utility method that computes the new apprent center or vanishing point after applying insets.
     * This is in pixels and with the top left being (0.0) and +y being downwards.
     *
     * @private
     * @param {number} width The width of the map in pixels.
     * @param {number} height The height of the map in pixels.
     * @returns {Point} The apparent center or vanishing point of the map.
     * @memberof EdgeInsets
     */
    getCenter(width, height) {
        // Clamp insets so they never overflow width/height and always calculate a valid center
        const x = clamp((this.left + width - this.right) / 2, 0, width);
        const y = clamp((this.top + height - this.bottom) / 2, 0, height);
        return new Point$2(x, y);
    }
    equals(other) {
        return this.top === other.top && this.bottom === other.bottom && this.left === other.left && this.right === other.right;
    }
    clone() {
        return new EdgeInsets(this.top, this.bottom, this.left, this.right);
    }
    /**
     * Returns the current state as json, useful when you want to have a
     * read-only representation of the inset.
     *
     * @private
     * @returns {PaddingOptions} The current padding options.
     * @memberof EdgeInsets
     */
    toJSON() {
        return {
            top: this.top,
            bottom: this.bottom,
            left: this.left,
            right: this.right
        };
    }
}

//      
function updateTransformOrientation(matrix, orientation) {
    // Take temporary copy of position to prevent it from being overwritten
    const position = getColumn(matrix, 3);
    // Convert quaternion to rotation matrix
    mat4_1.fromQuat(matrix, orientation);
    setColumn(matrix, 3, position);
}
function updateTransformPosition(matrix, position) {
    setColumn(matrix, 3, [
        position[0],
        position[1],
        position[2],
        1
    ]);
}
function orientationFromPitchBearing(pitch, bearing) {
    // Both angles are considered to define CW rotation around their respective axes.
    // Values have to be negated to achieve the proper quaternion in left handed coordinate space
    const orientation = quat_1.identity([]);
    quat_1.rotateZ(orientation, orientation, -bearing);
    quat_1.rotateX(orientation, orientation, -pitch);
    return orientation;
}
function orientationFromFrame(forward, up) {
    // Find right-vector of the resulting coordinate frame. Up-vector has to be
    // sanitized first in order to remove the roll component from the orientation
    const xyForward = [
        forward[0],
        forward[1],
        0
    ];
    const xyUp = [
        up[0],
        up[1],
        0
    ];
    const epsilon = 1e-15;
    if (vec3_1.length(xyForward) >= epsilon) {
        // Roll rotation can be seen as the right vector not being on the xy-plane, ie. right[2] != 0.0.
        // It can be negated by projecting the up vector on top of the forward vector.
        const xyDir = vec3_1.normalize([], xyForward);
        vec3_1.scale(xyUp, xyDir, vec3_1.dot(xyUp, xyDir));
        up[0] = xyUp[0];
        up[1] = xyUp[1];
    }
    const right = vec3_1.cross([], up, forward);
    if (vec3_1.len(right) < epsilon) {
        return null;
    }
    const bearing = Math.atan2(-right[1], right[0]);
    const pitch = Math.atan2(Math.sqrt(forward[0] * forward[0] + forward[1] * forward[1]), -forward[2]);
    return orientationFromPitchBearing(pitch, bearing);
}
/**
 * Options for accessing physical properties of the underlying camera entity.
 * Direct access to these properties allows more flexible and precise controlling of the camera.
 * These options are also fully compatible and interchangeable with CameraOptions. All fields are optional.
 * See {@link Map#setFreeCameraOptions} and {@link Map#getFreeCameraOptions}.
 *
 * @param {MercatorCoordinate} position Position of the camera in slightly modified web mercator coordinates.
        - The size of 1 unit is the width of the projected world instead of the "mercator meter".
          Coordinate [0, 0, 0] is the north-west corner and [1, 1, 0] is the south-east corner.
        - Z coordinate is conformal and must respect minimum and maximum zoom values.
        - Zoom is automatically computed from the altitude (z).
 * @param {quat} orientation Orientation of the camera represented as a unit quaternion [x, y, z, w] in a left-handed coordinate space.
        Direction of the rotation is clockwise around the respective axis.
        The default pose of the camera is such that the forward vector is looking up the -Z axis.
        The up vector is aligned with north orientation of the map:
          forward: [0, 0, -1]
          up:      [0, -1, 0]
          right    [1, 0, 0]
        Orientation can be set freely but certain constraints still apply:
         - Orientation must be representable with only pitch and bearing.
         - Pitch has an upper limit
 * @example
 * const camera = map.getFreeCameraOptions();
 *
 * const position = [138.72649, 35.33974];
 * const altitude = 3000;
 *
 * camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
 * camera.lookAtPoint([138.73036, 35.36197]);
 *
 * map.setFreeCameraOptions(camera);
 * @see [Example: Animate the camera around a point in 3D terrain](https://docs.mapbox.com/mapbox-gl-js/example/free-camera-point/)
 * @see [Example: Animate the camera along a path](https://docs.mapbox.com/mapbox-gl-js/example/free-camera-path/)
*/
class FreeCameraOptions {
    constructor(position, orientation) {
        this.position = position;
        this.orientation = orientation;
    }
    get position() {
        return this._position;
    }
    set position(position) {
        if (!position) {
            this._position = null;
        } else {
            const mercatorCoordinate = position instanceof MercatorCoordinate ? position : new MercatorCoordinate(position[0], position[1], position[2]);
            if (this._renderWorldCopies) {
                mercatorCoordinate.x = wrap$1(mercatorCoordinate.x, 0, 1);
            }
            this._position = mercatorCoordinate;
        }
    }
    /**
     * Helper function for setting orientation of the camera by defining a focus point
     * on the map.
     *
     * @param {LngLatLike} location Location of the focus point on the map.
     * @param {vec3?} up Up vector of the camera is necessary in certain scenarios where bearing can't be deduced
     *      from the viewing direction.
     * @example
     * const camera = map.getFreeCameraOptions();
     *
     * const position = [138.72649, 35.33974];
     * const altitude = 3000;
     *
     * camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
     * camera.lookAtPoint([138.73036, 35.36197]);
     * // Apply camera changes
     * map.setFreeCameraOptions(camera);
     */
    lookAtPoint(location, up) {
        this.orientation = null;
        if (!this.position) {
            return;
        }
        const pos = this.position;
        const altitude = this._elevation ? this._elevation.getAtPointOrZero(MercatorCoordinate.fromLngLat(location)) : 0;
        const target = MercatorCoordinate.fromLngLat(location, altitude);
        const forward = [
            target.x - pos.x,
            target.y - pos.y,
            target.z - pos.z
        ];
        if (!up)
            up = [
                0,
                0,
                1
            ];
        // flip z-component if the up vector is pointing downwards
        up[2] = Math.abs(up[2]);
        this.orientation = orientationFromFrame(forward, up);
    }
    /**
     * Helper function for setting the orientation of the camera as a pitch and a bearing.
     *
     * @param {number} pitch Pitch angle in degrees.
     * @param {number} bearing Bearing angle in degrees.
     * @example
     * const camera = map.getFreeCameraOptions();
     *
     * // Update camera pitch and bearing
     * camera.setPitchBearing(80, 90);
     * // Apply changes
     * map.setFreeCameraOptions(camera);
     */
    setPitchBearing(pitch, bearing) {
        this.orientation = orientationFromPitchBearing(degToRad(pitch), degToRad(-bearing));
    }
}
/**
 * While using the free camera API the outcome value of isZooming, isMoving and isRotating
 * is not a result of the free camera API.
 * If the user sets the map.interactive to true, there will be conflicting behaviors while
 * interacting with map via zooming or moving using mouse or/and keyboard which will result
 * in isZooming, isMoving and isRotating to return true while using free camera API. In order
 * to prevent the confilicting behavior please set map.interactive to false which will result
 * in muting the following events: zoom, zoomend, zoomstart, rotate, rotateend, rotatestart,
 * move, moveend, movestart, pitch, pitchend, pitchstart.
 */
class FreeCamera {
    constructor(position, orientation) {
        this._transform = mat4_1.identity([]);
        this.orientation = orientation;
        this.position = position;
    }
    get mercatorPosition() {
        const pos = this.position;
        return new MercatorCoordinate(pos[0], pos[1], pos[2]);
    }
    get position() {
        const col = getColumn(this._transform, 3);
        return [
            col[0],
            col[1],
            col[2]
        ];
    }
    set position(value) {
        if (value) {
            updateTransformPosition(this._transform, value);
        }
    }
    get orientation() {
        return this._orientation;
    }
    set orientation(value) {
        this._orientation = value || quat_1.identity([]);
        if (value) {
            updateTransformOrientation(this._transform, this._orientation);
        }
    }
    getPitchBearing() {
        const f = this.forward();
        const r = this.right();
        return {
            bearing: Math.atan2(-r[1], r[0]),
            pitch: Math.atan2(Math.sqrt(f[0] * f[0] + f[1] * f[1]), -f[2])
        };
    }
    setPitchBearing(pitch, bearing) {
        this._orientation = orientationFromPitchBearing(pitch, bearing);
        updateTransformOrientation(this._transform, this._orientation);
    }
    forward() {
        const col = getColumn(this._transform, 2);
        // Forward direction is towards the negative Z-axis
        return [
            -col[0],
            -col[1],
            -col[2]
        ];
    }
    up() {
        const col = getColumn(this._transform, 1);
        // Up direction has to be flipped to point towards north
        return [
            -col[0],
            -col[1],
            -col[2]
        ];
    }
    right() {
        const col = getColumn(this._transform, 0);
        return [
            col[0],
            col[1],
            col[2]
        ];
    }
    getCameraToWorld(worldSize, pixelsPerMeter) {
        const cameraToWorld = new Float64Array(16);
        mat4_1.invert(cameraToWorld, this.getWorldToCamera(worldSize, pixelsPerMeter));
        return cameraToWorld;
    }
    getCameraToWorldMercator() {
        return this._transform;
    }
    getWorldToCameraPosition(worldSize, pixelsPerMeter, uniformScale) {
        const invPosition = this.position;
        vec3_1.scale(invPosition, invPosition, -worldSize);
        const matrix = new Float64Array(16);
        mat4_1.fromScaling(matrix, [
            uniformScale,
            uniformScale,
            uniformScale
        ]);
        mat4_1.translate(matrix, matrix, invPosition);
        // Adjust scale on z (3rd column 3rd row)
        matrix[10] *= pixelsPerMeter;
        return matrix;
    }
    getWorldToCamera(worldSize, pixelsPerMeter) {
        // transformation chain from world space to camera space:
        // 1. Height value (z) of renderables is in meters. Scale z coordinate by pixelsPerMeter
        // 2. Transform from pixel coordinates to camera space with cameraMatrix^-1
        // 3. flip Y if required
        // worldToCamera: flip * cam^-1 * zScale
        // cameraToWorld: (flip * cam^-1 * zScale)^-1 => (zScale^-1 * cam * flip^-1)
        const matrix = new Float64Array(16);
        // Compute inverse of camera matrix and post-multiply negated translation
        const invOrientation = new Float64Array(4);
        const invPosition = this.position;
        quat_1.conjugate(invOrientation, this._orientation);
        vec3_1.scale(invPosition, invPosition, -worldSize);
        mat4_1.fromQuat(matrix, invOrientation);
        mat4_1.translate(matrix, matrix, invPosition);
        // Pre-multiply y (2nd row)
        matrix[1] *= -1;
        matrix[5] *= -1;
        matrix[9] *= -1;
        matrix[13] *= -1;
        // Post-multiply z (3rd column)
        matrix[8] *= pixelsPerMeter;
        matrix[9] *= pixelsPerMeter;
        matrix[10] *= pixelsPerMeter;
        matrix[11] *= pixelsPerMeter;
        return matrix;
    }
    getCameraToClipPerspective(fovy, aspectRatio, nearZ, farZ) {
        const matrix = new Float64Array(16);
        mat4_1.perspective(matrix, fovy, aspectRatio, nearZ, farZ);
        return matrix;
    }
    getCameraToClipOrthographic(left, right, bottom, top, nearZ, farZ) {
        const matrix = new Float64Array(16);
        mat4_1.ortho(matrix, left, right, bottom, top, nearZ, farZ);
        return matrix;
    }
    // The additional parameter needs to be removed. This was introduced because originally
    // the value returned by this function was incorrect. Fixing it would break the fog visuals and needs to be
    // communicated carefully first. Also see transform.cameraWorldSizeForFog.
    getDistanceToElevation(elevationMeters, convert = false) {
        const z0 = elevationMeters === 0 ? 0 : mercatorZfromAltitude(elevationMeters, convert ? latFromMercatorY(this.position[1]) : this.position[1]);
        const f = this.forward();
        return (z0 - this.position[2]) / f[2];
    }
    clone() {
        return new FreeCamera([...this.position], [...this.orientation]);
    }
}

//      
function getProjectionAdjustments(transform, withoutRotation) {
    const interpT = getProjectionInterpolationT(transform.projection, transform.zoom, transform.width, transform.height);
    const matrix = getShearAdjustment(transform.projection, transform.zoom, transform.center, interpT, withoutRotation);
    const scaleAdjustment = getScaleAdjustment(transform);
    mat4_1.scale(matrix, matrix, [
        scaleAdjustment,
        scaleAdjustment,
        1
    ]);
    return matrix;
}
function getScaleAdjustment(transform) {
    const projection = transform.projection;
    const interpT = getProjectionInterpolationT(transform.projection, transform.zoom, transform.width, transform.height);
    const zoomAdjustment = getZoomAdjustment(projection, transform.center);
    const zoomAdjustmentOrigin = getZoomAdjustment(projection, LngLat$1.convert(projection.center));
    const scaleAdjustment = Math.pow(2, zoomAdjustment * interpT + (1 - interpT) * zoomAdjustmentOrigin);
    return scaleAdjustment;
}
function getProjectionAdjustmentInverted(transform) {
    const m = getProjectionAdjustments(transform, true);
    return mat2_1.invert([], [
        m[0],
        m[1],
        m[4],
        m[5]
    ]);
}
function getProjectionInterpolationT(projection, zoom, width, height, maxSize = Infinity) {
    const range = projection.range;
    if (!range)
        return 0;
    const size = Math.min(maxSize, Math.max(width, height));
    // The interpolation ranges are manually defined based on what makes
    // sense in a 1024px wide map. Adjust the ranges to the current size
    // of the map. The smaller the map, the earlier you can start unskewing.
    const rangeAdjustment = Math.log(size / 1024) / Math.LN2;
    const zoomA = range[0] + rangeAdjustment;
    const zoomB = range[1] + rangeAdjustment;
    const t = smoothstep(zoomA, zoomB, zoom);
    return t;
}
// approx. kilometers per longitude degree at equator
const offset = 1 / 40000;
/*
 * Calculates the scale difference between Mercator and the given projection at a certain location.
 */
function getZoomAdjustment(projection, loc) {
    // make sure we operate within mercator space for adjustments (they can go over for other projections)
    const lat = clamp(loc.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
    const loc1 = new LngLat$1(loc.lng - 180 * offset, lat);
    const loc2 = new LngLat$1(loc.lng + 180 * offset, lat);
    const p1 = projection.project(loc1.lng, lat);
    const p2 = projection.project(loc2.lng, lat);
    const m1 = MercatorCoordinate.fromLngLat(loc1);
    const m2 = MercatorCoordinate.fromLngLat(loc2);
    const pdx = p2.x - p1.x;
    const pdy = p2.y - p1.y;
    const mdx = m2.x - m1.x;
    const mdy = m2.y - m1.y;
    const scale = Math.sqrt((mdx * mdx + mdy * mdy) / (pdx * pdx + pdy * pdy));
    return Math.log(scale) / Math.LN2;
}
function getShearAdjustment(projection, zoom, loc, interpT, withoutRotation) {
    // create two locations a tiny amount (~1km) east and west of the given location
    const locw = new LngLat$1(loc.lng - 180 * offset, loc.lat);
    const loce = new LngLat$1(loc.lng + 180 * offset, loc.lat);
    const pw = projection.project(locw.lng, locw.lat);
    const pe = projection.project(loce.lng, loce.lat);
    const pdx = pe.x - pw.x;
    const pdy = pe.y - pw.y;
    // Calculate how much the map would need to be rotated to make east-west in
    // projected coordinates be left-right
    const angleAdjust = -Math.atan2(pdy, pdx);
    // Pick a location identical to the original one except for poles to make sure we're within mercator bounds
    const mc2 = MercatorCoordinate.fromLngLat(loc);
    mc2.y = clamp(mc2.y, -1 + offset, 1 - offset);
    const loc2 = mc2.toLngLat();
    const p2 = projection.project(loc2.lng, loc2.lat);
    // Find the projected coordinates of two locations, one slightly south and one slightly east.
    // Then calculate the transform that would make the projected coordinates of the two locations be:
    // - equal distances from the original location
    // - perpendicular to one another
    //
    // Only the position of the coordinate to the north is adjusted.
    // The coordinate to the east stays where it is.
    const mc3 = MercatorCoordinate.fromLngLat(loc2);
    mc3.x += offset;
    const loc3 = mc3.toLngLat();
    const p3 = projection.project(loc3.lng, loc3.lat);
    const pdx3 = p3.x - p2.x;
    const pdy3 = p3.y - p2.y;
    const delta3 = rotate(pdx3, pdy3, angleAdjust);
    const mc4 = MercatorCoordinate.fromLngLat(loc2);
    mc4.y += offset;
    const loc4 = mc4.toLngLat();
    const p4 = projection.project(loc4.lng, loc4.lat);
    const pdx4 = p4.x - p2.x;
    const pdy4 = p4.y - p2.y;
    const delta4 = rotate(pdx4, pdy4, angleAdjust);
    const scale = Math.abs(delta3.x) / Math.abs(delta4.y);
    const unrotate = mat4_1.identity([]);
    mat4_1.rotateZ(unrotate, unrotate, -angleAdjust * (1 - (withoutRotation ? 0 : interpT)));
    // unskew
    const shear = mat4_1.identity([]);
    mat4_1.scale(shear, shear, [
        1,
        1 - (1 - scale) * interpT,
        1
    ]);
    shear[4] = -delta4.x / delta4.y * interpT;
    // unrotate
    mat4_1.rotateZ(shear, shear, angleAdjust);
    mat4_1.multiply(shear, unrotate, shear);
    return shear;
}
function rotate(x, y, angle) {
    const cos = Math.cos(angle);
    const sin = Math.sin(angle);
    return {
        x: x * cos - y * sin,
        y: x * sin + y * cos
    };
}

//      
/**
 * Converts a pixel value at a the given zoom level to tile units.
 *
 * The shaders mostly calculate everything in tile units so style
 * properties need to be converted from pixels to tile units using this.
 *
 * For example, a translation by 30 pixels at zoom 6.5 will be a
 * translation by pixelsToTileUnits(30, 6.5) tile units.
 *
 * @returns value in tile units
 * @private
 */
function pixelsToTileUnits (tile, pixelValue, z) {
    return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));
}
function getPixelsToTileUnitsMatrix(tile, transform) {
    const {scale} = tile.tileTransform;
    const s = scale * EXTENT / (tile.tileSize * Math.pow(2, transform.zoom - tile.tileID.overscaledZ + tile.tileID.canonical.z));
    return mat2_1.scale(new Float32Array(4), transform.inverseAdjustmentMatrix, [
        s,
        s
    ]);
}

//      
const FlipState = {
    unknown: 0,
    flipRequired: 1,
    flipNotRequired: 2
};
const maxTangent = Math.tan(85 * Math.PI / 180);
/*
 * # Overview of coordinate spaces
 *
 * ## Tile coordinate spaces
 * Each label has an anchor. Some labels have corresponding line geometries.
 * The points for both anchors and lines are stored in tile units. Each tile has it's own
 * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right.
 *
 * ## GL coordinate space
 * At the end of everything, the vertex shader needs to produce a position in GL coordinate space,
 * which is (-1, 1) at the top left and (1, -1) in the bottom right.
 *
 * ## Map pixel coordinate spaces
 * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is
 * whatever counts as 1 pixel at the current zoom.
 * This space is used for pitch-alignment=map, rotation-alignment=map
 *
 * ## Rotated map pixel coordinate spaces
 * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile.
 * This space is used for pitch-alignment=map, rotation-alignment=viewport
 *
 * ## Viewport pixel coordinate space
 * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner
 * of the canvas. This space is used for pitch-alignment=viewport
 *
 *
 * # Vertex projection
 * It goes roughly like this:
 * 1. project the anchor and line from tile units into the correct label coordinate space
 *      - map pixel space           pitch-alignment=map         rotation-alignment=map
 *      - rotated map pixel space   pitch-alignment=map         rotation-alignment=viewport
 *      - viewport pixel space      pitch-alignment=viewport    rotation-alignment=*
 * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor.
 * 3. add the glyph's corner offset to the point from step 3
 * 4. convert from the label coordinate space to gl coordinates
 *
 * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work).
 *      This is what `u_label_plane_matrix` is used for.
 * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry.
 *      This is what `updateLineLabels(...)` does.
 *      Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix.
 *
 * Steps 3 and 4 are done in the shaders for all labels.
 */
/*
 * Returns a matrix for converting from tile units to the correct label coordinate space.
 * This variation of the function returns a label space matrix specialized for rendering.
 * It transforms coordinates as-is to whatever the target space is (either 2D or 3D).
 * See also `getLabelPlaneMatrixForPlacement`
 */
function getLabelPlaneMatrixForRendering(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits) {
    const m = mat4_1.create();
    if (pitchWithMap) {
        if (projection.name === 'globe') {
            const lm = calculateGlobeLabelMatrix(transform, tileID);
            mat4_1.multiply(m, m, lm);
        } else {
            const s = mat2_1.invert([], pixelsToTileUnits);
            m[0] = s[0];
            m[1] = s[1];
            m[4] = s[2];
            m[5] = s[3];
            if (!rotateWithMap) {
                mat4_1.rotateZ(m, m, transform.angle);
            }
        }
    } else {
        mat4_1.multiply(m, transform.labelPlaneMatrix, posMatrix);
    }
    return m;
}
/*
 * Returns a matrix for converting from tile units to the correct label coordinate space.
 * This variation of the function returns a matrix specialized for placement logic.
 * Coordinates will be clamped to x&y 2D plane which is used with viewport and map aligned placement
 * logic in most cases. Certain projections such as globe view will use 3D space for map aligned
 * label placement.
 */
function getLabelPlaneMatrixForPlacement(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits) {
    const m = getLabelPlaneMatrixForRendering(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits);
    // Symbol placement logic is performed in 2D in most scenarios.
    // For this reason project all coordinates to the xy-plane by discarding the z-component
    if (projection.name !== 'globe' || !pitchWithMap) {
        // Pre-multiply by scaling z to 0
        m[2] = m[6] = m[10] = m[14] = 0;
    }
    return m;
}
/*
 * Returns a matrix for converting from the correct label coordinate space to gl coords.
 */
function getGlCoordMatrix(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits) {
    if (pitchWithMap) {
        if (projection.name === 'globe') {
            const m = getLabelPlaneMatrixForRendering(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits);
            mat4_1.invert(m, m);
            mat4_1.multiply(m, posMatrix, m);
            return m;
        } else {
            const m = mat4_1.clone(posMatrix);
            const s = mat4_1.identity([]);
            s[0] = pixelsToTileUnits[0];
            s[1] = pixelsToTileUnits[1];
            s[4] = pixelsToTileUnits[2];
            s[5] = pixelsToTileUnits[3];
            mat4_1.multiply(m, m, s);
            if (!rotateWithMap) {
                mat4_1.rotateZ(m, m, -transform.angle);
            }
            return m;
        }
    } else {
        return transform.glCoordMatrix;
    }
}
function project(x, y, z, matrix) {
    const pos = [
        x,
        y,
        z,
        1
    ];
    if (z) {
        vec4_1.transformMat4(pos, pos, matrix);
    } else {
        xyTransformMat4(pos, pos, matrix);
    }
    const w = pos[3];
    pos[0] /= w;
    pos[1] /= w;
    pos[2] /= w;
    return pos;
}
function projectClamped([x, y, z], matrix) {
    const pos = [
        x,
        y,
        z,
        1
    ];
    vec4_1.transformMat4(pos, pos, matrix);
    // Clamp distance to a positive value so we can avoid screen coordinate
    // being flipped possibly due to perspective projection
    const w = pos[3] = Math.max(pos[3], 0.000001);
    pos[0] /= w;
    pos[1] /= w;
    pos[2] /= w;
    return pos;
}
function getPerspectiveRatio(cameraToCenterDistance, signedDistanceFromCamera) {
    return Math.min(0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera), 1.5);
}
function isVisible(anchorPos, clippingBuffer) {
    const x = anchorPos[0] / anchorPos[3];
    const y = anchorPos[1] / anchorPos[3];
    const inPaddedViewport = x >= -clippingBuffer[0] && x <= clippingBuffer[0] && y >= -clippingBuffer[1] && y <= clippingBuffer[1];
    return inPaddedViewport;
}
/*
 *  Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view.
 *  This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader.
 */
function updateLineLabels(bucket, posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright, getElevation, tileID) {
    const tr = painter.transform;
    const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
    const partiallyEvaluatedSize = evaluateSizeForZoom(sizeData, painter.transform.zoom);
    const isGlobe = tr.projection.name === 'globe';
    const clippingBuffer = [
        256 / painter.width * 2 + 1,
        256 / painter.height * 2 + 1
    ];
    const dynamicLayoutVertexArray = isText ? bucket.text.dynamicLayoutVertexArray : bucket.icon.dynamicLayoutVertexArray;
    dynamicLayoutVertexArray.clear();
    let globeExtVertexArray = null;
    if (isGlobe) {
        globeExtVertexArray = isText ? bucket.text.globeExtVertexArray : bucket.icon.globeExtVertexArray;
    }
    const lineVertexArray = bucket.lineVertexArray;
    const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray;
    const aspectRatio = painter.transform.width / painter.transform.height;
    let useVertical = false;
    let prevWritingMode;
    for (let s = 0; s < placedSymbols.length; s++) {
        const symbol = placedSymbols.get(s);
        const {numGlyphs, writingMode} = symbol;
        // Normally, the 'Horizontal|Vertical' writing mode is followed by a 'Vertical' counterpart, this
        // is not true for 'Vertical' only line labels. For this case, we'll have to overwrite the 'useVertical'
        // status before further checks.
        if (writingMode === WritingMode.vertical && !useVertical && prevWritingMode !== WritingMode.horizontal) {
            useVertical = true;
        }
        prevWritingMode = writingMode;
        // Don't do calculations for vertical glyphs unless the previous symbol was horizontal
        // and we determined that vertical glyphs were necessary.
        // Also don't do calculations for symbols that are collided and fully faded out
        if ((symbol.hidden || writingMode === WritingMode.vertical) && !useVertical) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
            continue;
        }
        // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart
        useVertical = false;
        // Project tile anchor to globe anchor
        const tileAnchorPoint = new Point$2(symbol.tileAnchorX, symbol.tileAnchorY);
        let {x, y, z} = tr.projection.projectTilePoint(tileAnchorPoint.x, tileAnchorPoint.y, tileID.canonical);
        if (getElevation) {
            const [dx, dy, dz] = getElevation(tileAnchorPoint);
            x += dx;
            y += dy;
            z += dz;
        }
        const anchorPos = [
            x,
            y,
            z,
            1
        ];
        vec4_1.transformMat4(anchorPos, anchorPos, posMatrix);
        // Don't bother calculating the correct point for invisible labels.
        if (!isVisible(anchorPos, clippingBuffer)) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
            continue;
        }
        const cameraToAnchorDistance = anchorPos[3];
        const perspectiveRatio = getPerspectiveRatio(painter.transform.getCameraToCenterDistance(tr.projection), cameraToAnchorDistance);
        const fontSize = evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);
        const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;
        const labelPlaneAnchorPoint = project(x, y, z, labelPlaneMatrix);
        // Skip labels behind the camera
        if (labelPlaneAnchorPoint[3] <= 0) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
            continue;
        }
        let projectionCache = {};
        const getElevationForPlacement = pitchWithMap ? null : getElevation;
        // When pitchWithMap, we're projecting to scaled tile coordinate space: there is no need to get elevation as it doesn't affect projection.
        const placeUnflipped = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false    /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, globeExtVertexArray, labelPlaneAnchorPoint, tileAnchorPoint, projectionCache, aspectRatio, getElevationForPlacement, tr.projection, tileID, pitchWithMap);
        useVertical = placeUnflipped.useVertical;
        if (getElevationForPlacement && placeUnflipped.needsFlipping)
            projectionCache = {};
        // Truncated points should be recalculated.
        if (placeUnflipped.notEnoughRoom || useVertical || placeUnflipped.needsFlipping && placeGlyphsAlongLine(symbol, pitchScaledFontSize, true    /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, globeExtVertexArray, labelPlaneAnchorPoint, tileAnchorPoint, projectionCache, aspectRatio, getElevationForPlacement, tr.projection, tileID, pitchWithMap).notEnoughRoom) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
        }
    }
    if (isText) {
        bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);
        if (globeExtVertexArray && bucket.text.globeExtVertexBuffer) {
            bucket.text.globeExtVertexBuffer.updateData(globeExtVertexArray);
        }
    } else {
        bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);
        if (globeExtVertexArray && bucket.icon.globeExtVertexBuffer) {
            bucket.icon.globeExtVertexBuffer.updateData(globeExtVertexArray);
        }
    }
}
function placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, returnPathInTileCoords, projection, tileID, pitchWithMap) {
    const {lineStartIndex, glyphStartIndex, segment} = symbol;
    const glyphEndIndex = glyphStartIndex + symbol.numGlyphs;
    const lineEndIndex = lineStartIndex + symbol.lineLength;
    const firstGlyphOffset = glyphOffsetArray.getoffsetX(glyphStartIndex);
    const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1);
    const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, returnPathInTileCoords, true, projection, tileID, pitchWithMap);
    if (!firstPlacedGlyph)
        return null;
    const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, returnPathInTileCoords, true, projection, tileID, pitchWithMap);
    if (!lastPlacedGlyph)
        return null;
    return {
        first: firstPlacedGlyph,
        last: lastPlacedGlyph
    };
}
// Check in the glCoordinate space, the rough estimation of angle between the text line and the Y axis.
// If the angle if less or equal to 5 degree, then keep the text glyphs unflipped even if it is required.
function isInFlipRetainRange(dx, dy) {
    return dx === 0 || Math.abs(dy / dx) > maxTangent;
}
function requiresOrientationChange(writingMode, flipState, dx, dy) {
    if (writingMode === WritingMode.horizontal && Math.abs(dy) > Math.abs(dx)) {
        // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate
        // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal
        // and vertical versions can have slightly different projections which could lead to angles where both or
        // neither showed.
        return { useVertical: true };
    }
    // Check if flipping is required for "verticalOnly" case.
    if (writingMode === WritingMode.vertical) {
        return dy > 0 ? { needsFlipping: true } : null;
    }
    // symbol's flipState stores the flip decision from the previous frame, and that
    // decision is reused when the symbol is in the retain range.
    if (flipState !== FlipState.unknown && isInFlipRetainRange(dx, dy)) {
        return flipState === FlipState.flipRequired ? { needsFlipping: true } : null;
    }
    // Check if flipping is required for "horizontal" case.
    return dx < 0 ? { needsFlipping: true } : null;
}
function placeGlyphsAlongLine(symbol, fontSize, flip, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, globeExtVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio, getElevation, projection, tileID, pitchWithMap) {
    const fontScale = fontSize / 24;
    const lineOffsetX = symbol.lineOffsetX * fontScale;
    const lineOffsetY = symbol.lineOffsetY * fontScale;
    const {lineStartIndex, glyphStartIndex, numGlyphs, segment, writingMode, flipState} = symbol;
    const lineEndIndex = lineStartIndex + symbol.lineLength;
    const addGlyph = glyph => {
        if (globeExtVertexArray) {
            const [ux, uy, uz] = glyph.up;
            const offset = dynamicLayoutVertexArray.length;
            updateGlobeVertexNormal(globeExtVertexArray, offset + 0, ux, uy, uz);
            updateGlobeVertexNormal(globeExtVertexArray, offset + 1, ux, uy, uz);
            updateGlobeVertexNormal(globeExtVertexArray, offset + 2, ux, uy, uz);
            updateGlobeVertexNormal(globeExtVertexArray, offset + 3, ux, uy, uz);
        }
        const [x, y, z] = glyph.point;
        addDynamicAttributes(dynamicLayoutVertexArray, x, y, z, glyph.angle);
    };
    if (numGlyphs > 1) {
        // Place the first and the last glyph in the label first, so we can figure out
        // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode
        const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, false, projection, tileID, pitchWithMap);
        if (!firstAndLastGlyph) {
            return { notEnoughRoom: true };
        }
        if (keepUpright && !flip) {
            let [x0, y0, z0] = firstAndLastGlyph.first.point;
            let [x1, y1, z1] = firstAndLastGlyph.last.point;
            [x0, y0] = project(x0, y0, z0, glCoordMatrix);
            [x1, y1] = project(x1, y1, z1, glCoordMatrix);
            const orientationChange = requiresOrientationChange(writingMode, flipState, (x1 - x0) * aspectRatio, y1 - y0);
            symbol.flipState = orientationChange && orientationChange.needsFlipping ? FlipState.flipRequired : FlipState.flipNotRequired;
            if (orientationChange) {
                return orientationChange;
            }
        }
        addGlyph(firstAndLastGlyph.first);
        for (let glyphIndex = glyphStartIndex + 1; glyphIndex < glyphStartIndex + numGlyphs - 1; glyphIndex++) {
            // Since first and last glyph fit on the line, the rest of the glyphs can be placed too, but check to make sure
            const glyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, false, false, projection, tileID, pitchWithMap);
            if (!glyph) {
                // undo previous glyphs of the symbol if it doesn't fit; it will be filled with hideGlyphs instead
                dynamicLayoutVertexArray.length -= 4 * (glyphIndex - glyphStartIndex);
                return { notEnoughRoom: true };
            }
            addGlyph(glyph);
        }
        addGlyph(firstAndLastGlyph.last);
    } else {
        // Only a single glyph to place
        // So, determine whether to flip based on projected angle of the line segment it's on
        if (keepUpright && !flip) {
            const a = project(tileAnchorPoint.x, tileAnchorPoint.y, 0, posMatrix);
            const tileVertexIndex = lineStartIndex + segment + 1;
            const tileSegmentEnd = new Point$2(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex));
            const projectedVertex = project(tileSegmentEnd.x, tileSegmentEnd.y, 0, posMatrix);
            // We know the anchor will be in the viewport, but the end of the line segment may be
            // behind the plane of the camera, in which case we can use a point at any arbitrary (closer)
            // point on the segment.
            const b = projectedVertex[3] > 0 ? projectedVertex : projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix, undefined, projection, tileID.canonical);
            const orientationChange = requiresOrientationChange(writingMode, flipState, (b[0] - a[0]) * aspectRatio, b[1] - a[1]);
            symbol.flipState = orientationChange && orientationChange.needsFlipping ? FlipState.flipRequired : FlipState.flipNotRequired;
            if (orientationChange) {
                return orientationChange;
            }
        }
        const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphStartIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, false, false, projection, tileID, pitchWithMap);
        if (!singleGlyph) {
            return { notEnoughRoom: true };
        }
        addGlyph(singleGlyph);
    }
    return {};
}
function elevatePointAndProject(p, tileID, posMatrix, projection, getElevation) {
    const {x, y, z} = projection.projectTilePoint(p.x, p.y, tileID);
    if (!getElevation) {
        return project(x, y, z, posMatrix);
    }
    const [dx, dy, dz] = getElevation(p);
    return project(x + dx, y + dy, z + dz, posMatrix);
}
function projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, getElevation, projection, tileID) {
    // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane
    // If it did, that would mean our label extended all the way out from within the viewport to a (very distant)
    // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the
    // plane of the camera.
    const unitVertex = previousTilePoint.sub(currentTilePoint)._unit()._add(previousTilePoint);
    const projectedUnit = elevatePointAndProject(unitVertex, tileID, projectionMatrix, projection, getElevation);
    vec3_1.sub(projectedUnit, previousProjectedPoint, projectedUnit);
    vec3_1.normalize(projectedUnit, projectedUnit);
    return vec3_1.scaleAndAdd(projectedUnit, previousProjectedPoint, projectedUnit, minimumLength);
}
function placeGlyphAlongLine(offsetX, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, anchorSegment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache, getElevation, returnPathInTileCoords, endGlyph, reprojection, tileID, pitchWithMap) {
    const combinedOffsetX = flip ? offsetX - lineOffsetX : offsetX + lineOffsetX;
    let dir = combinedOffsetX > 0 ? 1 : -1;
    let angle = 0;
    if (flip) {
        // The label needs to be flipped to keep text upright.
        // Iterate in the reverse direction.
        dir *= -1;
        angle = Math.PI;
    }
    if (dir < 0)
        angle += Math.PI;
    let currentIndex = lineStartIndex + anchorSegment + (dir > 0 ? 0 : 1) | 0;
    let current = anchorPoint;
    let prev = anchorPoint;
    let distanceToPrev = 0;
    let currentSegmentDistance = 0;
    const absOffsetX = Math.abs(combinedOffsetX);
    const pathVertices = [];
    const tilePath = [];
    let currentVertex = tileAnchorPoint;
    let prevVertex = currentVertex;
    const getTruncatedLineSegment = () => {
        return projectTruncatedLineSegment(prevVertex, currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix, getElevation, reprojection, tileID.canonical);
    };
    while (distanceToPrev + currentSegmentDistance <= absOffsetX) {
        currentIndex += dir;
        // offset does not fit on the projected line
        if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex)
            return null;
        prev = current;
        prevVertex = currentVertex;
        pathVertices.push(prev);
        if (returnPathInTileCoords)
            tilePath.push(prevVertex);
        currentVertex = new Point$2(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));
        current = projectionCache[currentIndex];
        if (!current) {
            const projection = elevatePointAndProject(currentVertex, tileID.canonical, labelPlaneMatrix, reprojection, getElevation);
            if (projection[3] > 0) {
                current = projectionCache[currentIndex] = projection;
            } else {
                // The vertex is behind the plane of the camera, so we can't project it
                // Instead, we'll create a vertex along the line that's far enough to include the glyph
                // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment
                current = getTruncatedLineSegment();
            }
        }
        distanceToPrev += currentSegmentDistance;
        currentSegmentDistance = vec3_1.distance(prev, current);
    }
    if (endGlyph && getElevation) {
        // For terrain, always truncate end points in order to handle terrain curvature.
        // If previously truncated, on signedDistanceFromCamera < 0, don't do it.
        // Cache as end point. The cache is cleared if there is need for flipping in updateLineLabels.
        if (projectionCache[currentIndex]) {
            current = getTruncatedLineSegment();
            currentSegmentDistance = vec3_1.distance(prev, current);
        }
        projectionCache[currentIndex] = current;
    }
    // The point is on the current segment. Interpolate to find it. Compute points on both label plane and tile space
    const segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance;
    const tilePoint = currentVertex.sub(prevVertex)._mult(segmentInterpolationT)._add(prevVertex);
    const prevToCurrent = vec3_1.sub([], current, prev);
    const labelPlanePoint = vec3_1.scaleAndAdd([], prev, prevToCurrent, segmentInterpolationT);
    let axisZ = [
        0,
        0,
        1
    ];
    let diffX = prevToCurrent[0];
    let diffY = prevToCurrent[1];
    if (pitchWithMap) {
        axisZ = reprojection.upVector(tileID.canonical, tilePoint.x, tilePoint.y);
        if (axisZ[0] !== 0 || axisZ[1] !== 0 || axisZ[2] !== 1) {
            // Compute coordinate frame that is aligned to the tangent of the surface
            const axisX = [
                axisZ[2],
                0,
                -axisZ[0]
            ];
            const axisY = vec3_1.cross([], axisZ, axisX);
            vec3_1.normalize(axisX, axisX);
            vec3_1.normalize(axisY, axisY);
            diffX = vec3_1.dot(prevToCurrent, axisX);
            diffY = vec3_1.dot(prevToCurrent, axisY);
        }
    }
    // offset the point from the line to text-offset and icon-offset
    if (lineOffsetY) {
        // Find a coordinate frame for the vertical offset
        const offsetDir = vec3_1.cross([], axisZ, prevToCurrent);
        vec3_1.normalize(offsetDir, offsetDir);
        vec3_1.scaleAndAdd(labelPlanePoint, labelPlanePoint, offsetDir, lineOffsetY * dir);
    }
    const segmentAngle = angle + Math.atan2(diffY, diffX);
    pathVertices.push(labelPlanePoint);
    if (returnPathInTileCoords) {
        tilePath.push(tilePoint);
    }
    return {
        point: labelPlanePoint,
        angle: segmentAngle,
        path: pathVertices,
        tilePath,
        up: axisZ
    };
}
// Hide them by moving them offscreen. We still need to add them to the buffer
// because the dynamic buffer is paired with a static buffer that doesn't get updated.
function hideGlyphs(num, dynamicLayoutVertexArray) {
    const offset = dynamicLayoutVertexArray.length;
    const end = offset + 4 * num;
    dynamicLayoutVertexArray.resize(end);
    // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to
    // Float32Array.fill for all vertices, instead of calling addDynamicAttributes for each vertex.
    dynamicLayoutVertexArray.float32.fill(-Infinity, offset * 4, end * 4);
}
// For line label layout, we're not using z output and our w input is always 1
// This custom matrix transformation ignores those components to make projection faster
function xyTransformMat4(out, a, m) {
    const x = a[0], y = a[1];
    out[0] = m[0] * x + m[4] * y + m[12];
    out[1] = m[1] * x + m[5] * y + m[13];
    out[3] = m[3] * x + m[7] * y + m[15];
    return out;
}

//      
const NUM_WORLD_COPIES = 3;
const DEFAULT_MIN_ZOOM = 0;
const DEFAULT_MAX_ZOOM = 25.5;
const MIN_LOD_PITCH = 60;
const OrthographicPitchTranstionValue = 15;
const lerp = (x, y, t) => {
    return (1 - t) * x + t * y;
};
const easeIn = x => {
    return x * x * x * x * x;
};
const lerpMatrix = (out, a, b, value) => {
    for (let i = 0; i < 16; i++) {
        out[i] = lerp(a[i], b[i], value);
    }
    return out;
};
/**
 * A single transform, generally used for a single tile to be
 * scaled, rotated, and zoomed.
 * @private
 */
class Transform {
    // 2^zoom (worldSize = tileSize * scale)
    // Map viewport size (not including the pixel ratio)
    // Bearing, radians, in [-pi, pi]
    // 2D rotation matrix in the horizontal plane, as a function of bearing
    // Zoom, modulo 1
    // The scale factor component of the conversion from pixels ([0, w] x [h, 0]) to GL
    // NDC ([1, -1] x [1, -1]) (note flipped y)
    // Distance from camera to the center, in screen pixel units, independent of zoom
    // Projection from mercator coordinates ([0, 0] nw, [1, 1] se) to GL clip coordinates
    // Translate points in mercator coordinates to be centered about the camera, with units chosen
    // for screen-height-independent scaling of fog. Not affected by orientation of camera.
    // Projection from world coordinates (mercator scaled by worldSize) to clip coordinates
    // Same as projMatrix, pixel-aligned to avoid fractional pixels for raster tiles
    // From world coordinates to screen pixel coordinates (projMatrix premultiplied by labelPlaneMatrix)
    // Transform from screen coordinates to GL NDC, [0, w] x [h, 0] --> [-1, 1] x [-1, 1]
    // Roughly speaking, applies pixelsToGLUnits scaling with a translation
    // Inverse of glCoordMatrix, from NDC to screen coordinates, [-1, 1] x [-1, 1] --> [0, w] x [h, 0]
    // globe coordinate transformation matrix
    constructor(minZoom, maxZoom, minPitch, maxPitch, renderWorldCopies, projection, bounds) {
        this.tileSize = 512;
        // constant
        this._renderWorldCopies = renderWorldCopies === undefined ? true : renderWorldCopies;
        this._minZoom = minZoom || DEFAULT_MIN_ZOOM;
        this._maxZoom = maxZoom || 22;
        this._minPitch = minPitch === undefined || minPitch === null ? 0 : minPitch;
        this._maxPitch = maxPitch === undefined || maxPitch === null ? 60 : maxPitch;
        this.setProjection(projection);
        this.setMaxBounds(bounds);
        this.width = 0;
        this.height = 0;
        this._center = new LngLat$1(0, 0);
        this.zoom = 0;
        this.angle = 0;
        this._fov = 0.6435011087932844;
        this._pitch = 0;
        this._nearZ = 0;
        this._farZ = 0;
        this._unmodified = true;
        this._edgeInsets = new EdgeInsets();
        this._projMatrixCache = {};
        this._alignedProjMatrixCache = {};
        this._fogTileMatrixCache = {};
        this._distanceTileDataCache = {};
        this._camera = new FreeCamera();
        this._centerAltitude = 0;
        this._averageElevation = 0;
        this.cameraElevationReference = 'ground';
        this._pixelsPerMercatorPixel = 1;
        this.globeRadius = 0;
        this.globeCenterInViewSpace = [
            0,
            0,
            0
        ];
        // Move the horizon closer to the center. 0 would not shift the horizon. 1 would put the horizon at the center.
        this._horizonShift = 0.1;
        this._orthographicProjectionAtLowPitch = false;
    }
    clone() {
        const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies, this.getProjection());
        clone._elevation = this._elevation;
        clone._centerAltitude = this._centerAltitude;
        clone._centerAltitudeValidForExaggeration = this._centerAltitudeValidForExaggeration;
        clone.tileSize = this.tileSize;
        clone.mercatorFromTransition = this.mercatorFromTransition;
        clone.width = this.width;
        clone.height = this.height;
        clone.cameraElevationReference = this.cameraElevationReference;
        clone._center = this._center;
        clone._setZoom(this.zoom);
        clone._seaLevelZoom = this._seaLevelZoom;
        clone.angle = this.angle;
        clone._fov = this._fov;
        clone._pitch = this._pitch;
        clone._nearZ = this._nearZ;
        clone._farZ = this._farZ;
        clone._averageElevation = this._averageElevation;
        clone._unmodified = this._unmodified;
        clone._edgeInsets = this._edgeInsets.clone();
        clone._camera = this._camera.clone();
        clone._calcMatrices();
        clone.freezeTileCoverage = this.freezeTileCoverage;
        clone.frustumCorners = this.frustumCorners;
        return clone;
    }
    get isOrthographic() {
        return this.projection.name !== 'globe' && this._orthographicProjectionAtLowPitch && this.pitch < OrthographicPitchTranstionValue;
    }
    get elevation() {
        return this._elevation;
    }
    set elevation(elevation) {
        if (this._elevation === elevation)
            return;
        this._elevation = elevation;
        this._updateCameraOnTerrain();
        this._calcMatrices();
    }
    get depthOcclusionForSymbolsAndCircles() {
        return this.projection.name !== 'globe' && !this.isOrthographic;
    }
    updateElevation(constrainCameraOverTerrain, adaptCameraAltitude = false) {
        const centerAltitudeChanged = this._elevation && this._elevation.exaggeration() !== this._centerAltitudeValidForExaggeration;
        if (this._seaLevelZoom == null || centerAltitudeChanged) {
            this._updateCameraOnTerrain();
        }
        if (constrainCameraOverTerrain || centerAltitudeChanged) {
            this._constrainCamera(adaptCameraAltitude);
        }
        this._calcMatrices();
    }
    getProjection() {
        return pick(this.projection, [
            'name',
            'center',
            'parallels'
        ]);
    }
    // Returns whether the projection changes
    setProjection(projection) {
        this.projectionOptions = projection || { name: 'mercator' };
        const oldProjection = this.projection ? this.getProjection() : undefined;
        this.projection = getProjection(this.projectionOptions);
        const newProjection = this.getProjection();
        const projectionHasChanged = !deepEqual(oldProjection, newProjection);
        if (projectionHasChanged) {
            this._calcMatrices();
        }
        this.mercatorFromTransition = false;
        return projectionHasChanged;
    }
    // Returns whether the projection need to be reevaluated
    setOrthographicProjectionAtLowPitch(enabled) {
        if (this._orthographicProjectionAtLowPitch === enabled) {
            return false;
        }
        this._orthographicProjectionAtLowPitch = enabled;
        this._calcMatrices();
        return true;
    }
    setMercatorFromTransition() {
        const oldProjection = this.projection.name;
        this.mercatorFromTransition = true;
        this.projectionOptions = { name: 'mercator' };
        this.projection = getProjection({ name: 'mercator' });
        const projectionHasChanged = oldProjection !== this.projection.name;
        if (projectionHasChanged) {
            this._calcMatrices();
        }
        return projectionHasChanged;
    }
    get minZoom() {
        return this._minZoom;
    }
    set minZoom(zoom) {
        if (this._minZoom === zoom)
            return;
        this._minZoom = zoom;
        this.zoom = Math.max(this.zoom, zoom);
    }
    get maxZoom() {
        return this._maxZoom;
    }
    set maxZoom(zoom) {
        if (this._maxZoom === zoom)
            return;
        this._maxZoom = zoom;
        this.zoom = Math.min(this.zoom, zoom);
    }
    get minPitch() {
        return this._minPitch;
    }
    set minPitch(pitch) {
        if (this._minPitch === pitch)
            return;
        this._minPitch = pitch;
        this.pitch = Math.max(this.pitch, pitch);
    }
    get maxPitch() {
        return this._maxPitch;
    }
    set maxPitch(pitch) {
        if (this._maxPitch === pitch)
            return;
        this._maxPitch = pitch;
        this.pitch = Math.min(this.pitch, pitch);
    }
    get renderWorldCopies() {
        return this._renderWorldCopies && this.projection.supportsWorldCopies === true;
    }
    set renderWorldCopies(renderWorldCopies) {
        if (renderWorldCopies === undefined) {
            renderWorldCopies = true;
        } else if (renderWorldCopies === null) {
            renderWorldCopies = false;
        }
        this._renderWorldCopies = renderWorldCopies;
    }
    get worldSize() {
        return this.tileSize * this.scale;
    }
    // This getter returns an incorrect value.
    // It should eventually be removed and cameraWorldSize be used instead.
    // See free_camera.getDistanceToElevation for the rationale.
    get cameraWorldSizeForFog() {
        const distance = Math.max(this._camera.getDistanceToElevation(this._averageElevation), Number.EPSILON);
        return this._worldSizeFromZoom(this._zoomFromMercatorZ(distance));
    }
    get cameraWorldSize() {
        const distance = Math.max(this._camera.getDistanceToElevation(this._averageElevation, true), Number.EPSILON);
        return this._worldSizeFromZoom(this._zoomFromMercatorZ(distance));
    }
    // `pixelsPerMeter` is used to describe relation between real world and pixel distances.
    // In mercator projection it is dependant on latitude value meaning that one meter covers
    // less pixels at the equator than near polar regions. Globe projection in other hand uses
    // fixed ratio everywhere.
    get pixelsPerMeter() {
        return this.projection.pixelsPerMeter(this.center.lat, this.worldSize);
    }
    get cameraPixelsPerMeter() {
        return mercatorZfromAltitude(1, this.center.lat) * this.cameraWorldSizeForFog;
    }
    get centerOffset() {
        return this.centerPoint._sub(this.size._div(2));
    }
    get size() {
        return new Point$2(this.width, this.height);
    }
    get bearing() {
        return wrap$1(this.rotation, -180, 180);
    }
    set bearing(bearing) {
        this.rotation = bearing;
    }
    get rotation() {
        return -this.angle / Math.PI * 180;
    }
    set rotation(rotation) {
        const b = -rotation * Math.PI / 180;
        if (this.angle === b)
            return;
        this._unmodified = false;
        this.angle = b;
        this._calcMatrices();
        // 2x2 matrix for rotating points
        this.rotationMatrix = mat2_1.create();
        mat2_1.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);
    }
    get pitch() {
        return this._pitch / Math.PI * 180;
    }
    set pitch(pitch) {
        const p = clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;
        if (this._pitch === p)
            return;
        this._unmodified = false;
        this._pitch = p;
        this._calcMatrices();
    }
    get aspect() {
        return this.width / this.height;
    }
    get fov() {
        return this._fov / Math.PI * 180;
    }
    get fovX() {
        return this._fov;
    }
    get fovY() {
        const focalLength = 1 / Math.tan(this.fovX * 0.5);
        return 2 * Math.atan(1 / this.aspect / focalLength);
    }
    set fov(fov) {
        fov = Math.max(0.01, Math.min(60, fov));
        if (this._fov === fov)
            return;
        this._unmodified = false;
        this._fov = degToRad(fov);
        this._calcMatrices();
    }
    get averageElevation() {
        return this._averageElevation;
    }
    set averageElevation(averageElevation) {
        this._averageElevation = averageElevation;
        this._calcFogMatrices();
        this._distanceTileDataCache = {};
    }
    get zoom() {
        return this._zoom;
    }
    set zoom(zoom) {
        const z = Math.min(Math.max(zoom, this.minZoom), this.maxZoom);
        if (this._zoom === z)
            return;
        this._unmodified = false;
        this._setZoom(z);
        this._updateSeaLevelZoom();
        this._constrain();
        this._calcMatrices();
    }
    _setZoom(z) {
        this._zoom = z;
        this.scale = this.zoomScale(z);
        this.tileZoom = Math.floor(z);
        this.zoomFraction = z - this.tileZoom;
    }
    _updateCameraOnTerrain() {
        const elevationAtCenter = this.elevation ? this.elevation.getAtPoint(this.locationCoordinate(this.center), Number.NEGATIVE_INFINITY) : Number.NEGATIVE_INFINITY;
        const usePreviousCenter = this.elevation && elevationAtCenter === Number.NEGATIVE_INFINITY && this.elevation.visibleDemTiles.length > 0 && this.elevation.exaggeration() > 0 && this._centerAltitudeValidForExaggeration;
        if (!this._elevation || elevationAtCenter === Number.NEGATIVE_INFINITY && !(usePreviousCenter && this._centerAltitude)) {
            // Elevation data not loaded yet, reset
            this._centerAltitude = 0;
            this._seaLevelZoom = null;
            this._centerAltitudeValidForExaggeration = undefined;
            return;
        }
        const elevation = this._elevation;
        if (usePreviousCenter || this._centerAltitude && this._centerAltitudeValidForExaggeration && elevation.exaggeration() && this._centerAltitudeValidForExaggeration !== elevation.exaggeration()) {
            const previousExaggeration = this._centerAltitudeValidForExaggeration;
            // scale down the centerAltitude
            this._centerAltitude = this._centerAltitude / previousExaggeration * elevation.exaggeration();
            this._centerAltitudeValidForExaggeration = elevation.exaggeration();
        } else {
            this._centerAltitude = elevationAtCenter || 0;
            this._centerAltitudeValidForExaggeration = elevation.exaggeration();
        }
        this._updateSeaLevelZoom();
    }
    _updateSeaLevelZoom() {
        if (this._centerAltitudeValidForExaggeration === undefined) {
            return;
        }
        const height = this.cameraToCenterDistance;
        const terrainElevation = this.pixelsPerMeter * this._centerAltitude;
        const mercatorZ = (terrainElevation + height) / this.worldSize;
        // MSL (Mean Sea Level) zoom describes the distance of the camera to the sea level (altitude).
        // It is used only for manipulating the camera location. The standard zoom (this._zoom)
        // defines the camera distance to the terrain (height). Its behavior and conceptual
        // meaning in determining which tiles to stream is same with or without the terrain.
        this._seaLevelZoom = this._zoomFromMercatorZ(mercatorZ);
    }
    sampleAverageElevation() {
        if (!this._elevation)
            return 0;
        const elevation = this._elevation;
        const elevationSamplePoints = [
            [
                0.5,
                0.2
            ],
            [
                0.3,
                0.5
            ],
            [
                0.5,
                0.5
            ],
            [
                0.7,
                0.5
            ],
            [
                0.5,
                0.8
            ]
        ];
        const horizon = this.horizonLineFromTop();
        let elevationSum = 0;
        let weightSum = 0;
        for (let i = 0; i < elevationSamplePoints.length; i++) {
            const pt = new Point$2(elevationSamplePoints[i][0] * this.width, horizon + elevationSamplePoints[i][1] * (this.height - horizon));
            const hit = elevation.pointCoordinate(pt);
            if (!hit)
                continue;
            const distanceToHit = Math.hypot(hit[0] - this._camera.position[0], hit[1] - this._camera.position[1]);
            const weight = 1 / distanceToHit;
            elevationSum += hit[3] * weight;
            weightSum += weight;
        }
        if (weightSum === 0)
            return NaN;
        return elevationSum / weightSum;
    }
    get center() {
        return this._center;
    }
    set center(center) {
        if (center.lat === this._center.lat && center.lng === this._center.lng)
            return;
        this._unmodified = false;
        this._center = center;
        if (this._terrainEnabled()) {
            if (this.cameraElevationReference === 'ground') {
                this._updateCameraOnTerrain();
            } else {
                this._updateZoomFromElevation();
            }
        }
        this._constrain();
        this._calcMatrices();
    }
    _updateZoomFromElevation() {
        if (this._seaLevelZoom == null || !this._elevation)
            return;
        // Compute zoom level from the height of the camera relative to the terrain
        const seaLevelZoom = this._seaLevelZoom;
        const elevationAtCenter = this._elevation.getAtPointOrZero(this.locationCoordinate(this.center));
        const mercatorElevation = this.pixelsPerMeter / this.worldSize * elevationAtCenter;
        const altitude = this._mercatorZfromZoom(seaLevelZoom);
        const minHeight = this._mercatorZfromZoom(this._maxZoom);
        const height = Math.max(altitude - mercatorElevation, minHeight);
        this._setZoom(this._zoomFromMercatorZ(height));
    }
    get padding() {
        return this._edgeInsets.toJSON();
    }
    set padding(padding) {
        if (this._edgeInsets.equals(padding))
            return;
        this._unmodified = false;
        //Update edge-insets inplace
        this._edgeInsets.interpolate(this._edgeInsets, padding, 1);
        this._calcMatrices();
    }
    /**
     * Computes a zoom value relative to a map plane that goes through the provided mercator position.
     *
     * @param {MercatorCoordinate} position A position defining the altitude of the the map plane.
     * @returns {number} The zoom value.
     */
    computeZoomRelativeTo(position) {
        // Find map center position on the target plane by casting a ray from screen center towards the plane.
        // Direct distance to the target position is used if the target position is above camera position.
        const centerOnTargetAltitude = this.rayIntersectionCoordinate(this.pointRayIntersection(this.centerPoint, position.toAltitude()));
        let targetPosition;
        if (position.z < this._camera.position[2]) {
            targetPosition = [
                centerOnTargetAltitude.x,
                centerOnTargetAltitude.y,
                centerOnTargetAltitude.z
            ];
        } else {
            targetPosition = [
                position.x,
                position.y,
                position.z
            ];
        }
        const distToTarget = vec3_1.length(vec3_1.sub([], this._camera.position, targetPosition));
        return clamp(this._zoomFromMercatorZ(distToTarget), this._minZoom, this._maxZoom);
    }
    setFreeCameraOptions(options) {
        if (!this.height)
            return;
        if (!options.position && !options.orientation)
            return;
        // Camera state must be up-to-date before accessing its getters
        this._updateCameraState();
        let changed = false;
        if (options.orientation && !quat_1.exactEquals(options.orientation, this._camera.orientation)) {
            // $FlowFixMe[incompatible-call] - Flow can't infer that orientation is not null
            changed = this._setCameraOrientation(options.orientation);
        }
        if (options.position) {
            const newPosition = [
                options.position.x,
                options.position.y,
                options.position.z
            ];
            if (!vec3_1.exactEquals(newPosition, this._camera.position)) {
                this._setCameraPosition(newPosition);
                changed = true;
            }
        }
        if (changed) {
            this._updateStateFromCamera();
            this.recenterOnTerrain();
        }
    }
    getFreeCameraOptions() {
        this._updateCameraState();
        const pos = this._camera.position;
        const options = new FreeCameraOptions();
        options.position = new MercatorCoordinate(pos[0], pos[1], pos[2]);
        options.orientation = this._camera.orientation;
        options._elevation = this.elevation;
        options._renderWorldCopies = this.renderWorldCopies;
        return options;
    }
    _setCameraOrientation(orientation) {
        // zero-length quaternions are not valid
        if (!quat_1.length(orientation))
            return false;
        quat_1.normalize(orientation, orientation);
        // The new orientation must be sanitized by making sure it can be represented
        // with a pitch and bearing. Roll-component must be removed and the camera can't be upside down
        const forward = vec3_1.transformQuat([], [
            0,
            0,
            -1
        ], orientation);
        const up = vec3_1.transformQuat([], [
            0,
            -1,
            0
        ], orientation);
        if (up[2] < 0)
            return false;
        const updatedOrientation = orientationFromFrame(forward, up);
        if (!updatedOrientation)
            return false;
        this._camera.orientation = updatedOrientation;
        return true;
    }
    _setCameraPosition(position) {
        // Altitude must be clamped to respect min and max zoom
        const minWorldSize = this.zoomScale(this.minZoom) * this.tileSize;
        const maxWorldSize = this.zoomScale(this.maxZoom) * this.tileSize;
        const distToCenter = this.cameraToCenterDistance;
        position[2] = clamp(position[2], distToCenter / maxWorldSize, distToCenter / minWorldSize);
        this._camera.position = position;
    }
    /**
     * The center of the screen in pixels with the top-left corner being (0,0)
     * and +y axis pointing downwards. This accounts for padding.
     *
     * @readonly
     * @type {Point}
     * @memberof Transform
     */
    get centerPoint() {
        return this._edgeInsets.getCenter(this.width, this.height);
    }
    /**
     * Returns the vertical half-fov, accounting for padding, in radians.
     *
     * @readonly
     * @type {number}
     * @private
     */
    get fovAboveCenter() {
        return this._fov * (0.5 + this.centerOffset.y / this.height);
    }
    /**
     * Returns true if the padding options are equal.
     *
     * @param {PaddingOptions} padding The padding options to compare.
     * @returns {boolean} True if the padding options are equal.
     * @memberof Transform
     */
    isPaddingEqual(padding) {
        return this._edgeInsets.equals(padding);
    }
    /**
     * Helper method to update edge-insets inplace.
     *
     * @param {PaddingOptions} start The initial padding options.
     * @param {PaddingOptions} target The target padding options.
     * @param {number} t The interpolation variable.
     * @memberof Transform
     */
    interpolatePadding(start, target, t) {
        this._unmodified = false;
        this._edgeInsets.interpolate(start, target, t);
        this._constrain();
        this._calcMatrices();
    }
    /**
     * Return the highest zoom level that fully includes all tiles within the transform's boundaries.
     * @param {Object} options Options.
     * @param {number} options.tileSize Tile size, expressed in screen pixels.
     * @param {boolean} options.roundZoom Target zoom level. If true, the value will be rounded to the closest integer. Otherwise the value will be floored.
     * @returns {number} An integer zoom level at which all tiles will be visible.
     */
    coveringZoomLevel(options) {
        const z = (options.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / options.tileSize));
        // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist.
        return Math.max(0, z);
    }
    /**
     * Return any "wrapped" copies of a given tile coordinate that are visible
     * in the current view.
     *
     * @private
     */
    getVisibleUnwrappedCoordinates(tileID) {
        const result = [new UnwrappedTileID(0, tileID)];
        if (this.renderWorldCopies) {
            const utl = this.pointCoordinate(new Point$2(0, 0));
            const utr = this.pointCoordinate(new Point$2(this.width, 0));
            const ubl = this.pointCoordinate(new Point$2(this.width, this.height));
            const ubr = this.pointCoordinate(new Point$2(0, this.height));
            const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));
            const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));
            // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources.
            // Both sources draw outside the tile boundaries of the tile that "contains them" so we need
            // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones.
            const extraWorldCopy = 1;
            for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {
                if (w === 0)
                    continue;
                result.push(new UnwrappedTileID(w, tileID));
            }
        }
        return result;
    }
    isLODDisabled(checkPitch) {
        // No change of LOD behavior for pitch lower than 60 and when there is no top padding: return only tile ids from the requested zoom level
        return (!checkPitch || this.pitch <= MIN_LOD_PITCH) && this._edgeInsets.top <= this._edgeInsets.bottom && !this._elevation && !this.projection.isReprojectedInTileSpace;
    }
    /**
     * Extends tile coverage to include potential shadow caster tiles.
     * @param {Array<OverscaledTileID>} coveringTiles tiles that are potential shadow receivers
     * @param {Vec3} lightDir direction of the light (unit vector)
     * @param {number} maxZoom maximum zoom level of shadow caster tiles
     * @returns {Array<OverscaledTileID>} a set of potential shadow casters
     */
    extendTileCoverForShadows(coveringTiles, lightDir, maxZoom) {
        let out = [];
        if (lightDir[0] === 0 && lightDir[1] === 0) {
            return out;
        }
        // Extra tile selection based on the direction of the light:
        // For each tile we add neighbourgs that might cast shadows over the current tile
        for (const id of coveringTiles) {
            const tileId = id.canonical;
            const overscaledZ = id.overscaledZ;
            const tileWrap = id.wrap;
            const tiles = 1 << tileId.z;
            const xMaxInsideRange = tileId.x + 1 < tiles;
            const xMinInsideRange = tileId.x > 0;
            const yMaxInsideRange = tileId.y + 1 < tiles;
            const yMinInsideRange = tileId.y > 0;
            const leftWrap = id.wrap - (xMinInsideRange ? 0 : 1);
            const rightWrap = id.wrap + (xMaxInsideRange ? 0 : 1);
            const leftTileX = xMinInsideRange ? tileId.x - 1 : tiles - 1;
            const rightTileX = xMaxInsideRange ? tileId.x + 1 : 0;
            if (lightDir[0] < 0) {
                out.push(new OverscaledTileID(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y));
                if (lightDir[1] < 0 && yMaxInsideRange) {
                    out.push(new OverscaledTileID(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1));
                    out.push(new OverscaledTileID(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y + 1));
                }
                if (lightDir[1] > 0 && yMinInsideRange) {
                    out.push(new OverscaledTileID(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1));
                    out.push(new OverscaledTileID(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y - 1));
                }
            } else if (lightDir[0] > 0) {
                out.push(new OverscaledTileID(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y));
                if (lightDir[1] < 0 && yMaxInsideRange) {
                    out.push(new OverscaledTileID(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1));
                    out.push(new OverscaledTileID(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y + 1));
                }
                if (lightDir[1] > 0 && yMinInsideRange) {
                    out.push(new OverscaledTileID(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1));
                    out.push(new OverscaledTileID(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y - 1));
                }
            } else {
                if (lightDir[1] < 0 && yMaxInsideRange) {
                    out.push(new OverscaledTileID(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1));
                } else if (yMinInsideRange) {
                    out.push(new OverscaledTileID(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1));
                }
            }
        }
        // Remove duplicates from new ids
        if (out.length > 1) {
            out.sort((a, b) => {
                return a.overscaledZ - b.overscaledZ || a.wrap - b.wrap || a.canonical.z - b.canonical.z || a.canonical.x - b.canonical.x || a.canonical.y - b.canonical.y;
            });
            let i = 0;
            let j = 0;
            while (j < out.length) {
                if (!out[j].equals(out[i])) {
                    out[++i] = out[j++];
                } else {
                    ++j;
                }
            }
            out.length = i + 1;
        }
        // Remove higher zoom new IDs that overlap with other new IDs
        const nonOverlappingIds = [];
        for (const id of out) {
            if (!out.some(ancestorCandidate => id.isChildOf(ancestorCandidate))) {
                nonOverlappingIds.push(id);
            }
        }
        // Remove new IDs that overlap with old IDs
        out = nonOverlappingIds.filter(newId => !coveringTiles.some(oldId => {
            if (newId.overscaledZ < maxZoom && oldId.isChildOf(newId)) {
                return true;
            }
            // Remove identical IDs or children of existing IDs
            return newId.equals(oldId) || newId.isChildOf(oldId);
        }));
        return out;
    }
    /**
     * Return all coordinates that could cover this transform for a covering
     * zoom level.
     * @param {Object} options
     * @param {number} options.tileSize
     * @param {number} options.minzoom
     * @param {number} options.maxzoom
     * @param {boolean} options.roundZoom
     * @param {boolean} options.reparseOverscaled
     * @returns {Array<OverscaledTileID>} OverscaledTileIDs
     * @private
     */
    coveringTiles(options) {
        let z = this.coveringZoomLevel(options);
        const actualZ = z;
        const hasExaggeration = this.elevation && this.elevation.exaggeration();
        const useElevationData = hasExaggeration && !options.isTerrainDEM;
        const isMercator = this.projection.name === 'mercator';
        if (options.minzoom !== undefined && z < options.minzoom)
            return [];
        if (options.maxzoom !== undefined && z > options.maxzoom)
            z = options.maxzoom;
        const centerCoord = this.locationCoordinate(this.center);
        const centerLatitude = this.center.lat;
        const numTiles = 1 << z;
        const centerPoint = [
            numTiles * centerCoord.x,
            numTiles * centerCoord.y,
            0
        ];
        const isGlobe = this.projection.name === 'globe';
        const zInMeters = !isGlobe;
        const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, z, zInMeters);
        const cameraCoord = isGlobe ? this._camera.mercatorPosition : this.pointCoordinate(this.getCameraPoint());
        const meterToTile = numTiles * mercatorZfromAltitude(1, this.center.lat);
        const cameraAltitude = this._camera.position[2] / mercatorZfromAltitude(1, this.center.lat);
        const cameraPoint = [
            numTiles * cameraCoord.x,
            numTiles * cameraCoord.y,
            cameraAltitude * (zInMeters ? 1 : meterToTile)
        ];
        const verticalFrustumIntersect = isGlobe || hasExaggeration;
        // Let's consider an example for !roundZoom: e.g. tileZoom 16 is used from zoom 16 all the way to zoom 16.99.
        // This would mean that the minimal distance to split would be based on distance from camera to center of 16.99 zoom.
        // The same is already incorporated in logic behind roundZoom for raster (so there is no adjustment needed in following line).
        // 0.02 added to compensate for precision errors, see "coveringTiles for terrain" test in transform.test.js.
        const zoomSplitDistance = this.cameraToCenterDistance / options.tileSize * (options.roundZoom ? 1 : 0.502);
        const minZoom = this.isLODDisabled(true) ? z : 0;
        // When calculating tile cover for terrain, create deep AABB for nodes, to ensure they intersect frustum: for sources,
        // other than DEM, use minimum of visible DEM tiles and center altitude as upper bound (pitch is always less than 90°).
        const maxRange = options.isTerrainDEM && this._elevation ? this._elevation.exaggeration() * 10000 : this._centerAltitude;
        const minRange = options.isTerrainDEM ? -maxRange : this._elevation ? this._elevation.getMinElevationBelowMSL() : 0;
        const scaleAdjustment = this.projection.isReprojectedInTileSpace ? getScaleAdjustment(this) : 1;
        const relativeScaleAtMercatorCoord = mc => {
            // Calculate how scale compares between projected coordinates and mercator coordinates.
            // Returns a length. The units don't matter since the result is only
            // used in a ratio with other values returned by this function.
            // Construct a small square in Mercator coordinates.
            const offset = 1 / 40000;
            const mcEast = new MercatorCoordinate(mc.x + offset, mc.y, mc.z);
            const mcSouth = new MercatorCoordinate(mc.x, mc.y + offset, mc.z);
            // Convert the square to projected coordinates.
            const ll = mc.toLngLat();
            const llEast = mcEast.toLngLat();
            const llSouth = mcSouth.toLngLat();
            const p = this.locationCoordinate(ll);
            const pEast = this.locationCoordinate(llEast);
            const pSouth = this.locationCoordinate(llSouth);
            // Calculate the size of each edge of the reprojected square
            const dx = Math.hypot(pEast.x - p.x, pEast.y - p.y);
            const dy = Math.hypot(pSouth.x - p.x, pSouth.y - p.y);
            // Calculate the size of a projected square that would have the
            // same area as the reprojected square.
            return Math.sqrt(dx * dy) * scaleAdjustment / offset;
        };
        const newRootTile = wrap => {
            const max = maxRange;
            const min = minRange;
            return {
                // With elevation, this._elevation provides z coordinate values. For 2D:
                // All tiles are on zero elevation plane => z difference is zero
                aabb: tileAABB(this, numTiles, 0, 0, 0, wrap, min, max, this.projection),
                zoom: 0,
                x: 0,
                y: 0,
                minZ: min,
                maxZ: max,
                wrap,
                fullyVisible: false
            };
        };
        // Do a depth-first traversal to find visible tiles and proper levels of detail
        const stack = [];
        let result = [];
        const maxZoom = z;
        const overscaledZ = options.reparseOverscaled ? actualZ : z;
        const square = a => a * a;
        const cameraHeightSqr = square((cameraAltitude - this._centerAltitude) * meterToTile);
        // in tile coordinates.
        const getAABBFromElevation = it => {
            if (!this._elevation || !it.tileID || !isMercator)
                return;
            // To silence flow.
            const minmax = this._elevation.getMinMaxForTile(it.tileID);
            const aabb = it.aabb;
            if (minmax) {
                aabb.min[2] = minmax.min;
                aabb.max[2] = minmax.max;
                aabb.center[2] = (aabb.min[2] + aabb.max[2]) / 2;
            } else {
                it.shouldSplit = shouldSplit(it);
                if (!it.shouldSplit) {
                    // At final zoom level, while corresponding DEM tile is not loaded yet,
                    // assume center elevation. This covers ground to horizon and prevents
                    // loading unnecessary tiles until DEM cover is fully loaded.
                    aabb.min[2] = aabb.max[2] = aabb.center[2] = this._centerAltitude;
                }
            }
        };
        // Scale distance to split for acute angles.
        // dzSqr: z component of camera to tile distance, square.
        // dSqr: 3D distance of camera to tile, square.
        const distToSplitScale = (dzSqr, dSqr) => {
            // When the angle between camera to tile ray and tile plane is smaller
            // than acuteAngleThreshold, scale the distance to split. Scaling is adaptive: smaller
            // the angle, the scale gets lower value. Although it seems early to start at 45,
            // it is not: scaling kicks in around 60 degrees pitch.
            const acuteAngleThresholdSin = 0.707;
            // Math.sin(45)
            const stretchTile = 1.1;
            // Distances longer than 'dz / acuteAngleThresholdSin' gets scaled
            // following geometric series sum: every next dz length in distance can be
            // 'stretchTile times' longer. It is further, the angle is sharper. Total,
            // adjusted, distance would then be:
            // = dz / acuteAngleThresholdSin + (dz * stretchTile + dz * stretchTile ^ 2 + ... + dz * stretchTile ^ k),
            // where k = (d - dz / acuteAngleThresholdSin) / dz = d / dz - 1 / acuteAngleThresholdSin;
            // = dz / acuteAngleThresholdSin + dz * ((stretchTile ^ (k + 1) - 1) / (stretchTile - 1) - 1)
            // or put differently, given that k is based on d and dz, tile on distance d could be used on distance scaled by:
            // 1 / acuteAngleThresholdSin + (stretchTile ^ (k + 1) - 1) / (stretchTile - 1) - 1
            if (dSqr * square(acuteAngleThresholdSin) < dzSqr)
                return 1;
            // Early return, no scale.
            const r = Math.sqrt(dSqr / dzSqr);
            const k = r - 1 / acuteAngleThresholdSin;
            return r / (1 / acuteAngleThresholdSin + (Math.pow(stretchTile, k + 1) - 1) / (stretchTile - 1) - 1);
        };
        const shouldSplit = it => {
            if (it.zoom < minZoom) {
                return true;
            } else if (it.zoom === maxZoom) {
                return false;
            }
            if (it.shouldSplit != null) {
                return it.shouldSplit;
            }
            const dx = it.aabb.distanceX(cameraPoint);
            const dy = it.aabb.distanceY(cameraPoint);
            let dzSqr = cameraHeightSqr;
            let tileScaleAdjustment = 1;
            if (isGlobe) {
                dzSqr = square(it.aabb.distanceZ(cameraPoint));
                // Compensate physical sizes of the tiles when determining which zoom level to use.
                // In practice tiles closer to poles should use more aggressive LOD as their
                // physical size is already smaller than size of tiles near the equator.
                const tilesAtZoom = Math.pow(2, it.zoom);
                const minLat = latFromMercatorY((it.y + 1) / tilesAtZoom);
                const maxLat = latFromMercatorY(it.y / tilesAtZoom);
                const closestLat = Math.min(Math.max(centerLatitude, minLat), maxLat);
                const relativeTileScale = circumferenceAtLatitude(closestLat) / circumferenceAtLatitude(centerLatitude);
                // With globe, the rendered scale does not exactly match the mercator scale at low zoom levels.
                // Account for this difference during LOD of loading so that you load the correct size tiles.
                // We try to compromise between two conflicting requirements:
                // - loading tiles at the camera's zoom level (for visual and styling consistency)
                // - loading correct size tiles (to reduce the number of tiles loaded)
                // These are arbitrarily balanced:
                if (closestLat === centerLatitude) {
                    // For tiles that are in the middle of the viewport, prioritize matching the camera
                    // zoom and allow divergence from the true scale.
                    const maxDivergence = 0.3;
                    tileScaleAdjustment = 1 / Math.max(1, this._mercatorScaleRatio - maxDivergence);
                } else {
                    // For other tiles, use the real scale to reduce tile counts near poles.
                    tileScaleAdjustment = Math.min(1, relativeTileScale / this._mercatorScaleRatio);
                }
                // Ensure that all tiles near the center have the same zoom level.
                // With LOD tile loading, tile zoom levels can change when scale slightly changes.
                // These differences can be pretty different in globe view. Work around this by
                // making more tiles match the center tile's zoom level. If the tiles are nearly big enough,
                // round up. Only apply this adjustment before the transition to mercator rendering has started.
                if (this.zoom <= GLOBE_ZOOM_THRESHOLD_MIN && it.zoom === maxZoom - 1 && relativeTileScale >= 0.9) {
                    return true;
                }
            } else {
                if (useElevationData) {
                    dzSqr = square(it.aabb.distanceZ(cameraPoint) * meterToTile);
                }
                if (this.projection.isReprojectedInTileSpace && actualZ <= 5) {
                    // In other projections, not all tiles are the same size.
                    // Account for the tile size difference by adjusting the distToSplit.
                    // Adjust by the ratio of the area at the tile center to the area at the map center.
                    // Adjustments are only needed at lower zooms where tiles are not similarly sized.
                    const numTiles = Math.pow(2, it.zoom);
                    const relativeScale = relativeScaleAtMercatorCoord(new MercatorCoordinate((it.x + 0.5) / numTiles, (it.y + 0.5) / numTiles));
                    // Fudge the ratio slightly so that all tiles near the center have the same zoom level.
                    tileScaleAdjustment = relativeScale > 0.85 ? 1 : relativeScale;
                }
            }
            const distanceSqr = dx * dx + dy * dy + dzSqr;
            const distToSplit = (1 << maxZoom - it.zoom) * zoomSplitDistance * tileScaleAdjustment;
            const distToSplitSqr = square(distToSplit * distToSplitScale(Math.max(dzSqr, cameraHeightSqr), distanceSqr));
            return distanceSqr < distToSplitSqr;
        };
        if (this.renderWorldCopies) {
            // Render copy of the globe thrice on both sides
            for (let i = 1; i <= NUM_WORLD_COPIES; i++) {
                stack.push(newRootTile(-i));
                stack.push(newRootTile(i));
            }
        }
        stack.push(newRootTile(0));
        while (stack.length > 0) {
            const it = stack.pop();
            const x = it.x;
            const y = it.y;
            let fullyVisible = it.fullyVisible;
            const isPoleNeighbourAndGlobeProjection = () => {
                return this.projection.name === 'globe' && (it.y === 0 || it.y === (1 << it.zoom) - 1);
            };
            // Visibility of a tile is not required if any of its ancestor is fully inside the frustum
            if (!fullyVisible) {
                let intersectResult = verticalFrustumIntersect ? it.aabb.intersects(cameraFrustum) : it.aabb.intersectsFlat(cameraFrustum);
                // For globe projection and pole neighboouring tiles - clip against pole segments as well
                if (intersectResult === 0 && isPoleNeighbourAndGlobeProjection()) {
                    const tileId = new CanonicalTileID(it.zoom, x, y);
                    const poleAABB = aabbForTileOnGlobe(this, numTiles, tileId, true);
                    intersectResult = poleAABB.intersects(cameraFrustum);
                }
                if (intersectResult === 0) {
                    continue;
                }
                fullyVisible = intersectResult === 2;
            }
            // Have we reached the target depth or is the tile too far away to be any split further?
            if (it.zoom === maxZoom || !shouldSplit(it)) {
                const tileZoom = it.zoom === maxZoom ? overscaledZ : it.zoom;
                if (!!options.minzoom && options.minzoom > tileZoom) {
                    // Not within source tile range.
                    continue;
                }
                // Perform more precise intersection tests to cull the remaining < 1% false positives from the earlier test.
                if (!fullyVisible) {
                    let intersectResult = verticalFrustumIntersect ? it.aabb.intersectsPrecise(cameraFrustum) : it.aabb.intersectsPreciseFlat(cameraFrustum);
                    // For globe projection and pole neighboouring tiles - clip against pole segments as well
                    if (intersectResult === 0 && isPoleNeighbourAndGlobeProjection()) {
                        const tileId = new CanonicalTileID(it.zoom, x, y);
                        const poleAABB = aabbForTileOnGlobe(this, numTiles, tileId, true);
                        intersectResult = poleAABB.intersectsPrecise(cameraFrustum);
                    }
                    if (intersectResult === 0) {
                        continue;
                    }
                }
                const dx = centerPoint[0] - (0.5 + x + (it.wrap << it.zoom)) * (1 << z - it.zoom);
                const dy = centerPoint[1] - 0.5 - y;
                const id = it.tileID ? it.tileID : new OverscaledTileID(tileZoom, it.wrap, it.zoom, x, y);
                result.push({
                    tileID: id,
                    distanceSq: dx * dx + dy * dy
                });
                continue;
            }
            for (let i = 0; i < 4; i++) {
                const childX = (x << 1) + i % 2;
                const childY = (y << 1) + (i >> 1);
                const aabb = isMercator ? it.aabb.quadrant(i) : tileAABB(this, numTiles, it.zoom + 1, childX, childY, it.wrap, it.minZ, it.maxZ, this.projection);
                const child = {
                    aabb,
                    zoom: it.zoom + 1,
                    x: childX,
                    y: childY,
                    wrap: it.wrap,
                    fullyVisible,
                    tileID: undefined,
                    shouldSplit: undefined,
                    minZ: it.minZ,
                    maxZ: it.maxZ
                };
                if (useElevationData && !isGlobe) {
                    child.tileID = new OverscaledTileID(it.zoom + 1 === maxZoom ? overscaledZ : it.zoom + 1, it.wrap, it.zoom + 1, childX, childY);
                    getAABBFromElevation(child);
                }
                stack.push(child);
            }
        }
        if (this.fogCullDistSq) {
            const fogCullDistSq = this.fogCullDistSq;
            const horizonLineFromTop = this.horizonLineFromTop();
            result = result.filter(entry => {
                const tl = [
                    0,
                    0,
                    0,
                    1
                ];
                const br = [
                    EXTENT,
                    EXTENT,
                    0,
                    1
                ];
                const fogTileMatrix = this.calculateFogTileMatrix(entry.tileID.toUnwrapped());
                vec4_1.transformMat4(tl, tl, fogTileMatrix);
                vec4_1.transformMat4(br, br, fogTileMatrix);
                // the fog matrix can flip the min/max values, so we calculate them explicitly
                const min = vec4_1.min([], tl, br);
                const max = vec4_1.max([], tl, br);
                const sqDist = getAABBPointSquareDist(min, max);
                if (sqDist === 0) {
                    return true;
                }
                let overHorizonLine = false;
                // Terrain loads at one zoom level lower than the raster data,
                // so the following checks whether the terrain sits above the horizon and ensures that
                // when mountains stick out above the fog (due to horizon-blend),
                // we haven’t accidentally culled some of the raster tiles we need to draw on them.
                // If we don’t do this, the terrain is default black color and may flash in and out as we move toward it.
                const elevation = this._elevation;
                if (elevation && sqDist > fogCullDistSq && horizonLineFromTop !== 0) {
                    const projMatrix = this.calculateProjMatrix(entry.tileID.toUnwrapped());
                    let minmax;
                    if (!options.isTerrainDEM) {
                        minmax = elevation.getMinMaxForTile(entry.tileID);
                    }
                    if (!minmax) {
                        minmax = {
                            min: minRange,
                            max: maxRange
                        };
                    }
                    // ensure that we want `this.rotation` instead of `this.bearing` here
                    const cornerFar = furthestTileCorner(this.rotation);
                    const farX = cornerFar[0] * EXTENT;
                    const farY = cornerFar[1] * EXTENT;
                    const worldFar = [
                        farX,
                        farY,
                        minmax.max
                    ];
                    // World to NDC
                    vec3_1.transformMat4(worldFar, worldFar, projMatrix);
                    // NDC to Screen
                    const screenCoordY = (1 - worldFar[1]) * this.height * 0.5;
                    // Prevent cutting tiles crossing over the horizon line to
                    // prevent pop-in and out within the fog culling range
                    overHorizonLine = screenCoordY < horizonLineFromTop;
                }
                return sqDist < fogCullDistSq || overHorizonLine;
            });
        }
        const cover = result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID);
        return cover;
    }
    resize(width, height) {
        this.width = width;
        this.height = height;
        this.pixelsToGLUnits = [
            2 / width,
            -2 / height
        ];
        this._constrain();
        this._calcMatrices();
    }
    get unmodified() {
        return this._unmodified;
    }
    zoomScale(zoom) {
        return Math.pow(2, zoom);
    }
    scaleZoom(scale) {
        return Math.log(scale) / Math.LN2;
    }
    // Transform from LngLat to Point in world coordinates [-180, 180] x [90, -90] --> [0, this.worldSize] x [0, this.worldSize]
    project(lnglat) {
        const lat = clamp(lnglat.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
        const projectedLngLat = this.projection.project(lnglat.lng, lat);
        return new Point$2(projectedLngLat.x * this.worldSize, projectedLngLat.y * this.worldSize);
    }
    // Transform from Point in world coordinates to LngLat [0, this.worldSize] x [0, this.worldSize] --> [-180, 180] x [90, -90]
    unproject(point) {
        return this.projection.unproject(point.x / this.worldSize, point.y / this.worldSize);
    }
    // Point at center in world coordinates.
    get point() {
        return this.project(this.center);
    }
    // Point at center in Mercator coordinates.
    get pointMerc() {
        return this.point._div(this.worldSize);
    }
    // Ratio of pixelsPerMeter in the current projection to Mercator's.
    get pixelsPerMeterRatio() {
        return this.pixelsPerMeter / mercatorZfromAltitude(1, this.center.lat) / this.worldSize;
    }
    setLocationAtPoint(lnglat, point) {
        let x, y;
        const centerPoint = this.centerPoint;
        if (this.projection.name === 'globe') {
            // Pixel coordinates are applied directly to the globe
            const worldSize = this.worldSize;
            x = (point.x - centerPoint.x) / worldSize;
            y = (point.y - centerPoint.y) / worldSize;
        } else {
            const a = this.pointCoordinate(point);
            const b = this.pointCoordinate(centerPoint);
            x = a.x - b.x;
            y = a.y - b.y;
        }
        const loc = this.locationCoordinate(lnglat);
        this.setLocation(new MercatorCoordinate(loc.x - x, loc.y - y));
    }
    setLocation(location) {
        this.center = this.coordinateLocation(location);
        if (this.projection.wrap) {
            this.center = this.center.wrap();
        }
    }
    /**
     * Given a location, return the screen point that corresponds to it. In 3D mode
     * (with terrain) this behaves the same as in 2D mode.
     * This method is coupled with {@see pointLocation} in 3D mode to model map manipulation
     * using flat plane approach to keep constant elevation above ground.
     * @param {LngLat} lnglat location
     * @returns {Point} screen point
     * @private
     */
    locationPoint(lnglat) {
        return this.projection.locationPoint(this, lnglat);
    }
    /**
     * Given a location, return the screen point that corresponds to it
     * In 3D mode (when terrain is enabled) elevation is sampled for the point before
     * projecting it. In 2D mode, behaves the same locationPoint.
     * @param {LngLat} lnglat location
     * @returns {Point} screen point
     * @private
     */
    locationPoint3D(lnglat) {
        return this.projection.locationPoint(this, lnglat, true);
    }
    /**
     * Given a point on screen, return its lnglat
     * @param {Point} p screen point
     * @returns {LngLat} lnglat location
     * @private
     */
    pointLocation(p) {
        return this.coordinateLocation(this.pointCoordinate(p));
    }
    /**
     * Given a point on screen, return its lnglat
     * In 3D mode (map with terrain) returns location of terrain raycast point.
     * In 2D mode, behaves the same as {@see pointLocation}.
     * @param {Point} p screen point
     * @returns {LngLat} lnglat location
     * @private
     */
    pointLocation3D(p) {
        return this.coordinateLocation(this.pointCoordinate3D(p));
    }
    /**
     * Given a geographical lngLat, return an unrounded
     * coordinate that represents it at this transform's zoom level.
     * @param {LngLat} lngLat
     * @returns {Coordinate}
     * @private
     */
    locationCoordinate(lngLat, altitude) {
        const z = altitude ? mercatorZfromAltitude(altitude, lngLat.lat) : undefined;
        const projectedLngLat = this.projection.project(lngLat.lng, lngLat.lat);
        return new MercatorCoordinate(projectedLngLat.x, projectedLngLat.y, z);
    }
    /**
     * Given a Coordinate, return its geographical position.
     * @param {Coordinate} coord
     * @returns {LngLat} lngLat
     * @private
     */
    coordinateLocation(coord) {
        return this.projection.unproject(coord.x, coord.y);
    }
    /**
     * Casts a ray from a point on screen and returns the Ray,
     * and the extent along it, at which it intersects the map plane.
     *
     * @param {Point} p Viewport pixel co-ordinates.
     * @param {number} z Optional altitude of the map plane, defaulting to elevation at center.
     * @returns {{ p0: Vec4, p1: Vec4, t: number }} p0,p1 are two points on the ray.
     * t is the fractional extent along the ray at which the ray intersects the map plane.
     * @private
     */
    pointRayIntersection(p, z) {
        const targetZ = z !== undefined && z !== null ? z : this._centerAltitude;
        // Since we don't know the correct projected z value for the point,
        // unproject two points to get a line and then find the point on that
        // line with z=0.
        const p0 = [
            p.x,
            p.y,
            0,
            1
        ];
        const p1 = [
            p.x,
            p.y,
            1,
            1
        ];
        vec4_1.transformMat4(p0, p0, this.pixelMatrixInverse);
        vec4_1.transformMat4(p1, p1, this.pixelMatrixInverse);
        const w0 = p0[3];
        const w1 = p1[3];
        vec4_1.scale(p0, p0, 1 / w0);
        vec4_1.scale(p1, p1, 1 / w1);
        const z0 = p0[2];
        const z1 = p1[2];
        const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);
        return {
            p0,
            p1,
            t
        };
    }
    screenPointToMercatorRay(p) {
        const p0 = [
            p.x,
            p.y,
            0,
            1
        ];
        const p1 = [
            p.x,
            p.y,
            1,
            1
        ];
        vec4_1.transformMat4(p0, p0, this.pixelMatrixInverse);
        vec4_1.transformMat4(p1, p1, this.pixelMatrixInverse);
        vec4_1.scale(p0, p0, 1 / p0[3]);
        vec4_1.scale(p1, p1, 1 / p1[3]);
        // Convert altitude from meters to pixels.
        p0[2] = mercatorZfromAltitude(p0[2], this._center.lat) * this.worldSize;
        p1[2] = mercatorZfromAltitude(p1[2], this._center.lat) * this.worldSize;
        vec4_1.scale(p0, p0, 1 / this.worldSize);
        vec4_1.scale(p1, p1, 1 / this.worldSize);
        return new Ray([
            p0[0],
            p0[1],
            p0[2]
        ], vec3_1.normalize([], vec3_1.sub([], p1, p0)));
    }
    /**
     *  Helper method to convert the ray intersection with the map plane to MercatorCoordinate.
     *
     * @param {RayIntersectionResult} rayIntersection
     * @returns {MercatorCoordinate}
     * @private
     */
    rayIntersectionCoordinate(rayIntersection) {
        const {p0, p1, t} = rayIntersection;
        const z0 = mercatorZfromAltitude(p0[2], this._center.lat);
        const z1 = mercatorZfromAltitude(p1[2], this._center.lat);
        return new MercatorCoordinate(number(p0[0], p1[0], t) / this.worldSize, number(p0[1], p1[1], t) / this.worldSize, number(z0, z1, t));
    }
    /**
     * Given a point on screen, returns MercatorCoordinate.
     * @param {Point} p Top left origin screen point, in pixels.
     * @param {number} z Optional altitude of the map plane, defaulting to elevation at center.
     * @private
     */
    pointCoordinate(p, z = this._centerAltitude) {
        return this.projection.pointCoordinate(this, p.x, p.y, z);
    }
    /**
     * Given a point on screen, returns MercatorCoordinate.
     * In 3D mode, raycast to terrain. In 2D mode, behaves the same as {@see pointCoordinate}.
     * For p above terrain, don't return point behind camera but clamp p.y at the top of terrain.
     * @param {Point} p top left origin screen point, in pixels.
     * @private
     */
    pointCoordinate3D(p) {
        if (!this.elevation)
            return this.pointCoordinate(p);
        let raycast = this.projection.pointCoordinate3D(this, p.x, p.y);
        if (raycast)
            return new MercatorCoordinate(raycast[0], raycast[1], raycast[2]);
        let start = 0, end = this.horizonLineFromTop();
        if (p.y > end)
            return this.pointCoordinate(p);
        // holes between tiles below horizon line or below bottom.
        const samples = 10;
        const threshold = 0.02 * end;
        const r = p.clone();
        for (let i = 0; i < samples && end - start > threshold; i++) {
            r.y = number(start, end, 0.66);
            // non uniform binary search favoring points closer to horizon.
            const rCast = this.projection.pointCoordinate3D(this, r.x, r.y);
            if (rCast) {
                end = r.y;
                raycast = rCast;
            } else {
                start = r.y;
            }
        }
        return raycast ? new MercatorCoordinate(raycast[0], raycast[1], raycast[2]) : this.pointCoordinate(p);
    }
    /**
     * Returns true if a screenspace Point p, is above the horizon.
     * In non-globe projections, this approximates the map as an infinite plane and does not account for z0-z3
     * wherein the map is small quad with whitespace above the north pole and below the south pole.
     *
     * @param {Point} p
     * @returns {boolean}
     * @private
     */
    isPointAboveHorizon(p) {
        return this.projection.isPointAboveHorizon(this, p);
    }
    /**
     * Determines if the given point is located on a visible map surface.
     *
     * @param {Point} p
     * @returns {boolean}
     * @private
     */
    isPointOnSurface(p) {
        if (p.y < 0 || p.y > this.height || p.x < 0 || p.x > this.width)
            return false;
        if (this.elevation || this.zoom >= GLOBE_ZOOM_THRESHOLD_MAX)
            return !this.isPointAboveHorizon(p);
        const coord = this.pointCoordinate(p);
        return coord.y >= 0 && coord.y <= 1;
    }
    /**
     * Given a coordinate, return the screen point that corresponds to it
     * @param {Coordinate} coord
     * @param {boolean} sampleTerrainIn3D in 3D mode (terrain enabled), sample elevation for the point.
     * If false, do the same as in 2D mode, assume flat camera elevation plane for all points.
     * @returns {Point} screen point
     * @private
     */
    _coordinatePoint(coord, sampleTerrainIn3D) {
        const elevation = sampleTerrainIn3D && this.elevation ? this.elevation.getAtPointOrZero(coord, this._centerAltitude) : this._centerAltitude;
        const p = [
            coord.x * this.worldSize,
            coord.y * this.worldSize,
            elevation + coord.toAltitude(),
            1
        ];
        vec4_1.transformMat4(p, p, this.pixelMatrix);
        return p[3] > 0 ? new Point$2(p[0] / p[3], p[1] / p[3]) : new Point$2(Number.MAX_VALUE, Number.MAX_VALUE);
    }
    // In Globe, conic and thematic projections, Lng/Lat extremes are not always at corners.
    // This function additionally checks each screen edge midpoint.
    // While midpoints continue to be extremes, it recursively checks midpoints of smaller segments.
    _getBoundsNonRectangular() {
        const {top, left} = this._edgeInsets;
        const bottom = this.height - this._edgeInsets.bottom;
        const right = this.width - this._edgeInsets.right;
        const tl = this.pointLocation3D(new Point$2(left, top));
        const tr = this.pointLocation3D(new Point$2(right, top));
        const br = this.pointLocation3D(new Point$2(right, bottom));
        const bl = this.pointLocation3D(new Point$2(left, bottom));
        let west = Math.min(tl.lng, tr.lng, br.lng, bl.lng);
        let east = Math.max(tl.lng, tr.lng, br.lng, bl.lng);
        let south = Math.min(tl.lat, tr.lat, br.lat, bl.lat);
        let north = Math.max(tl.lat, tr.lat, br.lat, bl.lat);
        // we pick an error threshold for calculating the bbox that balances between performance and precision
        // Roughly emulating behavior of maxErr in tile_transform.js
        const s = Math.pow(2, -this.zoom);
        const maxErr = s / 16 * 270;
        // 270 = avg(180, 360) i.e. rough conversion between Mercator coords and Lat/Lng
        // We check a minimum of 15 points on each side for Albers, etc.
        // We check a minmum of one midpoint on each side per globe.
        // Globe checks require raytracing and are slower
        // and mising area near the horizon is highly compressed so not noticeable
        const minRecursions = this.projection.name === 'globe' ? 1 : 4;
        const processSegment = (ax, ay, bx, by, depth) => {
            const mx = (ax + bx) / 2;
            const my = (ay + by) / 2;
            const p = new Point$2(mx, my);
            const {lng, lat} = this.pointLocation3D(p);
            // The error metric is the maximum change to bounds from a given point
            const err = Math.max(0, west - lng, south - lat, lng - east, lat - north);
            west = Math.min(west, lng);
            east = Math.max(east, lng);
            south = Math.min(south, lat);
            north = Math.max(north, lat);
            if (depth < minRecursions || err > maxErr) {
                processSegment(ax, ay, mx, my, depth + 1);
                processSegment(mx, my, bx, by, depth + 1);
            }
        };
        processSegment(left, top, right, top, 1);
        processSegment(right, top, right, bottom, 1);
        processSegment(right, bottom, left, bottom, 1);
        processSegment(left, bottom, left, top, 1);
        if (this.projection.name === 'globe') {
            const [northPoleIsVisible, southPoleIsVisible] = polesInViewport(this);
            if (northPoleIsVisible) {
                north = 90;
                east = 180;
                west = -180;
            } else if (southPoleIsVisible) {
                south = -90;
                east = 180;
                west = -180;
            }
        }
        return new LngLatBounds(new LngLat$1(west, south), new LngLat$1(east, north));
    }
    _getBoundsRectangular(min, max) {
        const {top, left} = this._edgeInsets;
        const bottom = this.height - this._edgeInsets.bottom;
        const right = this.width - this._edgeInsets.right;
        const topLeft = new Point$2(left, top);
        const topRight = new Point$2(right, top);
        const bottomRight = new Point$2(right, bottom);
        const bottomLeft = new Point$2(left, bottom);
        // Consider far points at the maximum possible elevation
        // and near points at the minimum to ensure full coverage.
        let tl = this.pointCoordinate(topLeft, min);
        let tr = this.pointCoordinate(topRight, min);
        const br = this.pointCoordinate(bottomRight, max);
        const bl = this.pointCoordinate(bottomLeft, max);
        // If map pitch places top corners off map edge (latitude > 90 or < -90),
        // place them at the intersection between the left/right screen edge and map edge.
        const slope = (p1, p2) => (p2.y - p1.y) / (p2.x - p1.x);
        if (tl.y > 1 && tr.y >= 0)
            tl = new MercatorCoordinate((1 - bl.y) / slope(bl, tl) + bl.x, 1);
        else if (tl.y < 0 && tr.y <= 1)
            tl = new MercatorCoordinate(-bl.y / slope(bl, tl) + bl.x, 0);
        if (tr.y > 1 && tl.y >= 0)
            tr = new MercatorCoordinate((1 - br.y) / slope(br, tr) + br.x, 1);
        else if (tr.y < 0 && tl.y <= 1)
            tr = new MercatorCoordinate(-br.y / slope(br, tr) + br.x, 0);
        return new LngLatBounds().extend(this.coordinateLocation(tl)).extend(this.coordinateLocation(tr)).extend(this.coordinateLocation(bl)).extend(this.coordinateLocation(br));
    }
    _getBoundsRectangularTerrain() {
        const elevation = this.elevation;
        if (!elevation.visibleDemTiles.length || elevation.isUsingMockSource()) {
            return this._getBoundsRectangular(0, 0);
        }
        const minmax = elevation.visibleDemTiles.reduce((acc, t) => {
            if (t.dem) {
                const tree = t.dem.tree;
                acc.min = Math.min(acc.min, tree.minimums[0]);
                acc.max = Math.max(acc.max, tree.maximums[0]);
            }
            return acc;
        }, {
            min: Number.MAX_VALUE,
            max: 0
        });
        return this._getBoundsRectangular(minmax.min * elevation.exaggeration(), minmax.max * elevation.exaggeration());
    }
    /**
     * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not
     * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
     *
     * @returns {LngLatBounds} Returns a {@link LngLatBounds} object describing the map's geographical bounds.
     */
    getBounds() {
        if (this.projection.name === 'mercator' || this.projection.name === 'equirectangular') {
            if (this._terrainEnabled())
                return this._getBoundsRectangularTerrain();
            return this._getBoundsRectangular(0, 0);
        }
        return this._getBoundsNonRectangular();
    }
    /**
     * Returns position of horizon line from the top of the map in pixels.
     * If horizon is not visible, returns 0 by default or a negative value if called with clampToTop = false.
     * @private
     */
    horizonLineFromTop(clampToTop = true) {
        // h is height of space above map center to horizon.
        const h = this.height / 2 / Math.tan(this._fov / 2) / Math.tan(Math.max(this._pitch, 0.1)) - this.centerOffset.y;
        const offset = this.height / 2 - h * (1 - this._horizonShift);
        return clampToTop ? Math.max(0, offset) : offset;
    }
    /**
     * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
     * @returns {LngLatBounds} {@link LngLatBounds}.
     */
    getMaxBounds() {
        return this.maxBounds;
    }
    /**
     * Sets or clears the map's geographical constraints.
     *
     * @param {LngLatBounds} bounds A {@link LngLatBounds} object describing the new geographic boundaries of the map.
     */
    setMaxBounds(bounds) {
        this.maxBounds = bounds;
        this.minLat = -MAX_MERCATOR_LATITUDE;
        this.maxLat = MAX_MERCATOR_LATITUDE;
        this.minLng = -180;
        this.maxLng = 180;
        if (bounds) {
            this.minLat = bounds.getSouth();
            this.maxLat = bounds.getNorth();
            this.minLng = bounds.getWest();
            this.maxLng = bounds.getEast();
            if (this.maxLng < this.minLng)
                this.maxLng += 360;
        }
        this.worldMinX = mercatorXfromLng(this.minLng) * this.tileSize;
        this.worldMaxX = mercatorXfromLng(this.maxLng) * this.tileSize;
        this.worldMinY = mercatorYfromLat(this.maxLat) * this.tileSize;
        this.worldMaxY = mercatorYfromLat(this.minLat) * this.tileSize;
        this._constrain();
    }
    calculatePosMatrix(unwrappedTileID, worldSize) {
        return this.projection.createTileMatrix(this, worldSize, unwrappedTileID);
    }
    calculateDistanceTileData(unwrappedTileID) {
        const distanceDataKey = unwrappedTileID.key;
        const cache = this._distanceTileDataCache;
        if (cache[distanceDataKey]) {
            return cache[distanceDataKey];
        }
        //Calculate the offset of the tile
        const canonical = unwrappedTileID.canonical;
        const windowScaleFactor = 1 / this.height;
        const cws = this.cameraWorldSize;
        const scale = cws / this.zoomScale(canonical.z);
        const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;
        const tX = unwrappedX * scale;
        const tY = canonical.y * scale;
        const center = this.point;
        // center is in world/pixel coordinate, ensure it's in the same coordinate space as tX and tY computed earlier.
        center.x *= cws / this.worldSize;
        center.y *= cws / this.worldSize;
        // Calculate the bearing vector by rotating unit vector [0, -1] clockwise
        const angle = this.angle;
        const bX = Math.sin(-angle);
        const bY = -Math.cos(-angle);
        const cX = (center.x - tX) * windowScaleFactor;
        const cY = (center.y - tY) * windowScaleFactor;
        cache[distanceDataKey] = {
            bearing: [
                bX,
                bY
            ],
            center: [
                cX,
                cY
            ],
            scale: scale / EXTENT * windowScaleFactor
        };
        return cache[distanceDataKey];
    }
    /**
     * Calculate the fogTileMatrix that, given a tile coordinate, can be used to
     * calculate its position relative to the camera in units of pixels divided
     * by the map height. Used with fog for consistent computation of distance
     * from camera.
     *
     * @param {UnwrappedTileID} unwrappedTileID;
     * @private
     */
    calculateFogTileMatrix(unwrappedTileID) {
        const fogTileMatrixKey = unwrappedTileID.key;
        const cache = this._fogTileMatrixCache;
        if (cache[fogTileMatrixKey]) {
            return cache[fogTileMatrixKey];
        }
        const posMatrix = this.projection.createTileMatrix(this, this.cameraWorldSizeForFog, unwrappedTileID);
        mat4_1.multiply(posMatrix, this.worldToFogMatrix, posMatrix);
        cache[fogTileMatrixKey] = new Float32Array(posMatrix);
        return cache[fogTileMatrixKey];
    }
    /**
     * Calculate the projMatrix that, given a tile coordinate, would be used to display the tile on the screen.
     * @param {UnwrappedTileID} unwrappedTileID;
     * @private
     */
    calculateProjMatrix(unwrappedTileID, aligned = false) {
        const projMatrixKey = unwrappedTileID.key;
        const cache = aligned ? this._alignedProjMatrixCache : this._projMatrixCache;
        if (cache[projMatrixKey]) {
            return cache[projMatrixKey];
        }
        const posMatrix = this.calculatePosMatrix(unwrappedTileID, this.worldSize);
        const projMatrix = this.projection.isReprojectedInTileSpace ? this.mercatorMatrix : aligned ? this.alignedProjMatrix : this.projMatrix;
        mat4_1.multiply(posMatrix, projMatrix, posMatrix);
        cache[projMatrixKey] = new Float32Array(posMatrix);
        return cache[projMatrixKey];
    }
    calculatePixelsToTileUnitsMatrix(tile) {
        const key = tile.tileID.key;
        const cache = this._pixelsToTileUnitsCache;
        if (cache[key]) {
            return cache[key];
        }
        const matrix = getPixelsToTileUnitsMatrix(tile, this);
        cache[key] = matrix;
        return cache[key];
    }
    customLayerMatrix() {
        return this.mercatorMatrix.slice();
    }
    globeToMercatorMatrix() {
        if (this.projection.name === 'globe') {
            const pixelsToMerc = 1 / this.worldSize;
            const m = mat4_1.fromScaling([], [
                pixelsToMerc,
                pixelsToMerc,
                pixelsToMerc
            ]);
            mat4_1.multiply(m, m, this.globeMatrix);
            return m;
        }
        return undefined;
    }
    recenterOnTerrain() {
        if (!this._elevation || this.projection.name === 'globe')
            return;
        const elevation = this._elevation;
        this._updateCameraState();
        // Cast a ray towards the sea level and find the intersection point with the terrain.
        // We need to use a camera position that exists in the same coordinate space as the data.
        // The default camera position might have been compensated by the active projection model.
        const mercPixelsPerMeter = mercatorZfromAltitude(1, this._center.lat) * this.worldSize;
        const start = this._computeCameraPosition(mercPixelsPerMeter);
        const dir = this._camera.forward();
        // The raycast function expects z-component to be in meters
        const metersToMerc = mercatorZfromAltitude(1, this._center.lat);
        start[2] /= metersToMerc;
        dir[2] /= metersToMerc;
        vec3_1.normalize(dir, dir);
        const t = elevation.raycast(start, dir, elevation.exaggeration());
        if (t) {
            const point = vec3_1.scaleAndAdd([], start, dir, t);
            const newCenter = new MercatorCoordinate(point[0], point[1], mercatorZfromAltitude(point[2], latFromMercatorY(point[1])));
            const camToNew = [
                newCenter.x - start[0],
                newCenter.y - start[1],
                newCenter.z - start[2] * metersToMerc
            ];
            const maxAltitude = (newCenter.z + vec3_1.length(camToNew)) * this._pixelsPerMercatorPixel;
            this._seaLevelZoom = this._zoomFromMercatorZ(maxAltitude);
            // Camera zoom has to be updated as the orbit distance might have changed
            this._centerAltitude = newCenter.toAltitude();
            this._center = this.coordinateLocation(newCenter);
            this._updateZoomFromElevation();
            this._constrain();
            this._calcMatrices();
        }
    }
    _constrainCamera(adaptCameraAltitude = false) {
        if (!this._elevation)
            return;
        const elevation = this._elevation;
        // Find uncompensated camera position for elevation sampling.
        // The default camera position might have been compensated by the active projection model.
        const mercPixelsPerMeter = mercatorZfromAltitude(1, this._center.lat) * this.worldSize;
        const pos = this._computeCameraPosition(mercPixelsPerMeter);
        const elevationAtCamera = elevation.getAtPointOrZero(new MercatorCoordinate(...pos));
        const terrainElevation = this.pixelsPerMeter / this.worldSize * elevationAtCamera;
        const minHeight = this._minimumHeightOverTerrain();
        const cameraHeight = pos[2] - terrainElevation;
        if (cameraHeight <= minHeight) {
            if (cameraHeight < 0 || adaptCameraAltitude) {
                const center = this.locationCoordinate(this._center, this._centerAltitude);
                const cameraToCenter = [
                    pos[0],
                    pos[1],
                    center.z - pos[2]
                ];
                const prevDistToCamera = vec3_1.length(cameraToCenter);
                // Adjust the camera vector so that the camera is placed above the terrain.
                // Distance between the camera and the center point is kept constant.
                cameraToCenter[2] -= (minHeight - cameraHeight) / this._pixelsPerMercatorPixel;
                const newDistToCamera = vec3_1.length(cameraToCenter);
                if (newDistToCamera === 0)
                    return;
                vec3_1.scale(cameraToCenter, cameraToCenter, prevDistToCamera / newDistToCamera * this._pixelsPerMercatorPixel);
                this._camera.position = [
                    pos[0],
                    pos[1],
                    center.z * this._pixelsPerMercatorPixel - cameraToCenter[2]
                ];
                this._updateStateFromCamera();
            } else {
                this._isCameraConstrained = true;
            }
        }
    }
    _constrain() {
        if (!this.center || !this.width || !this.height || this._constraining)
            return;
        this._constraining = true;
        const isGlobe = this.projection.name === 'globe' || this.mercatorFromTransition;
        // alternate constraining for non-Mercator projections
        if (this.projection.isReprojectedInTileSpace || isGlobe) {
            const center = this.center;
            center.lat = clamp(center.lat, this.minLat, this.maxLat);
            if (this.maxBounds || !(this.renderWorldCopies || isGlobe))
                center.lng = clamp(center.lng, this.minLng, this.maxLng);
            this.center = center;
            this._constraining = false;
            return;
        }
        const unmodified = this._unmodified;
        const {x, y} = this.point;
        let s = 0;
        let x2 = x;
        let y2 = y;
        const w2 = this.width / 2;
        const h2 = this.height / 2;
        const minY = this.worldMinY * this.scale;
        const maxY = this.worldMaxY * this.scale;
        if (y - h2 < minY)
            y2 = minY + h2;
        if (y + h2 > maxY)
            y2 = maxY - h2;
        if (maxY - minY < this.height) {
            s = Math.max(s, this.height / (maxY - minY));
            y2 = (maxY + minY) / 2;
        }
        if (this.maxBounds || !this._renderWorldCopies || !this.projection.wrap) {
            const minX = this.worldMinX * this.scale;
            const maxX = this.worldMaxX * this.scale;
            // Translate to positive positions with the map center in the center position.
            // This ensures that the map snaps to the correct edge.
            const shift = this.worldSize / 2 - (minX + maxX) / 2;
            x2 = (x + shift + this.worldSize) % this.worldSize - shift;
            if (x2 - w2 < minX)
                x2 = minX + w2;
            if (x2 + w2 > maxX)
                x2 = maxX - w2;
            if (maxX - minX < this.width) {
                s = Math.max(s, this.width / (maxX - minX));
                x2 = (maxX + minX) / 2;
            }
        }
        if (x2 !== x || y2 !== y) {
            // pan the map to fit the range
            this.center = this.unproject(new Point$2(x2, y2));
        }
        if (s) {
            // scale the map to fit the range
            this.zoom += this.scaleZoom(s);
        }
        this._constrainCamera();
        this._unmodified = unmodified;
        this._constraining = false;
    }
    /**
     * Returns the minimum zoom at which `this.width` can fit max longitude range
     * and `this.height` can fit max latitude range.
     *
     * @returns {number} The zoom value.
     */
    _minZoomForBounds() {
        let minZoom = Math.max(0, this.scaleZoom(this.height / (this.worldMaxY - this.worldMinY)));
        if (this.maxBounds) {
            minZoom = Math.max(minZoom, this.scaleZoom(this.width / (this.worldMaxX - this.worldMinX)));
        }
        return minZoom;
    }
    /**
     * Returns the maximum distance of the camera from the center of the bounds, such that
     * `this.width` can fit max longitude range and `this.height` can fit max latitude range.
     * In mercator units.
     *
     * @returns {number} The mercator z coordinate.
     */
    _maxCameraBoundsDistance() {
        return this._mercatorZfromZoom(this._minZoomForBounds());
    }
    _calcMatrices() {
        if (!this.height)
            return;
        const offset = this.centerOffset;
        const isGlobe = this.projection.name === 'globe';
        // Z-axis uses pixel coordinates when globe mode is enabled
        const pixelsPerMeter = this.pixelsPerMeter;
        if (this.projection.name === 'globe') {
            this._mercatorScaleRatio = mercatorZfromAltitude(1, this.center.lat) / mercatorZfromAltitude(1, GLOBE_SCALE_MATCH_LATITUDE);
        }
        const projectionT = getProjectionInterpolationT(this.projection, this.zoom, this.width, this.height, 1024);
        // 'this._pixelsPerMercatorPixel' is the ratio between pixelsPerMeter in the current projection relative to Mercator.
        // This is useful for converting e.g. camera position between pixel spaces as some logic
        // such as raycasting expects the scale to be in mercator pixels
        this._pixelsPerMercatorPixel = this.projection.pixelSpaceConversion(this.center.lat, this.worldSize, projectionT);
        this.cameraToCenterDistance = 0.5 / Math.tan(this._fov * 0.5) * this.height * this._pixelsPerMercatorPixel;
        this._updateCameraState();
        this._farZ = this.projection.farthestPixelDistance(this);
        // The larger the value of nearZ is
        // - the more depth precision is available for features (good)
        // - clipping starts appearing sooner when the camera is close to 3d features (bad)
        //
        // Smaller values worked well for mapbox-gl-js but deckgl was encountering precision issues
        // when rendering it's layers using custom layers. This value was experimentally chosen and
        // seems to solve z-fighting issues in deckgl while not clipping buildings too close to the camera.
        this._nearZ = this.height / 50;
        const zUnit = this.projection.zAxisUnit === 'meters' ? pixelsPerMeter : 1;
        const worldToCamera = this._camera.getWorldToCamera(this.worldSize, zUnit);
        let cameraToClip;
        const cameraToClipPerspective = this._camera.getCameraToClipPerspective(this._fov, this.width / this.height, this._nearZ, this._farZ);
        // Apply offset/padding
        cameraToClipPerspective[8] = -offset.x * 2 / this.width;
        cameraToClipPerspective[9] = offset.y * 2 / this.height;
        if (this.isOrthographic) {
            const cameraToCenterDistance = 0.5 * this.height / Math.tan(this._fov / 2) * 1;
            // Calculate bounds for orthographic view
            let top = cameraToCenterDistance * Math.tan(this._fov * 0.5);
            let right = top * this.aspect;
            let left = -right;
            let bottom = -top;
            // Apply offset/padding
            right -= offset.x;
            left -= offset.x;
            top += offset.y;
            bottom += offset.y;
            cameraToClip = this._camera.getCameraToClipOrthographic(left, right, bottom, top, this._nearZ, this._farZ);
            const mixValue = this.pitch >= OrthographicPitchTranstionValue ? 1 : this.pitch / OrthographicPitchTranstionValue;
            lerpMatrix(cameraToClip, cameraToClip, cameraToClipPerspective, easeIn(mixValue));
        } else {
            cameraToClip = cameraToClipPerspective;
        }
        const worldToClipPerspective = mat4_1.mul([], cameraToClipPerspective, worldToCamera);
        let m = mat4_1.mul([], cameraToClip, worldToCamera);
        if (this.projection.isReprojectedInTileSpace) {
            // Projections undistort as you zoom in (shear, scale, rotate).
            // Apply the undistortion around the center of the map.
            const mc = this.locationCoordinate(this.center);
            const adjustments = mat4_1.identity([]);
            mat4_1.translate(adjustments, adjustments, [
                mc.x * this.worldSize,
                mc.y * this.worldSize,
                0
            ]);
            mat4_1.multiply(adjustments, adjustments, getProjectionAdjustments(this));
            mat4_1.translate(adjustments, adjustments, [
                -mc.x * this.worldSize,
                -mc.y * this.worldSize,
                0
            ]);
            mat4_1.multiply(m, m, adjustments);
            mat4_1.multiply(worldToClipPerspective, worldToClipPerspective, adjustments);
            this.inverseAdjustmentMatrix = getProjectionAdjustmentInverted(this);
        } else {
            this.inverseAdjustmentMatrix = [
                1,
                0,
                0,
                1
            ];
        }
        // The mercatorMatrix can be used to transform points from mercator coordinates
        // ([0, 0] nw, [1, 1] se) to GL coordinates. / zUnit compensates for scaling done in worldToCamera.
        this.mercatorMatrix = mat4_1.scale([], m, [
            this.worldSize,
            this.worldSize,
            this.worldSize / zUnit,
            1
        ]);
        this.projMatrix = m;
        // For tile cover calculation, use inverted of base (non elevated) matrix
        // as tile elevations are in tile coordinates and relative to center elevation.
        this.invProjMatrix = mat4_1.invert(new Float64Array(16), this.projMatrix);
        const clipToCamera = mat4_1.invert([], cameraToClip);
        this.frustumCorners = FrustumCorners.fromInvProjectionMatrix(clipToCamera, this.horizonLineFromTop(), this.height);
        // Create a camera frustum in mercator units
        this.cameraFrustum = Frustum.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, 0, !isGlobe);
        const view = new Float32Array(16);
        mat4_1.identity(view);
        mat4_1.scale(view, view, [
            1,
            -1,
            1
        ]);
        mat4_1.rotateX(view, view, this._pitch);
        mat4_1.rotateZ(view, view, this.angle);
        const projection = mat4_1.perspective(new Float32Array(16), this._fov, this.width / this.height, this._nearZ, this._farZ);
        this.starsProjMatrix = mat4_1.clone(projection);
        // The distance in pixels the skybox needs to be shifted down by to meet the shifted horizon.
        const skyboxHorizonShift = (Math.PI / 2 - this._pitch) * (this.height / this._fov) * this._horizonShift;
        // Apply center of perspective offset to skybox projection
        projection[8] = -offset.x * 2 / this.width;
        projection[9] = (offset.y + skyboxHorizonShift) * 2 / this.height;
        this.skyboxMatrix = mat4_1.multiply(view, projection, view);
        // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles.
        // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional
        // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension
        // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle
        // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that
        // it is always <= 0.5 pixels.
        const point = this.point;
        const x = point.x, y = point.y;
        const xShift = this.width % 2 / 2, yShift = this.height % 2 / 2, angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;
        const alignedM = new Float64Array(m);
        mat4_1.translate(alignedM, alignedM, [
            dx > 0.5 ? dx - 1 : dx,
            dy > 0.5 ? dy - 1 : dy,
            0
        ]);
        this.alignedProjMatrix = alignedM;
        m = mat4_1.create();
        mat4_1.scale(m, m, [
            this.width / 2,
            -this.height / 2,
            1
        ]);
        mat4_1.translate(m, m, [
            1,
            -1,
            0
        ]);
        this.labelPlaneMatrix = m;
        m = mat4_1.create();
        mat4_1.scale(m, m, [
            1,
            -1,
            1
        ]);
        mat4_1.translate(m, m, [
            -1,
            -1,
            0
        ]);
        mat4_1.scale(m, m, [
            2 / this.width,
            2 / this.height,
            1
        ]);
        this.glCoordMatrix = m;
        // matrix for conversion from location to screen coordinates
        this.pixelMatrix = mat4_1.multiply(new Float64Array(16), this.labelPlaneMatrix, worldToClipPerspective);
        this._calcFogMatrices();
        this._distanceTileDataCache = {};
        // inverse matrix for conversion from screen coordinates to location
        m = mat4_1.invert(new Float64Array(16), this.pixelMatrix);
        if (!m)
            throw new Error('failed to invert matrix');
        this.pixelMatrixInverse = m;
        if (this.projection.name === 'globe' || this.mercatorFromTransition) {
            this.globeMatrix = calculateGlobeMatrix(this);
            const globeCenter = [
                this.globeMatrix[12],
                this.globeMatrix[13],
                this.globeMatrix[14]
            ];
            this.globeCenterInViewSpace = vec3_1.transformMat4(globeCenter, globeCenter, worldToCamera);
            this.globeRadius = this.worldSize / 2 / Math.PI - 1;
        } else {
            this.globeMatrix = m;
        }
        this._projMatrixCache = {};
        this._alignedProjMatrixCache = {};
        this._pixelsToTileUnitsCache = {};
    }
    _calcFogMatrices() {
        this._fogTileMatrixCache = {};
        const cameraWorldSizeForFog = this.cameraWorldSizeForFog;
        const cameraPixelsPerMeter = this.cameraPixelsPerMeter;
        const cameraPos = this._camera.position;
        // The mercator fog matrix encodes transformation necessary to transform a position to camera fog space (in meters):
        // translates p to camera origin and transforms it from pixels to meters. The windowScaleFactor is used to have a
        // consistent transformation across different window sizes.
        // - p = p - cameraOrigin
        // - p.xy = p.xy * cameraWorldSizeForFog * windowScaleFactor
        // - p.z  = p.z  * cameraPixelsPerMeter * windowScaleFactor
        const windowScaleFactor = 1 / this.height / this._pixelsPerMercatorPixel;
        const metersToPixel = [
            cameraWorldSizeForFog,
            cameraWorldSizeForFog,
            cameraPixelsPerMeter
        ];
        vec3_1.scale(metersToPixel, metersToPixel, windowScaleFactor);
        vec3_1.scale(cameraPos, cameraPos, -1);
        vec3_1.multiply(cameraPos, cameraPos, metersToPixel);
        const m = mat4_1.create();
        mat4_1.translate(m, m, cameraPos);
        mat4_1.scale(m, m, metersToPixel);
        this.mercatorFogMatrix = m;
        // The worldToFogMatrix can be used for conversion from world coordinates to relative camera position in
        // units of fractions of the map height. Later composed with tile position to construct the fog tile matrix.
        this.worldToFogMatrix = this._camera.getWorldToCameraPosition(cameraWorldSizeForFog, cameraPixelsPerMeter, windowScaleFactor);
    }
    _computeCameraPosition(targetPixelsPerMeter) {
        targetPixelsPerMeter = targetPixelsPerMeter || this.pixelsPerMeter;
        const pixelSpaceConversion = targetPixelsPerMeter / this.pixelsPerMeter;
        const dir = this._camera.forward();
        const center = this.point;
        // Compute camera position using the following vector math: camera.position = map.center - camera.forward * cameraToCenterDist
        // Camera distance to the center can be found in mercator units by subtracting the center elevation from
        // camera's zenith position (which can be deduced from the zoom level)
        const zoom = this._seaLevelZoom ? this._seaLevelZoom : this._zoom;
        const altitude = this._mercatorZfromZoom(zoom) * pixelSpaceConversion;
        const distance = altitude - targetPixelsPerMeter / this.worldSize * this._centerAltitude;
        return [
            center.x / this.worldSize - dir[0] * distance,
            center.y / this.worldSize - dir[1] * distance,
            targetPixelsPerMeter / this.worldSize * this._centerAltitude - dir[2] * distance
        ];
    }
    _updateCameraState() {
        if (!this.height)
            return;
        // Set camera orientation and move it to a proper distance from the map
        this._camera.setPitchBearing(this._pitch, this.angle);
        this._camera.position = this._computeCameraPosition();
    }
    /**
     * Apply a 3d translation to the camera position, but clamping it so that
     * it respects the maximum longitude and latitude range set.
     *
     * @param {vec3} translation The translation vector.
     */
    _translateCameraConstrained(translation) {
        const maxDistance = this._maxCameraBoundsDistance();
        // Define a ceiling in mercator Z
        const maxZ = maxDistance * Math.cos(this._pitch);
        const z = this._camera.position[2];
        const deltaZ = translation[2];
        let t = 1;
        if (this.projection.wrap)
            this.center = this.center.wrap();
        // we only need to clamp if the camera is moving upwards
        if (deltaZ > 0) {
            t = Math.min((maxZ - z) / deltaZ, 1);
        }
        this._camera.position = vec3_1.scaleAndAdd([], this._camera.position, translation, t);
        this._updateStateFromCamera();
    }
    _updateStateFromCamera() {
        const position = this._camera.position;
        const dir = this._camera.forward();
        const {pitch, bearing} = this._camera.getPitchBearing();
        // Compute zoom from the distance between camera and terrain
        const centerAltitude = mercatorZfromAltitude(this._centerAltitude, this.center.lat) * this._pixelsPerMercatorPixel;
        const minHeight = this._mercatorZfromZoom(this._maxZoom) * Math.cos(degToRad(this._maxPitch));
        const height = Math.max((position[2] - centerAltitude) / Math.cos(pitch), minHeight);
        const zoom = this._zoomFromMercatorZ(height);
        // Cast a ray towards the ground to find the center point
        vec3_1.scaleAndAdd(position, position, dir, height);
        this._pitch = clamp(pitch, degToRad(this.minPitch), degToRad(this.maxPitch));
        this.angle = wrap$1(bearing, -Math.PI, Math.PI);
        this._setZoom(clamp(zoom, this._minZoom, this._maxZoom));
        this._updateSeaLevelZoom();
        this._center = this.coordinateLocation(new MercatorCoordinate(position[0], position[1], position[2]));
        this._unmodified = false;
        this._constrain();
        this._calcMatrices();
    }
    _worldSizeFromZoom(zoom) {
        return Math.pow(2, zoom) * this.tileSize;
    }
    _mercatorZfromZoom(zoom) {
        return this.cameraToCenterDistance / this._worldSizeFromZoom(zoom);
    }
    _minimumHeightOverTerrain() {
        // Determine minimum height for the camera over the terrain related to current zoom.
        // Values above 4 allow camera closer to e.g. top of the hill, exposing
        // drape raster overscale artifacts or cut terrain (see under it) as it gets clipped on
        // near plane. Returned value is in mercator coordinates.
        const MAX_DRAPE_OVERZOOM = 4;
        const zoom = Math.min((this._seaLevelZoom != null ? this._seaLevelZoom : this._zoom) + MAX_DRAPE_OVERZOOM, this._maxZoom);
        return this._mercatorZfromZoom(zoom);
    }
    _zoomFromMercatorZ(z) {
        return this.scaleZoom(this.cameraToCenterDistance / (z * this.tileSize));
    }
    // This function is helpful to approximate true zoom given a mercator height with varying ppm.
    // With Globe, since we use a fixed reference latitude at lower zoom levels and transition between this
    // latitude and the center's latitude as you zoom in, camera to center distance varies dynamically.
    // As the cameraToCenterDistance is a function of zoom, we need to approximate the true zoom
    // given a mercator meter value in order to eliminate the zoom/cameraToCenterDistance dependency.
    zoomFromMercatorZAdjusted(mercatorZ) {
        let zoomLow = 0;
        let zoomHigh = GLOBE_ZOOM_THRESHOLD_MAX;
        let zoom = 0;
        let minZoomDiff = Infinity;
        const epsilon = 0.000001;
        while (zoomHigh - zoomLow > epsilon && zoomHigh > zoomLow) {
            const zoomMid = zoomLow + (zoomHigh - zoomLow) * 0.5;
            const worldSize = this.tileSize * Math.pow(2, zoomMid);
            const d = this.getCameraToCenterDistance(this.projection, zoomMid, worldSize);
            const newZoom = this.scaleZoom(d / (mercatorZ * this.tileSize));
            const diff = Math.abs(zoomMid - newZoom);
            if (diff < minZoomDiff) {
                minZoomDiff = diff;
                zoom = zoomMid;
            }
            if (zoomMid < newZoom) {
                zoomLow = zoomMid;
            } else {
                zoomHigh = zoomMid;
            }
        }
        return zoom;
    }
    _terrainEnabled() {
        if (!this._elevation)
            return false;
        if (!this.projection.supportsTerrain) {
            warnOnce('Terrain is not yet supported with alternate projections. Use mercator or globe to enable terrain.');
            return false;
        }
        return true;
    }
    // Check if any of the four corners are off the edge of the rendered map
    // This function will return `false` for all non-mercator projection
    anyCornerOffEdge(p0, p1) {
        const minX = Math.min(p0.x, p1.x);
        const maxX = Math.max(p0.x, p1.x);
        const minY = Math.min(p0.y, p1.y);
        const maxY = Math.max(p0.y, p1.y);
        const horizon = this.horizonLineFromTop(false);
        if (minY < horizon)
            return true;
        if (this.projection.name !== 'mercator') {
            return false;
        }
        const min = new Point$2(minX, minY);
        const max = new Point$2(maxX, maxY);
        const corners = [
            min,
            max,
            new Point$2(minX, maxY),
            new Point$2(maxX, minY)
        ];
        const minWX = this.renderWorldCopies ? -NUM_WORLD_COPIES : 0;
        const maxWX = this.renderWorldCopies ? 1 + NUM_WORLD_COPIES : 1;
        const minWY = 0;
        const maxWY = 1;
        for (const corner of corners) {
            const rayIntersection = this.pointRayIntersection(corner);
            // Point is above the horizon
            if (rayIntersection.t < 0) {
                return true;
            }
            // Point is off the bondaries of the map
            const coordinate = this.rayIntersectionCoordinate(rayIntersection);
            if (coordinate.x < minWX || coordinate.y < minWY || coordinate.x > maxWX || coordinate.y > maxWY) {
                return true;
            }
        }
        return false;
    }
    // Checks the four corners of the frustum to see if they lie in the map's quad.
    //
    isHorizonVisible() {
        // we consider the horizon as visible if the angle between
        // a the top plane of the frustum and the map plane is smaller than this threshold.
        const horizonAngleEpsilon = 2;
        if (this.pitch + radToDeg(this.fovAboveCenter) > 90 - horizonAngleEpsilon) {
            return true;
        }
        return this.anyCornerOffEdge(new Point$2(0, 0), new Point$2(this.width, this.height));
    }
    /**
     * Converts a zoom delta value into a physical distance travelled in web mercator coordinates.
     *
     * @param {vec3} center Destination mercator point of the movement.
     * @param {number} zoomDelta Change in the zoom value.
     * @returns {number} The distance in mercator coordinates.
     */
    zoomDeltaToMovement(center, zoomDelta) {
        const distance = vec3_1.length(vec3_1.sub([], this._camera.position, center));
        const relativeZoom = this._zoomFromMercatorZ(distance) + zoomDelta;
        return distance - this._mercatorZfromZoom(relativeZoom);
    }
    /*
     * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation`
     * as the name for the location under the camera and on the surface of the earth (lng, lat, 0).
     * `cameraPoint` is the projected position of the `cameraLocation`.
     *
     * This point is useful to us because only fill-extrusions that are between `cameraPoint` and
     * the query point on the surface of the earth can extend and intersect the query.
     *
     * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because
     * the camera is right above the center of the map.
     */
    getCameraPoint() {
        if (this.projection.name === 'globe') {
            // Find precise location of the projected camera position on the curved surface
            const center = [
                this.globeMatrix[12],
                this.globeMatrix[13],
                this.globeMatrix[14]
            ];
            const pos = projectClamped(center, this.pixelMatrix);
            return new Point$2(pos[0], pos[1]);
        } else {
            const pitch = this._pitch;
            const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);
            return this.centerPoint.add(new Point$2(0, yOffset));
        }
    }
    getCameraToCenterDistance(projection, zoom = this.zoom, worldSize = this.worldSize) {
        const t = getProjectionInterpolationT(projection, zoom, this.width, this.height, 1024);
        const projectionScaler = projection.pixelSpaceConversion(this.center.lat, worldSize, t);
        let distance = 0.5 / Math.tan(this._fov * 0.5) * this.height * projectionScaler;
        // In case we have orthographic transition we need to interpolate the distance value in the range [1, distance]
        // to calculate correct perspective ratio values for symbols
        if (this.isOrthographic) {
            const mixValue = this.pitch >= OrthographicPitchTranstionValue ? 1 : this.pitch / OrthographicPitchTranstionValue;
            distance = lerp(1, distance, easeIn(mixValue));
        }
        return distance;
    }
    getWorldToCameraMatrix() {
        const zUnit = this.projection.zAxisUnit === 'meters' ? this.pixelsPerMeter : 1;
        const worldToCamera = this._camera.getWorldToCamera(this.worldSize, zUnit);
        if (this.projection.name === 'globe') {
            mat4_1.multiply(worldToCamera, worldToCamera, this.globeMatrix);
        }
        return worldToCamera;
    }
    getFrustum(zoom) {
        const zInMeters = this.projection.zAxisUnit === 'meters';
        return Frustum.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, zoom, zInMeters);
    }
}

//      
function rotationScaleYZFlipMatrix(out, rotation, scale) {
    mat4_1.identity(out);
    mat4_1.rotateZ(out, out, degToRad(rotation[2]));
    mat4_1.rotateX(out, out, degToRad(rotation[0]));
    mat4_1.rotateY(out, out, degToRad(rotation[1]));
    mat4_1.scale(out, out, scale);
    // gltf spec uses right handed coordinate space where +y is up. Coordinate space transformation matrix
    // has to be created for the initial transform to our left handed coordinate space
    const coordSpaceTransform = [
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1
    ];
    mat4_1.multiply(out, out, coordSpaceTransform);
}
// corners are in world coordinates.
function getBoxBottomFace(corners, meterToMercator) {
    const zUp = [
        0,
        0,
        1
    ];
    const boxFaces = [
        {
            corners: [
                0,
                1,
                3,
                2
            ],
            dotProductWithUp: 0
        },
        {
            corners: [
                1,
                5,
                2,
                6
            ],
            dotProductWithUp: 0
        },
        {
            corners: [
                0,
                4,
                1,
                5
            ],
            dotProductWithUp: 0
        },
        {
            corners: [
                2,
                6,
                3,
                7
            ],
            dotProductWithUp: 0
        },
        {
            corners: [
                4,
                7,
                5,
                6
            ],
            dotProductWithUp: 0
        },
        {
            corners: [
                0,
                3,
                4,
                7
            ],
            dotProductWithUp: 0
        }
    ];
    for (const face of boxFaces) {
        const p0 = corners[face.corners[0]];
        const p1 = corners[face.corners[1]];
        const p2 = corners[face.corners[2]];
        const a = [
            p1[0] - p0[0],
            p1[1] - p0[1],
            meterToMercator * (p1[2] - p0[2])
        ];
        const b = [
            p2[0] - p0[0],
            p2[1] - p0[1],
            meterToMercator * (p2[2] - p0[2])
        ];
        const normal = vec3_1.cross(a, a, b);
        vec3_1.normalize(normal, normal);
        face.dotProductWithUp = vec3_1.dot(normal, zUp);
    }
    boxFaces.sort((a, b) => {
        return a.dotProductWithUp - b.dotProductWithUp;
    });
    return boxFaces[0].corners;
}
function rotationFor3Points(out, p0, p1, p2, h0, h1, h2, meterToMercator) {
    const p0p1 = [
        p1[0] - p0[0],
        p1[1] - p0[1],
        0
    ];
    const p0p2 = [
        p2[0] - p0[0],
        p2[1] - p0[1],
        0
    ];
    // If model scale is zero, all bounding box points are identical and no rotation can be calculated
    if (vec3_1.length(p0p1) < 1e-12 || vec3_1.length(p0p2) < 1e-12) {
        return quat_1.identity(out);
    }
    const from = vec3_1.cross([], p0p1, p0p2);
    vec3_1.normalize(from, from);
    vec3_1.subtract(p0p2, p2, p0);
    p0p1[2] = (h1 - h0) * meterToMercator;
    p0p2[2] = (h2 - h0) * meterToMercator;
    const to = p0p1;
    vec3_1.cross(to, p0p1, p0p2);
    vec3_1.normalize(to, to);
    return quat_1.rotationTo(out, from, to);
}
function coordinateFrameAtEcef(ecef) {
    const zAxis = [
        ecef[0],
        ecef[1],
        ecef[2]
    ];
    let yAxis = [
        0,
        1,
        0
    ];
    const xAxis = vec3_1.cross([], yAxis, zAxis);
    vec3_1.cross(yAxis, zAxis, xAxis);
    if (vec3_1.squaredLength(yAxis) === 0) {
        // Coordinate space is ambiguous if the model is placed directly at north or south pole
        yAxis = [
            0,
            1,
            0
        ];
        vec3_1.cross(xAxis, zAxis, yAxis);
    }
    vec3_1.normalize(xAxis, xAxis);
    vec3_1.normalize(yAxis, yAxis);
    vec3_1.normalize(zAxis, zAxis);
    return [
        xAxis[0],
        xAxis[1],
        xAxis[2],
        0,
        yAxis[0],
        yAxis[1],
        yAxis[2],
        0,
        zAxis[0],
        zAxis[1],
        zAxis[2],
        0,
        ecef[0],
        ecef[1],
        ecef[2],
        1
    ];
}
function convertModelMatrix(matrix, transform, scaleWithViewport) {
    // The provided transformation matrix is expected to define model position and orientation in pixel units
    // with the exception of z-axis being in meters. Converting this into globe-aware matrix requires following steps:
    //  1. Take the (pixel) position from the last column of the matrix and convert it to lat&lng and then to
    //     ecef-presentation.
    //  2. Scale the model from (px, px, m) units to ecef-units and apply pixels-per-meter correction. Also
    //     remove translation component from the matrix as it represents position in Mercator coordinates.
    //  3. Compute coordinate frame at the desired lat&lng position by aligning coordinate axes x,y & z with
    //     the tangent plane at the said location.
    //  4. Prepend the original matrix with the new coordinate frame matrix and apply translation in ecef-units.
    //     After this operation the matrix presents correct position in ecef-space
    //  5. Multiply the matrix with globe matrix for getting the final pixel space position
    const worldSize = transform.worldSize;
    const position = [
        matrix[12],
        matrix[13],
        matrix[14]
    ];
    const lat = latFromMercatorY(position[1] / worldSize);
    const lng = lngFromMercatorX(position[0] / worldSize);
    // Construct a matrix for scaling the original one to ecef space and removing the translation in mercator space
    const mercToEcef = mat4_1.identity([]);
    const sourcePixelsPerMeter = mercatorZfromAltitude(1, lat) * worldSize;
    const pixelsPerMeterConversion = mercatorZfromAltitude(1, 0) * worldSize * getMetersPerPixelAtLatitude(lat, transform.zoom);
    const pixelsToEcef = 1 / globeECEFUnitsToPixelScale(worldSize);
    let scale = pixelsPerMeterConversion * pixelsToEcef;
    if (scaleWithViewport) {
        // Keep the size relative to viewport
        const t = getProjectionInterpolationT(transform.projection, transform.zoom, transform.width, transform.height, 1024);
        const projectionScaler = transform.projection.pixelSpaceConversion(transform.center.lat, worldSize, t);
        scale = pixelsToEcef * projectionScaler;
    }
    // Construct coordinate space matrix at the provided location in ecef space.
    const ecefCoord = latLngToECEF(lat, lng);
    // add altitude
    vec3_1.add(ecefCoord, ecefCoord, vec3_1.scale([], vec3_1.normalize([], ecefCoord), sourcePixelsPerMeter * scale * position[2]));
    const ecefFrame = coordinateFrameAtEcef(ecefCoord);
    mat4_1.scale(mercToEcef, mercToEcef, [
        scale,
        scale,
        scale * sourcePixelsPerMeter
    ]);
    mat4_1.translate(mercToEcef, mercToEcef, [
        -position[0],
        -position[1],
        -position[2]
    ]);
    const result = mat4_1.multiply([], transform.globeMatrix, ecefFrame);
    mat4_1.multiply(result, result, mercToEcef);
    mat4_1.multiply(result, result, matrix);
    return result;
}
// Computes a matrix for representing the provided transformation matrix (in mercator projection) in globe
function mercatorToGlobeMatrix(matrix, transform) {
    const worldSize = transform.worldSize;
    const pixelsPerMeterConversion = mercatorZfromAltitude(1, 0) * worldSize * getMetersPerPixelAtLatitude(transform.center.lat, transform.zoom);
    const pixelsToEcef = pixelsPerMeterConversion / globeECEFUnitsToPixelScale(worldSize);
    const pixelsPerMeter = mercatorZfromAltitude(1, transform.center.lat) * worldSize;
    const m = mat4_1.identity([]);
    mat4_1.rotateY(m, m, degToRad(transform.center.lng));
    mat4_1.rotateX(m, m, degToRad(transform.center.lat));
    mat4_1.translate(m, m, [
        0,
        0,
        GLOBE_RADIUS
    ]);
    mat4_1.scale(m, m, [
        pixelsToEcef,
        pixelsToEcef,
        pixelsToEcef * pixelsPerMeter
    ]);
    mat4_1.translate(m, m, [
        transform.point.x - 0.5 * worldSize,
        transform.point.y - 0.5 * worldSize,
        0
    ]);
    mat4_1.multiply(m, m, matrix);
    return mat4_1.multiply(m, transform.globeMatrix, m);
}
function affineMatrixLerp(a, b, t) {
    // Interpolate each of the coordinate axes separately while also preserving their length
    const lerpAxis = (ax, bx, t) => {
        const axLen = vec3_1.length(ax);
        const bxLen = vec3_1.length(bx);
        const c = interpolateVec3(ax, bx, t);
        return vec3_1.scale(c, c, 1 / vec3_1.length(c) * number(axLen, bxLen, t));
    };
    const xAxis = lerpAxis([
        a[0],
        a[1],
        a[2]
    ], [
        b[0],
        b[1],
        b[2]
    ], t);
    const yAxis = lerpAxis([
        a[4],
        a[5],
        a[6]
    ], [
        b[4],
        b[5],
        b[6]
    ], t);
    const zAxis = lerpAxis([
        a[8],
        a[9],
        a[10]
    ], [
        b[8],
        b[9],
        b[10]
    ], t);
    const pos = interpolateVec3([
        a[12],
        a[13],
        a[14]
    ], [
        b[12],
        b[13],
        b[14]
    ], t);
    return [
        xAxis[0],
        xAxis[1],
        xAxis[2],
        0,
        yAxis[0],
        yAxis[1],
        yAxis[2],
        0,
        zAxis[0],
        zAxis[1],
        zAxis[2],
        0,
        pos[0],
        pos[1],
        pos[2],
        1
    ];
}
function convertModelMatrixForGlobe(matrix, transform, scaleWithViewport = false) {
    const t = globeToMercatorTransition(transform.zoom);
    const modelMatrix = convertModelMatrix(matrix, transform, scaleWithViewport);
    if (t > 0) {
        const mercatorMatrix = mercatorToGlobeMatrix(matrix, transform);
        return affineMatrixLerp(modelMatrix, mercatorMatrix, t);
    }
    return modelMatrix;
}

//      
const HEIGHTMAP_DIM = 64;
// A rectangle with 5 DoF, no rolling
const ModelTraits = {
    CoordinateSpaceTile: 1,
    CoordinateSpaceYUp: 2,
    // not used yet.
    HasMapboxMeshFeatures: 1 << 2
};
const DefaultModelScale = [
    1,
    1,
    1
];
class Model {
    constructor(id, position, orientation, nodes) {
        this.id = id;
        this.position = position != null ? new LngLat$1(position[0], position[1]) : new LngLat$1(0, 0);
        this.orientation = orientation != null ? orientation : [
            0,
            0,
            0
        ];
        this.nodes = nodes;
        this.uploaded = false;
        this.aabb = new Aabb([
            Infinity,
            Infinity,
            Infinity
        ], [
            -Infinity,
            -Infinity,
            -Infinity
        ]);
        this.matrix = [];
    }
    _applyTransformations(node, parentMatrix) {
        // update local matrix
        mat4_1.multiply(node.matrix, parentMatrix, node.matrix);
        // apply local transform to bounding volume
        if (node.meshes) {
            for (const mesh of node.meshes) {
                const enclosingBounds = Aabb.applyTransform(mesh.aabb, node.matrix);
                this.aabb.encapsulate(enclosingBounds);
            }
        }
        if (node.children) {
            for (const child of node.children) {
                this._applyTransformations(child, node.matrix);
            }
        }
    }
    computeBoundsAndApplyParent() {
        const localMatrix = mat4_1.identity([]);
        for (const node of this.nodes) {
            this._applyTransformations(node, localMatrix);
        }
    }
    _positionModelOnTerrain(transform, rotationOnTerrain) {
        const elevation = transform.elevation;
        if (!elevation) {
            return 0;
        }
        const corners = Aabb.projectAabbCorners(this.aabb, this.matrix);
        const meterToMercator = mercatorZfromAltitude(1, this.position.lat) * transform.worldSize;
        const bottomFace = getBoxBottomFace(corners, meterToMercator);
        const b0 = corners[bottomFace[0]];
        const b1 = corners[bottomFace[1]];
        const b2 = corners[bottomFace[2]];
        const b3 = corners[bottomFace[3]];
        const e0 = elevation.getAtPointOrZero(new MercatorCoordinate(b0[0] / transform.worldSize, b0[1] / transform.worldSize), 0);
        const e1 = elevation.getAtPointOrZero(new MercatorCoordinate(b1[0] / transform.worldSize, b1[1] / transform.worldSize), 0);
        const e2 = elevation.getAtPointOrZero(new MercatorCoordinate(b2[0] / transform.worldSize, b2[1] / transform.worldSize), 0);
        const e3 = elevation.getAtPointOrZero(new MercatorCoordinate(b3[0] / transform.worldSize, b3[1] / transform.worldSize), 0);
        const d03 = (e0 + e3) / 2;
        const d12 = (e1 + e2) / 2;
        if (d03 > d12) {
            if (e1 < e2) {
                rotationFor3Points(rotationOnTerrain, b1, b3, b0, e1, e3, e0, meterToMercator);
            } else {
                rotationFor3Points(rotationOnTerrain, b2, b0, b3, e2, e0, e3, meterToMercator);
            }
        } else {
            if (e0 < e3) {
                rotationFor3Points(rotationOnTerrain, b0, b1, b2, e0, e1, e2, meterToMercator);
            } else {
                rotationFor3Points(rotationOnTerrain, b3, b2, b1, e3, e2, e1, meterToMercator);
            }
        }
        return Math.max(d03, d12);
    }
    computeModelMatrix(painter, rotation, scale, translation, applyElevation, followTerrainSlope, viewportScale = false) {
        const state = painter.transform;
        const zoom = state.zoom;
        const projectedPoint = state.project(this.position);
        const modelMetersPerPixel = getMetersPerPixelAtLatitude(this.position.lat, zoom);
        const modelPixelsPerMeter = 1 / modelMetersPerPixel;
        mat4_1.identity(this.matrix);
        const offset = [
            projectedPoint.x + translation[0] * modelPixelsPerMeter,
            projectedPoint.y + translation[1] * modelPixelsPerMeter,
            translation[2]
        ];
        mat4_1.translate(this.matrix, this.matrix, offset);
        let scaleXY = 1;
        let scaleZ = 1;
        const worldSize = state.worldSize;
        if (viewportScale) {
            if (state.projection.name === 'mercator') {
                let elevation = 0;
                if (state.elevation) {
                    elevation = state.elevation.getAtPointOrZero(new MercatorCoordinate(projectedPoint.x / worldSize, projectedPoint.y / worldSize), 0);
                }
                const mercProjPos = vec4_1.transformMat4([], [
                    projectedPoint.x,
                    projectedPoint.y,
                    elevation,
                    1
                ], state.projMatrix);
                const mercProjectionScale = mercProjPos[3] / state.cameraToCenterDistance;
                const viewMetersPerPixel = getMetersPerPixelAtLatitude(state.center.lat, zoom);
                scaleXY = mercProjectionScale;
                scaleZ = mercProjectionScale * viewMetersPerPixel;
            } else if (state.projection.name === 'globe') {
                const globeMatrix = convertModelMatrixForGlobe(this.matrix, state);
                const worldViewProjection = mat4_1.multiply([], state.projMatrix, globeMatrix);
                const globeProjPos = [
                    0,
                    0,
                    0,
                    1
                ];
                vec4_1.transformMat4(globeProjPos, globeProjPos, worldViewProjection);
                const globeProjectionScale = globeProjPos[3] / state.cameraToCenterDistance;
                const transition = globeToMercatorTransition(zoom);
                const modelPixelConv = state.projection.pixelsPerMeter(this.position.lat, worldSize) * getMetersPerPixelAtLatitude(this.position.lat, zoom);
                const viewPixelConv = state.projection.pixelsPerMeter(state.center.lat, worldSize) * getMetersPerPixelAtLatitude(state.center.lat, zoom);
                const viewLatScale = getLatitudeScale(state.center.lat);
                // Compensate XY size difference from model latitude, taking into account globe-mercator transition
                scaleXY = globeProjectionScale / number(modelPixelConv, viewLatScale, transition);
                // Compensate height difference from model latitude.
                // No interpolation, because the Z axis is fixed in globe projection.
                scaleZ = globeProjectionScale * modelMetersPerPixel / modelPixelConv;
                // In globe projection, zoom and scale do not match anymore.
                // Use pixelScaleConversion to scale to correct worldSize.
                scaleXY *= viewPixelConv;
                scaleZ *= viewPixelConv;
            }
        } else {
            scaleXY = modelPixelsPerMeter;
        }
        mat4_1.scale(this.matrix, this.matrix, [
            scaleXY,
            scaleXY,
            scaleZ
        ]);
        // When applying physics (rotation) we need to insert rotation matrix
        // between model rotation and transforms above. Keep the intermediate results.
        const modelMatrixBeforeRotationScaleYZFlip = [...this.matrix];
        const orientation = this.orientation;
        const rotationScaleYZFlip = [];
        rotationScaleYZFlipMatrix(rotationScaleYZFlip, [
            orientation[0] + rotation[0],
            orientation[1] + rotation[1],
            orientation[2] + rotation[2]
        ], scale);
        mat4_1.multiply(this.matrix, modelMatrixBeforeRotationScaleYZFlip, rotationScaleYZFlip);
        if (applyElevation && state.elevation) {
            let elevate = 0;
            const rotateOnTerrain = [];
            if (followTerrainSlope && state.elevation) {
                elevate = this._positionModelOnTerrain(state, rotateOnTerrain);
                const rotationOnTerrain = mat4_1.fromQuat([], rotateOnTerrain);
                const appendRotation = mat4_1.multiply([], rotationOnTerrain, rotationScaleYZFlip);
                mat4_1.multiply(this.matrix, modelMatrixBeforeRotationScaleYZFlip, appendRotation);
            } else {
                elevate = state.elevation.getAtPointOrZero(new MercatorCoordinate(projectedPoint.x / worldSize, projectedPoint.y / worldSize), 0);
            }
            if (elevate !== 0) {
                this.matrix[14] += elevate;
            }
        }
    }
    upload(context) {
        if (this.uploaded)
            return;
        for (const node of this.nodes) {
            uploadNode(node, context);
        }
        // Now destroy all buffers
        for (const node of this.nodes) {
            destroyNodeArrays(node);
        }
        this.uploaded = true;
    }
    destroy() {
        for (const node of this.nodes) {
            destroyBuffers(node);
        }
    }
}
function uploadTexture(texture, context, useSingleChannelTexture = false) {
    // $FlowFixMe[prop-missing]
    const textureFormat = useSingleChannelTexture ? context.gl.R8 : context.gl.RGBA;
    if (!texture.uploaded) {
        const useMipmap = texture.sampler.minFilter >= context.gl.NEAREST_MIPMAP_NEAREST;
        texture.gfxTexture = new Texture(context, texture.image, textureFormat, { useMipmap });
        texture.uploaded = true;
        texture.image = null;
    }
}
function uploadMesh(mesh, context, useSingleChannelOcclusionTexture) {
    // Buffers
    // Note: array buffers could reused for different nodes so destroy them in a later pass
    mesh.indexBuffer = context.createIndexBuffer(mesh.indexArray, false, true);
    mesh.vertexBuffer = context.createVertexBuffer(mesh.vertexArray, modelAttributes.members, false, true);
    if (mesh.normalArray) {
        mesh.normalBuffer = context.createVertexBuffer(mesh.normalArray, normalAttributes.members, false, true);
    }
    if (mesh.texcoordArray) {
        mesh.texcoordBuffer = context.createVertexBuffer(mesh.texcoordArray, texcoordAttributes.members, false, true);
    }
    if (mesh.colorArray) {
        const colorAttributes = mesh.colorArray.bytesPerElement === 12 ? color3fAttributes : color4fAttributes;
        mesh.colorBuffer = context.createVertexBuffer(mesh.colorArray, colorAttributes.members, false, true);
    }
    if (mesh.featureArray) {
        mesh.pbrBuffer = context.createVertexBuffer(mesh.featureArray, featureAttributes.members, true);
    }
    mesh.segments = SegmentVector.simpleSegment(0, 0, mesh.vertexArray.length, mesh.indexArray.length);
    // Textures
    const material = mesh.material;
    if (material.pbrMetallicRoughness.baseColorTexture) {
        uploadTexture(material.pbrMetallicRoughness.baseColorTexture, context);
    }
    if (material.pbrMetallicRoughness.metallicRoughnessTexture) {
        uploadTexture(material.pbrMetallicRoughness.metallicRoughnessTexture, context);
    }
    if (material.normalTexture) {
        uploadTexture(material.normalTexture, context);
    }
    if (material.occlusionTexture) {
        uploadTexture(material.occlusionTexture, context, useSingleChannelOcclusionTexture);
    }
    if (material.emissionTexture) {
        uploadTexture(material.emissionTexture, context);
    }
}
function uploadNode(node, context, useSingleChannelOcclusionTexture) {
    if (node.meshes) {
        for (const mesh of node.meshes) {
            uploadMesh(mesh, context, useSingleChannelOcclusionTexture);
        }
    }
    if (node.children) {
        for (const child of node.children) {
            uploadNode(child, context, useSingleChannelOcclusionTexture);
        }
    }
}
function destroyNodeArrays(node) {
    if (node.meshes) {
        for (const mesh of node.meshes) {
            mesh.indexArray.destroy();
            mesh.vertexArray.destroy();
            if (mesh.colorArray)
                mesh.colorArray.destroy();
            if (mesh.normalArray)
                mesh.normalArray.destroy();
            if (mesh.texcoordArray)
                mesh.texcoordArray.destroy();
            if (mesh.featureArray) {
                mesh.featureArray.destroy();
            }
        }
    }
    if (node.children) {
        for (const child of node.children) {
            destroyNodeArrays(child);
        }
    }
}
function destroyTextures(material) {
    if (material.pbrMetallicRoughness.baseColorTexture && material.pbrMetallicRoughness.baseColorTexture.gfxTexture) {
        material.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy();
    }
    if (material.pbrMetallicRoughness.metallicRoughnessTexture && material.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture) {
        material.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy();
    }
    if (material.normalTexture && material.normalTexture.gfxTexture) {
        material.normalTexture.gfxTexture.destroy();
    }
    if (material.emissionTexture && material.emissionTexture.gfxTexture) {
        material.emissionTexture.gfxTexture.destroy();
    }
    if (material.occlusionTexture && material.occlusionTexture.gfxTexture) {
        material.occlusionTexture.gfxTexture.destroy();
    }
}
function destroyBuffers(node) {
    if (node.meshes) {
        for (const mesh of node.meshes) {
            if (!mesh.vertexBuffer)
                continue;
            mesh.vertexBuffer.destroy();
            mesh.indexBuffer.destroy();
            if (mesh.normalBuffer) {
                mesh.normalBuffer.destroy();
            }
            if (mesh.texcoordBuffer) {
                mesh.texcoordBuffer.destroy();
            }
            if (mesh.colorBuffer) {
                mesh.colorBuffer.destroy();
            }
            if (mesh.pbrBuffer) {
                mesh.pbrBuffer.destroy();
            }
            mesh.segments.destroy();
            if (mesh.material) {
                destroyTextures(mesh.material);
            }
        }
    }
    if (node.children) {
        for (const child of node.children) {
            destroyBuffers(child);
        }
    }
}

//      
class ModelFeature {
    constructor(feature, offset) {
        this.feature = feature;
        this.instancedDataOffset = offset;
        this.instancedDataCount = 0;
        this.rotation = [
            0,
            0,
            0
        ];
        this.scale = [
            1,
            1,
            1
        ];
        this.translation = [
            0,
            0,
            0
        ];
    }
}
class PerModelAttributes {
    // If node has meshes, instancedDataArray gets an entry for each feature instance (used for all meshes or the node).
    // Gets added to DEM elevation of the instance to produce value in instancedDataArray.
    // via this.features, enable lookup instancedDataArray based on feature ID.
    constructor() {
        this.instancedDataArray = new StructArrayLayout16f64();
        this.instancesEvaluatedElevation = [];
        this.features = [];
        this.idToFeaturesIndex = {};
    }
}
class ModelBucket {
    // elevation is baked into vertex buffer together with evaluated instance translation
    // for tile AABB calculation
    // across all dimensions, for tile AABB calculation
    // calculated from previous two, during rendering, when models are available.
    // evaluated during first shadows pass and cached here for the second shadow pass.
    // Bucket min/max terrain elevation among instance positions taking exaggeration value into account
    /* $FlowIgnore[incompatible-type-arg] Doesn't need to know about all the implementations */
    constructor(options) {
        this.zoom = options.zoom;
        this.canonical = options.canonical;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.projection = options.projection;
        this.index = options.index;
        this.hasZoomDependentProperties = this.layers[0].isZoomDependent();
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.hasPattern = false;
        this.instancesPerModel = {};
        this.validForExaggeration = 0;
        this.maxVerticalOffset = 0;
        this.maxScale = 0;
        this.maxHeight = 0;
        // reduce density, more on lower zooms and almost no reduction in overscale range.
        // Heuristics is related to trees performance.
        this.lookupDim = this.zoom > this.canonical.z ? 256 : this.zoom > 15 ? 75 : 100;
        this.instanceCount = 0;
        this.terrainElevationMin = 0;
        this.terrainElevationMax = 0;
        this.validForDEMTile = {
            id: null,
            timestamp: 0
        };
    }
    populate(features, options, canonical, tileTransform) {
        this.tileToMeter = tileToMeter(canonical);
        const needGeometry = this.layers[0]._featureFilter.needGeometry;
        this.lookup = new Uint8Array(this.lookupDim * this.lookupDim);
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            // $FlowFixMe[method-unbinding]
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const bucketFeature = {
                id,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),
                properties: feature.properties,
                type: feature.type,
                patterns: {}
            };
            const modelId = this.addFeature(bucketFeature, bucketFeature.geometry, evaluationFeature);
            if (modelId) {
                options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, this.instancesPerModel[modelId].instancedDataArray.length);
            }
        }
        this.lookup = null;
    }
    // eslint-disable-next-line no-unused-vars
    update(states, vtLayer, availableImages, imagePositions) {
        // called when setFeature state API is used
        for (const modelId in this.instancesPerModel) {
            const instances = this.instancesPerModel[modelId];
            for (const id in states) {
                if (instances.idToFeaturesIndex.hasOwnProperty(id)) {
                    const feature = instances.features[instances.idToFeaturesIndex[id]];
                    this.evaluate(feature, states[id], instances, true);
                }
            }
        }
        this.maxHeight = 0;    // needs to be recalculated.
    }
    updateZoomBasedPaintProperties() {
        if (!this.hasZoomDependentProperties) {
            return false;
        }
        // layer.paint.get('model-rotation').isZoom
        let reuploadNeeded = false;
        for (const modelId in this.instancesPerModel) {
            const instances = this.instancesPerModel[modelId];
            for (const feature of instances.features) {
                const layer = this.layers[0];
                const evaluationFeature = feature.feature;
                const canonical = this.canonical;
                const rotation = layer.paint.get('model-rotation').evaluate(evaluationFeature, {}, canonical);
                const scale = layer.paint.get('model-scale').evaluate(evaluationFeature, {}, canonical);
                const translation = layer.paint.get('model-translation').evaluate(evaluationFeature, {}, canonical);
                // $FlowFixMe.
                if (!vec3_1.exactEquals(feature.rotation, rotation) || // $FlowFixMe.
                    !vec3_1.exactEquals(feature.scale, scale) || // $FlowFixMe.
                    !vec3_1.exactEquals(feature.translation, translation)) {
                    this.evaluate(feature, feature.featureStates, instances, true);
                    reuploadNeeded = true;
                }
            }
        }
        return reuploadNeeded;
    }
    isEmpty() {
        for (const modelId in this.instancesPerModel) {
            const perModelAttributes = this.instancesPerModel[modelId];
            if (perModelAttributes.instancedDataArray.length !== 0)
                return false;
        }
        return true;
    }
    uploadPending() {
        return !this.uploaded;
    }
    upload(context) {
        // if buffer size is less than the threshold, do not upload instance buffer.
        // if instance buffer is not uploaded, instances are rendered one by one.
        const useInstancingThreshold = 0;
        if (!this.uploaded) {
            for (const modelId in this.instancesPerModel) {
                const perModelAttributes = this.instancesPerModel[modelId];
                if (perModelAttributes.instancedDataArray.length < useInstancingThreshold || perModelAttributes.instancedDataArray.length === 0)
                    continue;
                if (!perModelAttributes.instancedDataBuffer) {
                    perModelAttributes.instancedDataBuffer = context.createVertexBuffer(perModelAttributes.instancedDataArray, instanceAttributes.members, true, undefined, this.instanceCount);
                } else {
                    perModelAttributes.instancedDataBuffer.updateData(perModelAttributes.instancedDataArray);
                }
            }
        }
        this.uploaded = true;
    }
    destroy() {
        for (const modelId in this.instancesPerModel) {
            const perModelAttributes = this.instancesPerModel[modelId];
            if (perModelAttributes.instancedDataArray.length === 0)
                continue;
            if (perModelAttributes.instancedDataBuffer) {
                perModelAttributes.instancedDataBuffer.destroy();
            }
        }
    }
    addFeature(feature, geometry, evaluationFeature) {
        const layer = this.layers[0];
        const modelIdProperty = layer.layout.get('model-id');
        const modelId = modelIdProperty.evaluate(evaluationFeature, {}, this.canonical);
        if (!modelId) {
            warnOnce(`modelId is not evaluated for layer ${ layer.id } and it is not going to get rendered.`);
            return modelId;
        }
        if (!this.instancesPerModel[modelId]) {
            this.instancesPerModel[modelId] = new PerModelAttributes();
        }
        const perModelVertexArray = this.instancesPerModel[modelId];
        const instancedDataArray = perModelVertexArray.instancedDataArray;
        const modelFeature = new ModelFeature(evaluationFeature, instancedDataArray.length);
        for (const geometries of geometry) {
            for (const point of geometries) {
                if (point.x < 0 || point.x >= EXTENT || point.y < 0 || point.y >= EXTENT) {
                    continue;    // Clip on tile borders to prevent duplicates
                }
                // reduce density
                const tileToLookup = (this.lookupDim - 1) / EXTENT;
                const lookupIndex = this.lookupDim * (point.y * tileToLookup | 0) + point.x * tileToLookup | 0;
                if (this.lookup) {
                    if (this.lookup[lookupIndex] !== 0) {
                        continue;
                    }
                    this.lookup[lookupIndex] = 1;
                }
                this.instanceCount++;
                const i = instancedDataArray.length;
                instancedDataArray.resize(i + 1);
                perModelVertexArray.instancesEvaluatedElevation.push(0);
                instancedDataArray.float32[i * 16] = point.x;
                instancedDataArray.float32[i * 16 + 1] = point.y;
            }
        }
        modelFeature.instancedDataCount = perModelVertexArray.instancedDataArray.length - modelFeature.instancedDataOffset;
        if (modelFeature.instancedDataCount > 0) {
            if (feature.id) {
                perModelVertexArray.idToFeaturesIndex[feature.id] = perModelVertexArray.features.length;
            }
            perModelVertexArray.features.push(modelFeature);
            this.evaluate(modelFeature, {}, perModelVertexArray, false);
        }
        return modelId;
    }
    evaluate(feature, featureState, perModelVertexArray, update) {
        const layer = this.layers[0];
        const evaluationFeature = feature.feature;
        const canonical = this.canonical;
        // $FlowFixMe.
        const rotation = feature.rotation = layer.paint.get('model-rotation').evaluate(evaluationFeature, featureState, canonical);
        // $FlowFixMe.
        const scale = feature.scale = layer.paint.get('model-scale').evaluate(evaluationFeature, featureState, canonical);
        // $FlowFixMe.
        const translation = feature.translation = layer.paint.get('model-translation').evaluate(evaluationFeature, featureState, canonical);
        const color = layer.paint.get('model-color').evaluate(evaluationFeature, featureState, canonical);
        color.a = layer.paint.get('model-color-mix-intensity').evaluate(evaluationFeature, featureState, canonical);
        const rotationScaleYZFlip = [];
        if (this.maxVerticalOffset < translation[2])
            this.maxVerticalOffset = translation[2];
        this.maxScale = Math.max(Math.max(this.maxScale, scale[0]), Math.max(scale[1], scale[2]));
        rotationScaleYZFlipMatrix(rotationScaleYZFlip, rotation, scale);
        // https://github.com/mapbox/mapbox-gl-native-internal/blob/c380f9492220906accbdca1f02cca5ee489d97fc/src/mbgl/renderer/layers/render_model_layer.cpp#L1282
        const constantTileToMeterAcrossTile = 10;
        const vaOffset2 = Math.round(100 * color.a) + color.b / 1.05;
        for (let i = 0; i < feature.instancedDataCount; ++i) {
            const instanceOffset = feature.instancedDataOffset + i;
            const offset = instanceOffset * 16;
            const va = perModelVertexArray.instancedDataArray.float32;
            let terrainElevationContribution = 0;
            if (update) {
                terrainElevationContribution = va[offset + 6] - perModelVertexArray.instancesEvaluatedElevation[instanceOffset];
            }
            // All per-instance attributes are packed to one 4x4 float matrix. Data is not expected
            // to change on every frame when e.g. camera or light changes.
            // Column major order. Elements:
            // 0 & 1: tile coordinates stored in integer part of float, R and G color components,
            // originally in range [0..1], scaled to range [0..0.952(arbitrary, just needs to be
            // under 1)].
            const pointY = va[offset + 1] | 0;
            // point.y stored in integer part
            va[offset] = (va[offset] | 0) + color.r / 1.05;
            // point.x stored in integer part
            va[offset + 1] = pointY + color.g / 1.05;
            // Element 2: packs color's alpha (as integer part) and blue component in fractional part.
            va[offset + 2] = vaOffset2;
            // tileToMeter is taken at center of tile. Prevent recalculating it over again for
            // thousands of trees.
            // Element 3: tileUnitsToMeter conversion.
            va[offset + 3] = 1 / (canonical.z > constantTileToMeterAcrossTile ? this.tileToMeter : tileToMeter(canonical, pointY));
            // Elements [4..6]: translation evaluated for the feature.
            va[offset + 4] = translation[0];
            va[offset + 5] = translation[1];
            va[offset + 6] = translation[2] + terrainElevationContribution;
            // Elements [7..16] Instance modelMatrix holds combined rotation and scale 3x3,
            va[offset + 7] = rotationScaleYZFlip[0];
            va[offset + 8] = rotationScaleYZFlip[1];
            va[offset + 9] = rotationScaleYZFlip[2];
            va[offset + 10] = rotationScaleYZFlip[4];
            va[offset + 11] = rotationScaleYZFlip[5];
            va[offset + 12] = rotationScaleYZFlip[6];
            va[offset + 13] = rotationScaleYZFlip[8];
            va[offset + 14] = rotationScaleYZFlip[9];
            va[offset + 15] = rotationScaleYZFlip[10];
            perModelVertexArray.instancesEvaluatedElevation[instanceOffset] = translation[2];
        }
    }
}
register(ModelBucket, 'ModelBucket', { omit: ['layers'] });
register(PerModelAttributes, 'PerModelAttributes');
register(ModelFeature, 'ModelFeature');

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$5 = new Properties({
    'visibility': new DataConstantProperty(spec['layout_model']['visibility']),
    'model-id': new DataDrivenProperty(spec['layout_model']['model-id'])
});
const paint$6 = new Properties({
    'model-opacity': new DataConstantProperty(spec['paint_model']['model-opacity']),
    'model-rotation': new DataDrivenProperty(spec['paint_model']['model-rotation']),
    'model-scale': new DataDrivenProperty(spec['paint_model']['model-scale']),
    'model-translation': new DataDrivenProperty(spec['paint_model']['model-translation']),
    'model-color': new DataDrivenProperty(spec['paint_model']['model-color']),
    'model-color-mix-intensity': new DataDrivenProperty(spec['paint_model']['model-color-mix-intensity']),
    'model-type': new DataConstantProperty(spec['paint_model']['model-type']),
    'model-cast-shadows': new DataConstantProperty(spec['paint_model']['model-cast-shadows']),
    'model-receive-shadows': new DataConstantProperty(spec['paint_model']['model-receive-shadows']),
    'model-ambient-occlusion-intensity': new DataConstantProperty(spec['paint_model']['model-ambient-occlusion-intensity']),
    'model-emissive-strength': new DataDrivenProperty(spec['paint_model']['model-emissive-strength']),
    'model-roughness': new DataDrivenProperty(spec['paint_model']['model-roughness']),
    'model-height-based-emissive-strength-multiplier': new DataDrivenProperty(spec['paint_model']['model-height-based-emissive-strength-multiplier']),
    'model-cutoff-fade-range': new DataConstantProperty(spec['paint_model']['model-cutoff-fade-range'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$a = {
    paint: paint$6,
    layout: layout$5
};

//      
class ModelStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$a, options);
    }
    createBucket(parameters) {
        return new ModelBucket(parameters);
    }
    getProgramIds() {
        return ['model'];
    }
    is3D() {
        return true;
    }
    hasShadowPass() {
        return true;
    }
    canCastShadows() {
        return true;
    }
    hasLightBeamPass() {
        return true;
    }
    cutoffRange() {
        return this.paint.get('model-cutoff-fade-range');
    }
    // $FlowFixMe[method-unbinding]
    queryRadius() {
        return 0;
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature() {
        return false;
    }
    _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) {
        if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {
            return false;
        }
        // relayout on programatically setPaintProperty for all non-data-driven properties that get baked into vertex data.
        // Buckets could be updated without relayout later, if needed to optimize.
        return name === 'model-color' || name === 'model-color-mix-intensity' || name === 'model-rotation' || name === 'model-scale' || name === 'model-translation' || name === 'model-emissive-strength';
    }
    _isPropertyZoomDependent(name) {
        const prop = this._transitionablePaint._values[name];
        return prop != null && prop.value != null && prop.value.expression != null && prop.value.expression instanceof ZoomDependentExpression;
    }
    isZoomDependent() {
        return this._isPropertyZoomDependent('model-scale') || this._isPropertyZoomDependent('model-rotation') || this._isPropertyZoomDependent('model-translation');
    }
}

//      
const lookup = new Float32Array(512 * 512);
const passLookup = new Uint8Array(512 * 512);
function getNodeHeight(node) {
    let height = 0;
    if (node.meshes) {
        for (const mesh of node.meshes) {
            height = Math.max(height, mesh.aabb.max[2]);
        }
    }
    if (node.children) {
        for (const child of node.children) {
            height = Math.max(height, getNodeHeight(child));
        }
    }
    return height;
}
const PartIndices = {
    wall: 1,
    door: 2,
    roof: 3,
    window: 4,
    lamp: 5,
    logo: 6
};
const PartNames = [
    '',
    'wall',
    'door',
    'roof',
    'window',
    'lamp',
    'logo'
];
class Tiled3dModelFeature {
    constructor(node) {
        this.node = node;
        this.evaluatedRMEA = [
            [
                1,
                0,
                0,
                1
            ],
            [
                1,
                0,
                0,
                1
            ],
            // wall
            [
                1,
                0,
                0,
                1
            ],
            // door
            [
                1,
                0,
                0,
                1
            ],
            // roof
            [
                0.4,
                1,
                0,
                1
            ],
            // window
            [
                1,
                0,
                0,
                1
            ],
            // lamp
            [
                1,
                0,
                0,
                1
            ]
        ];
        // logo
        this.hiddenByReplacement = false;
        this.evaluatedScale = [
            1,
            1,
            1
        ];
        this.evaluatedColor = [];
        this.emissionHeightBasedParams = [];
        // Needs to calculate geometry
        this.feature = {
            type: 'Point',
            id: node.id,
            geometry: [],
            properties: { 'height': getNodeHeight(node) }
        };
    }
}
class Tiled3dModelBucket {
    /* $FlowIgnore[incompatible-type-arg] Doesn't need to know about all the implementations */
    constructor(nodes, id, hasMbxMeshFeatures, brightness) {
        this.nodes = nodes;
        this.id = id;
        this.modelTraits |= ModelTraits.CoordinateSpaceTile;
        this.uploaded = false;
        this.hasPattern = false;
        if (hasMbxMeshFeatures) {
            this.modelTraits |= ModelTraits.HasMapboxMeshFeatures;
        }
        this.zoom = -1;
        this.terrainExaggeration = 1;
        this.projection = { name: 'mercator' };
        this.replacementUpdateTime = 0;
        this.elevationReadFromZ = 255;
        // Re-read if underlying DEM zoom changes.
        this.brightness = brightness;
        this.dirty = true;
        this.needsUpload = false;
    }
    update() {
        console.log('Update 3D model bucket');
    }
    populate() {
        console.log('populate 3D model bucket');
    }
    uploadPending() {
        return !this.uploaded || this.needsUpload;
    }
    upload(context) {
        if (!this.needsUpload)
            return;
        const nodesInfo = this.getNodesInfo();
        for (const nodeInfo of nodesInfo) {
            const node = nodeInfo.node;
            if (this.uploaded) {
                this.updatePbrBuffer(node);
                continue;
            }
            uploadNode(node, context, true);
        }
        // Now destroy all buffers
        for (const nodeInfo of nodesInfo) {
            destroyNodeArrays(nodeInfo.node);
        }
        this.uploaded = true;
        this.needsUpload = false;
    }
    updatePbrBuffer(node) {
        let result = false;
        if (!node.meshes)
            return result;
        for (const mesh of node.meshes) {
            if (mesh.pbrBuffer) {
                mesh.pbrBuffer.updateData(mesh.featureArray);
                result = true;
            }
        }
        return result;
    }
    needsReEvaluation(painter, zoom, layer) {
        const projection = painter.transform.projectionOptions;
        const calculatedBrightness = painter.style.getBrightness();
        const brightnessChanged = this.brightness !== calculatedBrightness;
        if (!this.uploaded || this.dirty || projection.name !== this.projection.name || expressionRequiresReevaluation(layer.paint.get('model-color').value, brightnessChanged) || expressionRequiresReevaluation(layer.paint.get('model-color-mix-intensity').value, brightnessChanged) || expressionRequiresReevaluation(layer.paint.get('model-roughness').value, brightnessChanged) || expressionRequiresReevaluation(layer.paint.get('model-emissive-strength').value, brightnessChanged) || expressionRequiresReevaluation(layer.paint.get('model-height-based-emissive-strength-multiplier').value, brightnessChanged)) {
            this.projection = projection;
            this.brightness = calculatedBrightness;
            return true;
        }
        return false;
    }
    evaluateScale(painter, layer) {
        if (painter.transform.zoom === this.zoom)
            return;
        this.zoom = painter.transform.zoom;
        const nodesInfo = this.getNodesInfo();
        const canonical = this.id.canonical;
        for (const nodeInfo of nodesInfo) {
            const evaluationFeature = nodeInfo.feature;
            nodeInfo.evaluatedScale = layer.paint.get('model-scale').evaluate(evaluationFeature, {}, canonical);
        }
    }
    evaluate(layer) {
        const nodesInfo = this.getNodesInfo();
        for (const nodeInfo of nodesInfo) {
            if (!nodeInfo.node.meshes)
                continue;
            const evaluationFeature = nodeInfo.feature;
            const hasFeatures = nodeInfo.node.meshes && nodeInfo.node.meshes[0].featureData;
            const previousDoorColor = nodeInfo.evaluatedColor[PartIndices.door];
            const previousDoorRMEA = nodeInfo.evaluatedRMEA[PartIndices.door];
            const canonical = this.id.canonical;
            nodeInfo.hasTranslucentParts = false;
            if (hasFeatures) {
                for (let i = 0; i < PartNames.length; i++) {
                    const part = PartNames[i];
                    if (part.length) {
                        evaluationFeature.properties['part'] = part;
                    }
                    const color = layer.paint.get('model-color').evaluate(evaluationFeature, {}, canonical);
                    const colorMixIntensity = layer.paint.get('model-color-mix-intensity').evaluate(evaluationFeature, {}, canonical);
                    nodeInfo.evaluatedColor[i] = [
                        color.r,
                        color.g,
                        color.b,
                        colorMixIntensity
                    ];
                    nodeInfo.evaluatedRMEA[i][0] = layer.paint.get('model-roughness').evaluate(evaluationFeature, {}, canonical);
                    // For the first version metallic is not styled
                    nodeInfo.evaluatedRMEA[i][2] = layer.paint.get('model-emissive-strength').evaluate(evaluationFeature, {}, canonical);
                    nodeInfo.evaluatedRMEA[i][3] = color.a;
                    nodeInfo.emissionHeightBasedParams[i] = layer.paint.get('model-height-based-emissive-strength-multiplier').evaluate(evaluationFeature, {}, canonical);
                    if (!nodeInfo.hasTranslucentParts && color.a < 1) {
                        nodeInfo.hasTranslucentParts = true;
                    }
                }
                delete evaluationFeature.properties['part'];
                const doorLightChanged = previousDoorColor !== nodeInfo.evaluatedColor[PartIndices.door] || previousDoorRMEA !== nodeInfo.evaluatedRMEA[PartIndices.door];
                updateNodeFeatureVertices(nodeInfo, doorLightChanged);
            }
            nodeInfo.evaluatedScale = layer.paint.get('model-scale').evaluate(evaluationFeature, {}, canonical);
            if (!this.updatePbrBuffer(nodeInfo.node)) {
                this.needsUpload = true;
            }
        }
        this.dirty = false;
    }
    elevationUpdate(terrain, exaggeration, coord, source) {
        const demTile = terrain.findDEMTileFor(coord);
        if (!demTile)
            return;
        if (demTile.tileID.canonical === this.terrainTile && exaggeration === this.terrainExaggeration)
            return;
        if (demTile.dem && demTile.tileID.overscaledZ !== this.elevationReadFromZ) {
            this.elevationReadFromZ = demTile.tileID.overscaledZ;
            const dem = DEMSampler.create(terrain, coord, demTile);
            if (!dem)
                return;
            if (this.modelTraits & ModelTraits.HasMapboxMeshFeatures) {
                this.updateDEM(terrain, dem, coord, source);
            }
            for (const nodeInfo of this.getNodesInfo()) {
                const node = nodeInfo.node;
                if (!node.footprint || !node.footprint.vertices || !node.footprint.vertices.length) {
                    continue;
                }
                const vertices = node.footprint.vertices;
                let elevation = dem.getElevationAt(vertices[0].x, vertices[0].y, true, true);
                for (let i = 1; i < vertices.length; i++) {
                    elevation = Math.min(elevation, dem.getElevationAt(vertices[i].x, vertices[i].y, true, true));
                }
                node.elevation = elevation;
            }
        }
        this.terrainTile = demTile.tileID.canonical;
        this.terrainExaggeration = exaggeration;
    }
    updateDEM(terrain, dem, coord, source) {
        let tiles = dem._dem._modifiedForSources[source];
        if (tiles === undefined) {
            dem._dem._modifiedForSources[source] = [];
            tiles = dem._dem._modifiedForSources[source];
        }
        if (tiles.includes(coord.canonical)) {
            return;
        }
        // Resolution of the DEM data.
        const demRes = dem._dem.dim;
        tiles.push(coord.canonical);
        let changed = false;
        for (const nodeInfo of this.getNodesInfo()) {
            const node = nodeInfo.node;
            if (!node.footprint || !node.footprint.grid) {
                continue;
            }
            // Convert the bounds of the footprint for this node from its tile coordinates to DEM pixel coordinates.
            const grid = node.footprint.grid;
            const minDem = dem.tileCoordToPixel(grid.min.x, grid.min.y);
            const maxDem = dem.tileCoordToPixel(grid.max.x, grid.max.y);
            const distanceToBorder = Math.min(Math.min(demRes - maxDem.y, minDem.x), Math.min(minDem.y, demRes - maxDem.x));
            if (distanceToBorder < 0) {
                continue;    // don't deal with neighbors and landmarks crossing tile borders, fix terrain only for buildings within the tile
            }
            // demAtt is a number of pixels we use to propagate attenuated change to surrounding pixels.
            // this is clamped further when sampling near tile border.
            // The footprint covers a certain region of DEM pixels as indicated with 'minDem' and 'maxDem' (region A).
            // This region is further padded by demAtt pixels to form the region B.
            // First mark all the DEM pixels in region B as unchanged (using 'passLookup' array).
            // +------------+
            // |  +-----+   |
            // |  |  A  |   |
            // |  +-----+ B |
            // +------------+
            const demAtt = clamp(distanceToBorder, 2, 5);
            let minx = Math.max(0, minDem.x - demAtt);
            let miny = Math.max(0, minDem.y - demAtt);
            let maxx = Math.min(maxDem.x + demAtt, demRes - 1);
            let maxy = Math.min(maxDem.y + demAtt, demRes - 1);
            for (let y = miny; y <= maxy; ++y) {
                for (let x = minx; x <= maxx; ++x) {
                    passLookup[y * demRes + x] = 255;
                }
            }
            // Next go through all eligible DEM pixels in region A, mark them as changed and calculate the average height(elevation).
            // Some pixels may be skipped (and therefore aren't eligible) because no footprint geometry overlaps them.
            // This is indicated by the existence of a 'Cell' at a given pixel's position.
            let heightAcc = 0;
            let count = 0;
            for (let celly = 0; celly < grid.cellsY; ++celly) {
                for (let cellx = 0; cellx < grid.cellsX; ++cellx) {
                    const cell = grid.cells[celly * grid.cellsX + cellx];
                    if (!cell) {
                        continue;
                    }
                    const demP = dem.tileCoordToPixel(grid.min.x + cellx / grid.xScale, grid.min.y + celly / grid.yScale);
                    const demPMax = dem.tileCoordToPixel(grid.min.x + (cellx + 1) / grid.xScale, grid.min.y + (celly + 1) / grid.yScale);
                    for (let y = demP.y; y <= Math.min(demPMax.y + 1, demRes - 1); ++y) {
                        for (let x = demP.x; x <= Math.min(demPMax.x + 1, demRes - 1); ++x) {
                            if (passLookup[y * demRes + x] === 255) {
                                passLookup[y * demRes + x] = 0;
                                const height = dem.getElevationAtPixel(x, y);
                                heightAcc += height;
                                count++;
                            }
                        }
                    }
                }
            }
            const avgHeight = heightAcc / count;
            // See https://github.com/mapbox/mapbox-gl-js-internal/pull/804#issuecomment-1738720351
            // for explanation why bounds should be clamped to 1 and demRes - 2 respectively.
            minx = Math.max(1, minDem.x - demAtt);
            miny = Math.max(1, minDem.y - demAtt);
            maxx = Math.min(maxDem.x + demAtt, demRes - 2);
            maxy = Math.min(maxDem.y + demAtt, demRes - 2);
            // Next, update the DEM pixels in region A (which the footprint overlaps with) by the average height.
            // This effectively flattens the terrain for the given footprint/building.
            // Store the difference of the original height with the average height in 'lookup' array.
            changed = true;
            for (let y = miny; y <= maxy; ++y) {
                for (let x = minx; x <= maxx; ++x) {
                    if (passLookup[y * demRes + x] === 0) {
                        lookup[y * demRes + x] = dem._dem.set(x, y, avgHeight);
                    }
                }
            }
            // Finally propagate the flattened out values to the remaining surrounding pixels (as goverened by demAtt padding) in region B.
            // This ensures a smooth transition between the flattened and the non-flattened regions.
            for (let p = 1; p < demAtt; ++p) {
                minx = Math.max(1, minDem.x - p);
                miny = Math.max(1, minDem.y - p);
                maxx = Math.min(maxDem.x + p, demRes - 2);
                maxy = Math.min(maxDem.y + p, demRes - 2);
                for (let y = miny; y <= maxy; ++y) {
                    for (let x = minx; x <= maxx; ++x) {
                        const indexThis = y * demRes + x;
                        // If DEM pixel is not modified.
                        if (passLookup[indexThis] === 255) {
                            let maxDiff = 0;
                            let maxDiffAbs = 0;
                            let xoffset = -1;
                            let yoffset = -1;
                            for (let j = -1; j <= 1; ++j) {
                                for (let i = -1; i <= 1; ++i) {
                                    const index = (y + j) * demRes + x + i;
                                    if (passLookup[index] >= p) {
                                        continue;
                                    }
                                    const diff = lookup[index];
                                    const diffAbs = Math.abs(diff);
                                    if (diffAbs > maxDiffAbs) {
                                        maxDiff = diff;
                                        maxDiffAbs = diffAbs;
                                        xoffset = i;
                                        yoffset = j;
                                    }
                                }
                            }
                            if (maxDiffAbs > 0.1) {
                                const diagonalAttenuation = Math.abs(xoffset * yoffset) * 0.5;
                                const attenuation = 1 - (p + diagonalAttenuation) / demAtt;
                                const prev = dem._dem.get(x, y);
                                let next = prev + maxDiff * attenuation;
                                // parent - child in the meaning of wave propagation
                                const parent = dem._dem.get(x + xoffset, y + yoffset);
                                const child = dem._dem.get(x - xoffset, y - yoffset, true);
                                // prevent waves
                                if ((next - parent) * (next - child) > 0) {
                                    next = (parent + child) / 2;
                                }
                                lookup[indexThis] = dem._dem.set(x, y, next);
                                passLookup[indexThis] = p;
                            }
                        }
                    }
                }
            }
        }
        if (changed) {
            dem._demTile.needsDEMTextureUpload = true;
            dem._dem._timestamp = exported$1.now();
        }
    }
    getNodesInfo() {
        if (!this.nodesInfo) {
            this.nodesInfo = [];
            for (const node of this.nodes) {
                this.nodesInfo.push(new Tiled3dModelFeature(node));
            }
            this.freeNodes();
        }
        return this.nodesInfo;
    }
    freeNodes() {
        if (this.nodes) {
            for (const node of this.nodes) {
                destroyBuffers(node);
            }
            this.nodes.splice(0, this.nodes.length);
        }
    }
    destroy() {
        this.freeNodes();
        const nodesInfo = this.getNodesInfo();
        for (const nodeInfo of nodesInfo) {
            destroyNodeArrays(nodeInfo.node);
            destroyBuffers(nodeInfo.node);
        }
    }
    isEmpty() {
        return !this.nodes.length;
    }
    updateReplacement(coord, source) {
        // Replacement has to be re-checked if the source has been updated since last time
        if (source.updateTime === this.replacementUpdateTime) {
            return;
        }
        this.replacementUpdateTime = source.updateTime;
        const activeReplacements = source.getReplacementRegionsForTile(coord.toUnwrapped());
        const nodesInfo = this.getNodesInfo();
        for (let i = 0; i < this.nodesInfo.length; i++) {
            const node = nodesInfo[i].node;
            // Node is visible if its footprint passes the replacement check
            nodesInfo[i].hiddenByReplacement = !!node.footprint && !activeReplacements.find(region => region.footprint === node.footprint);
        }
    }
    getHeightAtTileCoord(x, y) {
        const nodesInfo = this.getNodesInfo();
        const candidates = [];
        for (let i = 0; i < this.nodesInfo.length; i++) {
            const nodeInfo = nodesInfo[i];
            const mesh = nodeInfo.node.meshes[0];
            if (x < mesh.aabb.min[0] || y < mesh.aabb.min[1] || x > mesh.aabb.max[0] || y > mesh.aabb.max[1])
                continue;
            const xCell = (x - mesh.aabb.min[0]) / (mesh.aabb.max[0] - mesh.aabb.min[0]) * HEIGHTMAP_DIM | 0;
            const yCell = (y - mesh.aabb.min[1]) / (mesh.aabb.max[1] - mesh.aabb.min[1]) * HEIGHTMAP_DIM | 0;
            const heightmapIndex = Math.min(HEIGHTMAP_DIM - 1, yCell) * HEIGHTMAP_DIM + Math.min(HEIGHTMAP_DIM - 1, xCell);
            if (mesh.heightmap[heightmapIndex] < 0 && nodeInfo.node.footprint) {
                // unpopulated cell. If it is in the building footprint, return undefined height
                nodeInfo.node.footprint.grid.query(new Point$2(x, y), new Point$2(x, y), candidates);
                if (candidates.length > 0) {
                    return {
                        height: undefined,
                        maxHeight: nodeInfo.feature.properties['height'],
                        hidden: nodeInfo.hiddenByReplacement,
                        verticalScale: nodeInfo.evaluatedScale[2]
                    };
                }
                continue;
            }
            if (nodeInfo.hiddenByReplacement)
                return;
            // better luck with the next source
            return {
                height: mesh.heightmap[heightmapIndex],
                maxHeight: nodeInfo.feature.properties['height'],
                hidden: false,
                verticalScale: nodeInfo.evaluatedScale[2]
            };
        }
    }
}
function expressionRequiresReevaluation(e, brightnessChanged) {
    return !e.isLightConstant && brightnessChanged;
}
function encodeEmissionToByte(emission) {
    const clampedEmission = clamp(emission, 0, 2);
    return Math.min(Math.round(0.5 * clampedEmission * 255), 255);
}
function addPBRVertex(vertexArray, color, colorMix, rmea, heightBasedEmissionMultiplierParams, zMin, zMax, lightsFeatureArray) {
    let r = (color & 61440 | (color & 61440) >> 4) >> 8;
    let g = (color & 3840 | (color & 3840) >> 4) >> 4;
    let b = color & 240 | (color & 240) >> 4;
    if (colorMix[3] > 0) {
        r = number(r, 255 * colorMix[0], colorMix[3]);
        g = number(g, 255 * colorMix[1], colorMix[3]);
        b = number(b, 255 * colorMix[2], colorMix[3]);
    }
    const a0 = r << 8 | g;
    const a1 = b << 8 | Math.floor(rmea[3] * 255);
    const a2 = encodeEmissionToByte(rmea[2]) << 8 | rmea[0] * 15 << 4 | rmea[1] * 15;
    const emissionMultiplierStart = clamp(heightBasedEmissionMultiplierParams[0], 0, 1);
    const emissionMultiplierFinish = clamp(heightBasedEmissionMultiplierParams[1], 0, 1);
    const emissionMultiplierValueStart = clamp(heightBasedEmissionMultiplierParams[2], 0, 1);
    const emissionMultiplierValueFinish = clamp(heightBasedEmissionMultiplierParams[3], 0, 1);
    let a3, b0, b1, b2;
    if (emissionMultiplierStart !== emissionMultiplierFinish && zMax !== zMin && emissionMultiplierFinish !== emissionMultiplierStart) {
        const zRange = zMax - zMin;
        b0 = 1 / (zRange * (emissionMultiplierFinish - emissionMultiplierStart));
        b1 = -(zMin + zRange * emissionMultiplierStart) / (zRange * (emissionMultiplierFinish - emissionMultiplierStart));
        const power = clamp(heightBasedEmissionMultiplierParams[4], -1, 1);
        b2 = Math.pow(10, power);
        a3 = emissionMultiplierValueStart * 255 << 8 | emissionMultiplierValueFinish * 255;
    } else {
        a3 = 255 << 8 | 255;
        b0 = 0;
        b1 = 1;
        b2 = 1;
    }
    vertexArray.emplaceBack(a0, a1, a2, a3, b0, b1, b2);
    if (lightsFeatureArray) {
        const size = lightsFeatureArray.length;
        lightsFeatureArray.clear();
        for (let j = 0; j < size; j++) {
            lightsFeatureArray.emplaceBack(a0, a1, a2, a3, b0, b1, b2);
        }
    }
}
function updateNodeFeatureVertices(nodeInfo, doorLightChanged) {
    const node = nodeInfo.node;
    let i = 0;
    for (const mesh of node.meshes) {
        if (node.lights && node.lightMeshIndex === i)
            continue;
        if (!mesh.featureData)
            continue;
        // initialize featureArray
        mesh.featureArray = new StructArrayLayout4ui3f20();
        mesh.featureArray.reserve(mesh.featureData.length);
        let pendingDoorLightUpdate = doorLightChanged;
        for (const feature of mesh.featureData) {
            let lightsFeatureArray;
            const id = feature & 65535;
            const partId = (id & 15) < 8 ? id & 15 : 0;
            const featureColor = feature >> 16 & 65535;
            const rmea = nodeInfo.evaluatedRMEA[partId];
            const evaluatedColor = nodeInfo.evaluatedColor[partId];
            const emissionParams = nodeInfo.emissionHeightBasedParams[partId];
            if (pendingDoorLightUpdate && partId === PartIndices.door && node.lights) {
                lightsFeatureArray = new StructArrayLayout4ui3f20();
                lightsFeatureArray.resize(node.lights.length * 10);
            }
            addPBRVertex(mesh.featureArray, featureColor, evaluatedColor, rmea, emissionParams, mesh.aabb.min[2], mesh.aabb.max[2], lightsFeatureArray);
            if (lightsFeatureArray && pendingDoorLightUpdate) {
                pendingDoorLightUpdate = false;
                const lightsMesh = node.meshes[node.lightMeshIndex];
                lightsMesh.featureArray = lightsFeatureArray;
                lightsMesh.featureArray._trim();
            }
        }
        mesh.featureArray._trim();
        i++;
    }
}
register(Tiled3dModelBucket, 'Tiled3dModelBucket', { omit: ['layers'] });
register(Tiled3dModelFeature, 'Tiled3dModelFeature');

//      
// Abstract interface that acts as a source for footprints used in the replacement process
class ReplacementSource {
    constructor() {
        this._updateTime = 0;
        this._sourceIds = [];
        this._activeRegions = [];
        this._prevRegions = [];
    }
    clear() {
        if (this._activeRegions.length > 0) {
            ++this._updateTime;
        }
        this._activeRegions = [];
        this._prevRegions = [];
    }
    get updateTime() {
        return this._updateTime;
    }
    getReplacementRegionsForTile(id) {
        const tileBounds = transformAabbToMerc(new Point$2(0, 0), new Point$2(EXTENT, EXTENT), id);
        const result = [];
        for (const region of this._activeRegions) {
            if (region.hiddenByOverlap) {
                continue;
            }
            if (!regionsOverlap(tileBounds, region)) {
                continue;
            }
            const bounds = transformAabbToTile(region.min, region.max, id);
            result.push({
                min: bounds.min,
                max: bounds.max,
                sourceId: this._sourceIds[region.priority],
                footprint: region.footprint,
                footprintTileId: region.tileId
            });
        }
        return result;
    }
    setSources(sources) {
        this._setSources(sources.map(source => {
            return {
                getSourceId: () => {
                    return source.cache.id;
                },
                getFootprints: () => {
                    const footprints = [];
                    for (const id of source.cache.getVisibleCoordinates()) {
                        const tile = source.cache.getTile(id);
                        const bucket = tile.buckets[source.layer];
                        if (!bucket) {
                            continue;
                        }
                        for (const nodeInfo of bucket.getNodesInfo()) {
                            const node = nodeInfo.node;
                            if (!node.footprint) {
                                continue;
                            }
                            footprints.push({
                                footprint: node.footprint,
                                id: id.toUnwrapped()
                            });
                        }
                    }
                    return footprints;
                }
            };
        }));
    }
    _addSource(source) {
        const footprints = source.getFootprints();
        if (footprints.length === 0) {
            return;
        }
        for (const fp of footprints) {
            if (!fp.footprint) {
                continue;
            }
            const bounds = transformAabbToMerc(fp.footprint.min, fp.footprint.max, fp.id);
            this._activeRegions.push({
                min: bounds.min,
                max: bounds.max,
                hiddenByOverlap: false,
                priority: this._sourceIds.length,
                tileId: fp.id,
                footprint: fp.footprint
            });
        }
        this._sourceIds.push(source.getSourceId());
    }
    _computeReplacement() {
        this._activeRegions.sort((a, b) => {
            return a.priority - b.priority || comparePoint(a.min, b.min) || comparePoint(a.max, b.max);
        });
        // Check if active regions have changed since last update
        let regionsChanged = this._activeRegions.length !== this._prevRegions.length;
        if (!regionsChanged) {
            let activeIdx = 0;
            let prevIdx = 0;
            while (!regionsChanged && activeIdx !== this._activeRegions.length) {
                const curr = this._activeRegions[activeIdx];
                const prev = this._prevRegions[prevIdx];
                regionsChanged = curr.priority !== prev.priority || !boundsEquals(curr, prev);
                ++activeIdx;
                ++prevIdx;
            }
        }
        if (regionsChanged) {
            ++this._updateTime;
            const firstRegionOfNextPriority = idx => {
                const regs = this._activeRegions;
                if (idx >= regs.length) {
                    return idx;
                }
                const priority = regs[idx].priority;
                while (idx < regs.length && regs[idx].priority === priority) {
                    ++idx;
                }
                return idx;
            };
            if (this._sourceIds.length > 1) {
                // More than one replacement source exists in the style.
                // Hide any overlapping regions in subsequent sources.
                // Travel through all regions and hide regions overlapping with
                // ones with higher priority.
                let rangeBegin = 0;
                let rangeEnd = firstRegionOfNextPriority(rangeBegin);
                while (rangeBegin !== rangeEnd) {
                    let idx = rangeBegin;
                    const prevRangeEnd = rangeBegin;
                    while (idx !== rangeEnd) {
                        const active = this._activeRegions[idx];
                        // Go through each footprint in the current priority level
                        // and check whether they're been occluded by any other regions
                        // with higher priority
                        active.hiddenByOverlap = false;
                        for (let prevIdx = 0; prevIdx < prevRangeEnd; prevIdx++) {
                            const prev = this._activeRegions[prevIdx];
                            if (prev.hiddenByOverlap) {
                                continue;
                            }
                            if (regionsOverlap(active, prev)) {
                                active.hiddenByOverlap = footprintsIntersect(active.footprint, active.tileId, prev.footprint, prev.tileId);
                                if (active.hiddenByOverlap) {
                                    break;
                                }
                            }
                        }
                        ++idx;
                    }
                    rangeBegin = rangeEnd;
                    rangeEnd = firstRegionOfNextPriority(rangeBegin);
                }
            }
        }
    }
    _setSources(sources) {
        // $FlowIssue[unsupported-syntax]
        [this._prevRegions, this._activeRegions] = [
            this._activeRegions,
            []
        ];
        this._sourceIds = [];
        for (let i = sources.length - 1; i >= 0; i--) {
            this._addSource(sources[i]);
        }
        this._computeReplacement();
    }
}
function comparePoint(a, b) {
    return a.x - b.x || a.y - b.y;
}
function boundsEquals(a, b) {
    return comparePoint(a.min, b.min) === 0 && comparePoint(a.max, b.max) === 0;
}
function regionsOverlap(a, b) {
    if (a.min.x > b.max.x || a.max.x < b.min.x)
        return false;
    else if (a.min.y > b.max.y || a.max.y < b.min.y)
        return false;
    return true;
}
function regionsEquals(a, b) {
    if (a.length !== b.length) {
        return false;
    }
    for (let i = 0; i < a.length; i++) {
        if (a[i].sourceId !== b[i].sourceId || !boundsEquals(a[i], b[i])) {
            return false;
        }
    }
    return true;
}
function transformAabbToMerc(min, max, id) {
    const invExtent = 1 / EXTENT;
    const invTiles = 1 / (1 << id.canonical.z);
    const minx = (min.x * invExtent + id.canonical.x) * invTiles + id.wrap;
    const maxx = (max.x * invExtent + id.canonical.x) * invTiles + id.wrap;
    const miny = (min.y * invExtent + id.canonical.y) * invTiles;
    const maxy = (max.y * invExtent + id.canonical.y) * invTiles;
    return {
        min: new Point$2(minx, miny),
        max: new Point$2(maxx, maxy)
    };
}
function transformAabbToTile(min, max, id) {
    const tiles = 1 << id.canonical.z;
    const minx = ((min.x - id.wrap) * tiles - id.canonical.x) * EXTENT;
    const maxx = ((max.x - id.wrap) * tiles - id.canonical.x) * EXTENT;
    const miny = (min.y * tiles - id.canonical.y) * EXTENT;
    const maxy = (max.y * tiles - id.canonical.y) * EXTENT;
    return {
        min: new Point$2(minx, miny),
        max: new Point$2(maxx, maxy)
    };
}
function footprintTrianglesIntersect(footprint, vertices, indices, indexOffset, indexCount, baseVertex, padding) {
    const fpIndices = footprint.indices;
    const fpVertices = footprint.vertices;
    const candidateTriangles = [];
    for (let i = indexOffset; i < indexOffset + indexCount; i += 3) {
        const a = vertices[indices[i + 0] + baseVertex];
        const b = vertices[indices[i + 1] + baseVertex];
        const c = vertices[indices[i + 2] + baseVertex];
        const mnx = Math.min(a.x, b.x, c.x);
        const mxx = Math.max(a.x, b.x, c.x);
        const mny = Math.min(a.y, b.y, c.y);
        const mxy = Math.max(a.y, b.y, c.y);
        candidateTriangles.length = 0;
        footprint.grid.query(new Point$2(mnx, mny), new Point$2(mxx, mxy), candidateTriangles);
        for (let j = 0; j < candidateTriangles.length; j++) {
            const triIdx = candidateTriangles[j];
            const v0 = fpVertices[fpIndices[triIdx * 3 + 0]];
            const v1 = fpVertices[fpIndices[triIdx * 3 + 1]];
            const v2 = fpVertices[fpIndices[triIdx * 3 + 2]];
            if (triangleIntersectsTriangle(v0, v1, v2, a, b, c, padding)) {
                return true;
            }
        }
    }
    return false;
}
function footprintsIntersect(a, aTile, b, bTile) {
    if (!a || !b) {
        return false;
    }
    let queryVertices = a.vertices;
    // Convert vertices of the smaller footprint to the coordinate space of the larger one
    if (!aTile.canonical.equals(bTile.canonical) || aTile.wrap !== bTile.wrap) {
        if (b.vertices.length < a.vertices.length) {
            return footprintsIntersect(b, bTile, a, aTile);
        }
        const srcId = aTile.canonical;
        const dstId = bTile.canonical;
        const zDiff = Math.pow(2, dstId.z - srcId.z);
        queryVertices = a.vertices.map(v => {
            const x = v.x * srcId.x * EXTENT * zDiff - dstId.x * EXTENT;
            const y = v.y * srcId.y * EXTENT * zDiff - dstId.y * EXTENT;
            return new Point$2(x, y);
        });
    }
    return footprintTrianglesIntersect(b, queryVertices, a.indices, 0, a.indices.length, 0, 0);
}

//      
const vectorTileFeatureTypes = VectorTileFeature.types;
const EARCUT_MAX_RINGS = 500;
const fillExtrusionDefaultDataDrivenProperties = [
    'fill-extrusion-base',
    'fill-extrusion-height',
    'fill-extrusion-color',
    'fill-extrusion-pattern',
    'fill-extrusion-flood-light-wall-radius'
];
const fillExtrusionGroundDataDrivenProperties = ['fill-extrusion-flood-light-ground-radius'];
const FACTOR = Math.pow(2, 13);
const TANGENT_CUTOFF = 4;
const NORM = Math.pow(2, 15) - 1;
const QUAD_VERTS = 4;
const QUAD_TRIS = 2;
// In flood lighting a line segment is extruded based on the flood light radius to form a quad.
// The tile is divided into four regions (left, right, top and bottom).
// As an example when a quad crosses the left border it belongs to the left region.
const TILE_REGIONS = 4;
const HIDDEN_CENTROID = new Point$2(0, 1);
const HIDDEN_BY_REPLACEMENT = 2147483648;
// Also declared in _prelude_terrain.vertex.glsl
// Used to scale most likely elevation values to fit well in an uint16
// (Elevation of Dead Sea + ELEVATION_OFFSET) * ELEVATION_SCALE is roughly 0
// (Height of mt everest + ELEVATION_OFFSET) * ELEVATION_SCALE is roughly 64k
const ELEVATION_SCALE = 7;
const ELEVATION_OFFSET = 450;
function addVertex$1(vertexArray, x, y, nxRatio, nySign, normalUp, top, e) {
    vertexArray.emplaceBack(// a_pos_normal_ed:
    // Encode top and side/up normal using the least significant bits
    (x << 1) + top, (y << 1) + normalUp, // dxdy is signed, encode quadrant info using the least significant bit
    (Math.floor(nxRatio * FACTOR) << 1) + nySign, // edgedistance (used for wrapping patterns around extrusion sides)
    Math.round(e));
}
function addGroundVertex(vertexArray, p, q, start, bottom, angle) {
    vertexArray.emplaceBack(p.x, p.y, (q.x << 1) + start, (q.y << 1) + bottom, angle);
}
function addGlobeExtVertex(vertexArray, pos, normal) {
    const encode = 1 << 14;
    vertexArray.emplaceBack(pos.x, pos.y, pos.z, normal[0] * encode, normal[1] * encode, normal[2] * encode);
}
class FootprintSegment {
    constructor() {
        this.vertexOffset = 0;
        this.vertexCount = 0;
        this.indexOffset = 0;
        this.indexCount = 0;
    }
}
// Stores centroid buffer content (one entry per feature as opposite to one entry per
// vertex in the buffer). This information is used to do conflation vs 3d model layers.
// PartData and BorderCentroidData are split because PartData is stored for every
// bucket feature and BorderCentroidData only for features that intersect border.
class PartData {
    constructor() {
        this.centroidXY = new Point$2(0, 0);
        this.vertexArrayOffset = 0;
        this.vertexCount = 0;
        this.groundVertexArrayOffset = 0;
        this.groundVertexCount = 0;
        this.flags = 0;
        this.footprintSegIdx = -1;
        this.footprintSegLen = 0;
        this.min = new Point$2(Number.MAX_VALUE, Number.MAX_VALUE);
        this.max = new Point$2(-Number.MAX_VALUE, -Number.MAX_VALUE);
        this.height = 0;
    }
    span() {
        return new Point$2(this.max.x - this.min.x, this.max.y - this.min.y);
    }
}
// Used for calculating centroid of a feature and intersections of a feature with tile borders.
// Uses and extends data in PartData. References to PartData via centroidDataIndex.
class BorderCentroidData {
    // Array<[min, max]>
    constructor() {
        this.acc = new Point$2(0, 0);
        this.accCount = 0;
        this.centroidDataIndex = 0;
    }
    startRing(data, p) {
        if (data.min.x === Number.MAX_VALUE) {
            // If not initialized.
            data.min.x = data.max.x = p.x;
            data.min.y = data.max.y = p.y;
        }
    }
    appendEdge(data, p, prev) {
        this.accCount++;
        this.acc._add(p);
        let checkBorders = !!this.borders;
        if (p.x < data.min.x) {
            data.min.x = p.x;
            checkBorders = true;
        } else if (p.x > data.max.x) {
            data.max.x = p.x;
            checkBorders = true;
        }
        if (p.y < data.min.y) {
            data.min.y = p.y;
            checkBorders = true;
        } else if (p.y > data.max.y) {
            data.max.y = p.y;
            checkBorders = true;
        }
        if (((p.x === 0 || p.x === EXTENT) && p.x === prev.x) !== ((p.y === 0 || p.y === EXTENT) && p.y === prev.y)) {
            // Custom defined geojson buildings are cut on borders. Points are
            // repeated when edge cuts tile corner (reason for using xor).
            this.processBorderOverlap(p, prev);
        }
        if (checkBorders) {
            this.checkBorderIntersection(p, prev);
        }
    }
    checkBorderIntersection(p, prev) {
        if (prev.x < 0 !== p.x < 0) {
            this.addBorderIntersection(0, number(prev.y, p.y, (0 - prev.x) / (p.x - prev.x)));
        }
        if (prev.x > EXTENT !== p.x > EXTENT) {
            this.addBorderIntersection(1, number(prev.y, p.y, (EXTENT - prev.x) / (p.x - prev.x)));
        }
        if (prev.y < 0 !== p.y < 0) {
            this.addBorderIntersection(2, number(prev.x, p.x, (0 - prev.y) / (p.y - prev.y)));
        }
        if (prev.y > EXTENT !== p.y > EXTENT) {
            this.addBorderIntersection(3, number(prev.x, p.x, (EXTENT - prev.y) / (p.y - prev.y)));
        }
    }
    addBorderIntersection(index, i) {
        if (!this.borders) {
            this.borders = [
                [
                    Number.MAX_VALUE,
                    -Number.MAX_VALUE
                ],
                [
                    Number.MAX_VALUE,
                    -Number.MAX_VALUE
                ],
                [
                    Number.MAX_VALUE,
                    -Number.MAX_VALUE
                ],
                [
                    Number.MAX_VALUE,
                    -Number.MAX_VALUE
                ]
            ];
        }
        const b = this.borders[index];
        if (i < b[0])
            b[0] = i;
        if (i > b[1])
            b[1] = i;
    }
    processBorderOverlap(p, prev) {
        if (p.x === prev.x) {
            if (p.y === prev.y)
                return;
            // custom defined geojson could have points repeated.
            const index = p.x === 0 ? 0 : 1;
            this.addBorderIntersection(index, prev.y);
            this.addBorderIntersection(index, p.y);
        } else {
            const index = p.y === 0 ? 2 : 3;
            this.addBorderIntersection(index, prev.x);
            this.addBorderIntersection(index, p.x);
        }
    }
    centroid() {
        if (this.accCount === 0) {
            return new Point$2(0, 0);
        }
        return new Point$2(Math.floor(Math.max(0, this.acc.x) / this.accCount), Math.floor(Math.max(0, this.acc.y) / this.accCount));
    }
    intersectsCount() {
        if (!this.borders) {
            return 0;
        }
        return this.borders.reduce((acc, p) => acc + +(p[0] !== Number.MAX_VALUE), 0);
    }
}
function concavity(a, b) {
    return a.x * b.y - a.y * b.x < 0 ? -1 : 1;
}
function tanAngleClamped(angle) {
    return Math.min(TANGENT_CUTOFF, Math.max(-TANGENT_CUTOFF, Math.tan(angle))) / TANGENT_CUTOFF * NORM;
}
function getAngularOffsetFactor(na, nb) {
    const nm = na.add(nb)._unit();
    const cosHalfAngle = clamp(na.x * nm.x + na.y * nm.y, -1, 1);
    const factor = tanAngleClamped(Math.acos(cosHalfAngle)) * concavity(na, nb);
    return factor;
}
const borderCheck = [
    a => {
        return a.x < 0;
    },
    // left
    a => {
        return a.x > EXTENT;
    },
    // right
    a => {
        return a.y < 0;
    },
    // top
    a => {
        return a.y > EXTENT;
    }    // bottom
];
// Checks which region a quad belongs to. A quad belongs to left, right, top, bottom if
// it intersects with the left, right, top, bottom borders of the tile respectively.
// If a quad doesn't intersect any of the borders, it is assumed to be in the "default" region.
// Ids 0, 1, 2, 3 and 4 are denoting, left, right, top, bottom and default regions respectively.
// Note that a quad can also belong to more than one region (e.g. when it intersects with left and right borders).
function getTileRegions(pa, pb, na, maxRadius) {
    const regions = [4];
    if (maxRadius === 0)
        return regions;
    // Approximate the position of the extruded points by using a quad.
    na._mult(maxRadius);
    const c = pa.sub(na);
    const d = pb.sub(na);
    const points = [
        pa,
        pb,
        c,
        d
    ];
    for (let i = 0; i < TILE_REGIONS; i++) {
        for (const point of points) {
            if (borderCheck[i](point)) {
                regions.push(i);
                break;
            }
        }
    }
    return regions;
}
class GroundEffect {
    constructor(options) {
        this.vertexArray = new StructArrayLayout5i10();
        this.indexArray = new StructArrayLayout3ui6();
        const filtered = property => {
            return fillExtrusionGroundDataDrivenProperties.includes(property);
        };
        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom, filtered);
        this._segments = new SegmentVector();
        this.hiddenByLandmarkVertexArray = new StructArrayLayout1ub1();
        this._segmentToGroundQuads = {};
        this._segmentToGroundQuads[0] = [];
        this._segmentToRegionTriCounts = {};
        this._segmentToRegionTriCounts[0] = [
            0,
            0,
            0,
            0,
            0
        ];
        this.regionSegments = {};
        this.regionSegments[4] = new SegmentVector();
    }
    getDefaultSegment() {
        return this.regionSegments[4];
    }
    hasData() {
        return this.vertexArray.length !== 0;
    }
    addData(polyline, bounds, maxRadius, roundedEdges = false) {
        const n = polyline.length;
        if (n > 2) {
            let sid = Math.max(0, this._segments.get().length - 1);
            const numNewVerts = n * 4;
            const numExistingVerts = this.vertexArray.length;
            const numExistingTris = this._segmentToGroundQuads[sid].length * QUAD_TRIS;
            const segment = this._segments._prepareSegment(numNewVerts, numExistingVerts, numExistingTris);
            const newSegmentAdded = sid !== this._segments.get().length - 1;
            if (newSegmentAdded) {
                sid++;
                this._segmentToGroundQuads[sid] = [];
                this._segmentToRegionTriCounts[sid] = [
                    0,
                    0,
                    0,
                    0,
                    0
                ];
            }
            let prevFactor;
            {
                const pa = polyline[n - 1];
                const pb = polyline[0];
                const pc = polyline[1];
                const na = pb.sub(pa)._perp()._unit();
                const nb = pc.sub(pb)._perp()._unit();
                prevFactor = getAngularOffsetFactor(na, nb);
            }
            for (let i = 0; i < n; i++) {
                const j = i === n - 1 ? 0 : i + 1;
                const k = j === n - 1 ? 0 : j + 1;
                const pa = polyline[i];
                const pb = polyline[j];
                const pc = polyline[k];
                const na = pb.sub(pa)._perp()._unit();
                const nb = pc.sub(pb)._perp()._unit();
                const factor = getAngularOffsetFactor(na, nb);
                const a0 = prevFactor;
                const a1 = factor;
                if (isEdgeOutsideBounds(pa, pb, bounds) || roundedEdges && pointOutsideBounds(pa, bounds) && pointOutsideBounds(pb, bounds)) {
                    prevFactor = factor;
                    continue;
                }
                const idx = segment.vertexLength;
                addGroundVertex(this.vertexArray, pa, pb, 1, 1, a0);
                addGroundVertex(this.vertexArray, pa, pb, 1, 0, a0);
                addGroundVertex(this.vertexArray, pa, pb, 0, 1, a1);
                addGroundVertex(this.vertexArray, pa, pb, 0, 0, a1);
                segment.vertexLength += QUAD_VERTS;
                // When a tile belongs to more than one region it needs to be duplicated for that region.
                const regions = getTileRegions(pa, pb, na, maxRadius);
                // Note: mutates na
                for (const rid of regions) {
                    this._segmentToGroundQuads[sid].push({
                        id: idx,
                        region: rid
                    });
                    this._segmentToRegionTriCounts[sid][rid] += QUAD_TRIS;
                    segment.primitiveLength += QUAD_TRIS;
                }
                prevFactor = factor;
            }
        }
    }
    prepareBorderSegments() {
        if (!this.hasData())
            return;
        const segments = this._segments.get();
        // Sort the geometry in this order: left, right, top, bottom and default regions.
        const numSegments = segments.length;
        for (let i = 0; i < numSegments; i++) {
            const groundQuads = this._segmentToGroundQuads[i];
            groundQuads.sort((a, b) => {
                return a.region - b.region;
            });
        }
        // Populate the index array.
        for (let i = 0; i < numSegments; i++) {
            const groundQuads = this._segmentToGroundQuads[i];
            const segment = segments[i];
            const regionTriCounts = this._segmentToRegionTriCounts[i];
            regionTriCounts.reduce((acc, a) => {
                return acc + a;
            }, 0);
            // For each segment create 5 additional segments each representing a region.
            let regionTriCountOffset = 0;
            for (let k = 0; k <= TILE_REGIONS; k++) {
                const triCount = regionTriCounts[k];
                if (triCount !== 0) {
                    let segmentVector = this.regionSegments[k];
                    // Lazy initialise the segment vector. During rendering if no such vector exists
                    // it means that no geometry from this tile intersects the corresponding border.
                    // We therefore can skip the said border to speed up rendering.
                    if (!segmentVector) {
                        segmentVector = this.regionSegments[k] = new SegmentVector();
                    }
                    const nSegment = {
                        vertexOffset: segment.vertexOffset,
                        primitiveOffset: segment.primitiveOffset + regionTriCountOffset,
                        vertexLength: segment.vertexLength,
                        primitiveLength: triCount
                    };
                    segmentVector.get().push(nSegment);
                }
                regionTriCountOffset += triCount;
            }
            for (let j = 0; j < groundQuads.length; j++) {
                const groundQuad = groundQuads[j];
                const idx = groundQuad.id;
                this.indexArray.emplaceBack(idx, idx + 1, idx + 3);
                this.indexArray.emplaceBack(idx, idx + 3, idx + 2);
            }
        }
        // Free up memory as we no longer need these.
        this._segmentToGroundQuads = null;
        this._segmentToRegionTriCounts = null;
        this._segments.destroy();
        this._segments = null;
    }
    addPaintPropertiesData(feature, index, imagePositions, availableImages, canonical, brightness) {
        if (!this.hasData())
            return;
        this.programConfigurations.populatePaintArrays(this.vertexArray.length, feature, index, imagePositions, availableImages, canonical, brightness);
    }
    upload(context) {
        if (!this.hasData())
            return;
        this.vertexBuffer = context.createVertexBuffer(this.vertexArray, fillExtrusionGroundAttributes.members);
        this.indexBuffer = context.createIndexBuffer(this.indexArray);
    }
    uploadPaintProperties(context) {
        if (!this.hasData())
            return;
        this.programConfigurations.upload(context);
    }
    update(states, vtLayer, layers, availableImages, imagePositions, brightness) {
        if (!this.hasData())
            return;
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
    }
    updateHiddenByLandmark(data) {
        if (!this.hasData())
            return;
        const offset = data.groundVertexArrayOffset;
        const vertexArrayBounds = data.groundVertexCount + data.groundVertexArrayOffset;
        if (data.groundVertexCount === 0)
            return;
        const hide = data.flags & HIDDEN_BY_REPLACEMENT ? 1 : 0;
        for (let i = offset; i < vertexArrayBounds; ++i) {
            this.hiddenByLandmarkVertexArray.emplace(i, hide);
        }
        this._needsHiddenByLandmarkUpdate = true;
    }
    uploadHiddenByLandmark(context) {
        if (!this.hasData() || !this._needsHiddenByLandmarkUpdate) {
            return;
        }
        if (!this.hiddenByLandmarkVertexBuffer && this.hiddenByLandmarkVertexArray.length > 0) {
            // Create centroids vertex buffer
            this.hiddenByLandmarkVertexBuffer = context.createVertexBuffer(this.hiddenByLandmarkVertexArray, hiddenByLandmarkAttributes.members, true);
        } else if (this.hiddenByLandmarkVertexBuffer) {
            this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray);
        }
        this._needsHiddenByLandmarkUpdate = false;
    }
    destroy() {
        if (!this.vertexBuffer)
            return;
        this.vertexBuffer.destroy();
        this.indexBuffer.destroy();
        if (this.hiddenByLandmarkVertexBuffer) {
            this.hiddenByLandmarkVertexBuffer.destroy();
        }
        if (this._segments)
            this._segments.destroy();
        this.programConfigurations.destroy();
        for (let i = 0; i <= TILE_REGIONS; i++) {
            const segments = this.regionSegments[i];
            if (segments) {
                segments.destroy();
            }
        }
    }
}
class FillExtrusionBucket {
    // borders / borderDoneWithNeighborZ: 0 - left, 1, right, 2 - top, 3 - bottom
    // cache conversion.
    constructor(options) {
        this.zoom = options.zoom;
        this.canonical = options.canonical;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.hasPattern = false;
        this.edgeRadius = 0;
        this.projection = options.projection;
        this.activeReplacements = [];
        this.replacementUpdateTime = 0;
        this.centroidData = [];
        this.footprintIndices = new StructArrayLayout3ui6();
        this.footprintVertices = new StructArrayLayout2i4();
        this.footprintSegments = [];
        this.layoutVertexArray = new StructArrayLayout4i8();
        this.centroidVertexArray = new FillExtrusionCentroidArray();
        this.indexArray = new StructArrayLayout3ui6();
        const filtered = property => {
            return fillExtrusionDefaultDataDrivenProperties.includes(property);
        };
        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom, filtered);
        this.segments = new SegmentVector();
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.groundEffect = new GroundEffect(options);
        this.maxHeight = 0;
        this.partLookup = {};
    }
    populate(features, options, canonical, tileTransform) {
        this.features = [];
        this.hasPattern = hasPattern('fill-extrusion', this.layers, options);
        this.featuresOnBorder = [];
        this.borderFeatureIndices = [
            [],
            [],
            [],
            []
        ];
        this.borderDoneWithNeighborZ = [
            -1,
            -1,
            -1,
            -1
        ];
        this.tileToMeter = tileToMeter(canonical);
        this.edgeRadius = this.layers[0].layout.get('fill-extrusion-edge-radius') / this.tileToMeter;
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            // $FlowFixMe[method-unbinding]
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const bucketFeature = {
                id,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),
                properties: feature.properties,
                type: feature.type,
                patterns: {}
            };
            const vertexArrayOffset = this.layoutVertexArray.length;
            if (this.hasPattern) {
                this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options));
            } else {
                this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}, options.availableImages, tileTransform, options.brightness);
            }
            options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, vertexArrayOffset);
        }
        this.sortBorders();
        this.groundEffect.prepareBorderSegments();
    }
    addFeatures(options, canonical, imagePositions, availableImages, tileTransform, brightness) {
        for (const feature of this.features) {
            const {geometry} = feature;
            this.addFeature(feature, geometry, feature.index, canonical, imagePositions, availableImages, tileTransform, brightness);
        }
        this.sortBorders();
    }
    update(states, vtLayer, availableImages, imagePositions, brightness) {
        const withStateUpdates = Object.keys(states).length !== 0;
        if (withStateUpdates && !this.stateDependentLayers.length)
            return;
        const layers = withStateUpdates ? this.stateDependentLayers : this.layers;
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, brightness);
        this.groundEffect.update(states, vtLayer, layers, availableImages, imagePositions, brightness);
    }
    isEmpty() {
        return this.layoutVertexArray.length === 0;
    }
    uploadPending() {
        return !this.uploaded || this.programConfigurations.needsUpload || this.groundEffect.programConfigurations.needsUpload;
    }
    upload(context) {
        if (!this.uploaded) {
            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3);
            this.indexBuffer = context.createIndexBuffer(this.indexArray);
            if (this.layoutVertexExtArray) {
                this.layoutVertexExtBuffer = context.createVertexBuffer(this.layoutVertexExtArray, fillExtrusionAttributesExt.members, true);
            }
            this.groundEffect.upload(context);
        }
        this.groundEffect.uploadPaintProperties(context);
        this.programConfigurations.upload(context);
        this.uploaded = true;
    }
    uploadCentroid(context) {
        this.groundEffect.uploadHiddenByLandmark(context);
        if (!this.needsCentroidUpdate) {
            return;
        }
        if (!this.centroidVertexBuffer && this.centroidVertexArray.length > 0) {
            // Create centroids vertex buffer
            this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true);
        } else if (this.centroidVertexBuffer) {
            this.centroidVertexBuffer.updateData(this.centroidVertexArray);
        }
        this.needsCentroidUpdate = false;
    }
    destroy() {
        if (!this.layoutVertexBuffer)
            return;
        this.layoutVertexBuffer.destroy();
        if (this.centroidVertexBuffer) {
            this.centroidVertexBuffer.destroy();
        }
        if (this.layoutVertexExtBuffer) {
            this.layoutVertexExtBuffer.destroy();
        }
        this.groundEffect.destroy();
        this.indexBuffer.destroy();
        this.programConfigurations.destroy();
        this.segments.destroy();
    }
    addFeature(feature, geometry, index, canonical, imagePositions, availableImages, tileTransform, brightness) {
        const floodLightRadius = this.layers[0].paint.get('fill-extrusion-flood-light-ground-radius').evaluate(feature, {});
        const maxRadius = floodLightRadius / this.tileToMeter;
        const tileBounds = [
            new Point$2(0, 0),
            new Point$2(EXTENT, EXTENT)
        ];
        const projection = tileTransform.projection;
        const isGlobe = projection.name === 'globe';
        const isPolygon = vectorTileFeatureTypes[feature.type] === 'Polygon';
        const borderCentroidData = new BorderCentroidData();
        borderCentroidData.centroidDataIndex = this.centroidData.length;
        const centroid = new PartData();
        const base = this.layers[0].paint.get('fill-extrusion-base').evaluate(feature, {}, canonical);
        const onGround = base <= 0;
        const height = this.layers[0].paint.get('fill-extrusion-height').evaluate(feature, {}, canonical);
        centroid.height = height;
        centroid.vertexArrayOffset = this.layoutVertexArray.length;
        centroid.groundVertexArrayOffset = this.groundEffect.vertexArray.length;
        if (isGlobe && !this.layoutVertexExtArray) {
            this.layoutVertexExtArray = new StructArrayLayout6i12();
        }
        const polygons = classifyRings$1(geometry, EARCUT_MAX_RINGS);
        for (let i = polygons.length - 1; i >= 0; i--) {
            const polygon = polygons[i];
            if (polygon.length === 0 || isEntirelyOutside(polygon[0])) {
                polygons.splice(i, 1);
            }
        }
        let clippedPolygons;
        if (isGlobe) {
            // Perform tesselation for polygons of tiles in order to support long planar
            // triangles on the curved surface of the globe. This is done for all polygons
            // regardless of their size in order guarantee identical results on all sides of
            // tile boundaries.
            //
            // The globe is subdivided into a 32x16 grid. The number of subdivisions done
            // for a tile depends on the zoom level. For example tile with z=0 requires 2⁴
            // subdivisions, tile with z=1 2³ etc. The subdivision is done in polar coordinates
            // instead of tile coordinates.
            clippedPolygons = resampleFillExtrusionPolygonsForGlobe(polygons, tileBounds, canonical);
        } else {
            clippedPolygons = [];
            for (const polygon of polygons) {
                clippedPolygons.push({
                    polygon,
                    bounds: tileBounds
                });
            }
        }
        const edgeRadius = isPolygon ? this.edgeRadius : 0;
        const optimiseGround = edgeRadius > 0 && this.zoom < 17;
        const isDuplicate = (coords, a) => {
            if (coords.length === 0)
                return false;
            const b = coords[coords.length - 1];
            return a.x === b.x && a.y === b.y;
        };
        for (const {polygon, bounds} of clippedPolygons) {
            // Only triangulate and draw the area of the feature if it is a polygon
            // Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined
            let topIndex = 0;
            let numVertices = 0;
            for (const ring of polygon) {
                // make sure the ring closes
                if (isPolygon && !ring[0].equals(ring[ring.length - 1]))
                    ring.push(ring[0]);
                numVertices += isPolygon ? ring.length - 1 : ring.length;
            }
            // We use "(isPolygon ? 5 : 4) * numVertices" as an estimate to ensure whether additional segments are needed or not (see SegmentVector.MAX_VERTEX_ARRAY_LENGTH).
            const segment = this.segments.prepareSegment((isPolygon ? 5 : 4) * numVertices, this.layoutVertexArray, this.indexArray);
            if (centroid.footprintSegIdx < 0) {
                centroid.footprintSegIdx = this.footprintSegments.length;
            }
            const fpSegment = new FootprintSegment();
            fpSegment.vertexOffset = this.footprintVertices.length;
            fpSegment.indexOffset = this.footprintIndices.length * 3;
            fpSegment.ringIndices = [];
            if (isPolygon) {
                const flattened = [];
                const holeIndices = [];
                topIndex = segment.vertexLength;
                // First we offset (inset) the top vertices (i.e the vertices that make up the roof).
                for (let r = 0; r < polygon.length; r++) {
                    const ring = polygon[r];
                    if (ring.length && r !== 0) {
                        holeIndices.push(flattened.length / 2);
                    }
                    // Geometry used by ground flood light and AO.
                    const groundPolyline = [];
                    // The following vectors are used to avoid duplicate normal calculations when going over the vertices.
                    let na, nb;
                    {
                        const p0 = ring[0];
                        const p1 = ring[1];
                        na = p1.sub(p0)._perp()._unit();
                    }
                    // Store index to the end of this ring, we substract one because we don't add the last point to the
                    // footprint as it's the same as the first one
                    fpSegment.ringIndices.push(ring.length - 1);
                    for (let i = 1; i < ring.length; i++) {
                        const p1 = ring[i];
                        const p2 = ring[i === ring.length - 1 ? 1 : i + 1];
                        const q = p1.clone();
                        if (edgeRadius) {
                            nb = p2.sub(p1)._perp()._unit();
                            const nm = na.add(nb)._unit();
                            const cosHalfAngle = na.x * nm.x + na.y * nm.y;
                            const offset = edgeRadius * Math.min(4, 1 / cosHalfAngle);
                            q.x += offset * nm.x;
                            q.y += offset * nm.y;
                            q.x = Math.round(q.x);
                            q.y = Math.round(q.y);
                            na = nb;
                        }
                        if (onGround && (edgeRadius === 0 || optimiseGround) && !isDuplicate(groundPolyline, q)) {
                            groundPolyline.push(q);
                        }
                        addVertex$1(this.layoutVertexArray, q.x, q.y, 0, 0, 1, 1, 0);
                        segment.vertexLength++;
                        this.footprintVertices.emplaceBack(p1.x, p1.y);
                        // triangulate as if vertices were not offset to ensure correct triangulation
                        flattened.push(p1.x, p1.y);
                        if (isGlobe) {
                            const array = this.layoutVertexExtArray;
                            const projectedP = projection.projectTilePoint(q.x, q.y, canonical);
                            const n = projection.upVector(canonical, q.x, q.y);
                            addGlobeExtVertex(array, projectedP, n);
                        }
                    }
                    if (onGround && (edgeRadius === 0 || optimiseGround)) {
                        if (groundPolyline.length !== 0 && isDuplicate(groundPolyline, groundPolyline[0])) {
                            groundPolyline.pop();
                        }
                        this.groundEffect.addData(groundPolyline, bounds, maxRadius);
                    }
                }
                const indices = earcut$1(flattened, holeIndices);
                for (let j = 0; j < indices.length; j += 3) {
                    this.footprintIndices.emplaceBack(fpSegment.vertexOffset + indices[j + 0], fpSegment.vertexOffset + indices[j + 1], fpSegment.vertexOffset + indices[j + 2]);
                    // clockwise winding order.
                    this.indexArray.emplaceBack(topIndex + indices[j], topIndex + indices[j + 2], topIndex + indices[j + 1]);
                    segment.primitiveLength++;
                }
                fpSegment.indexCount += indices.length;
                fpSegment.vertexCount += this.footprintVertices.length - fpSegment.vertexOffset;
            }
            for (let r = 0; r < polygon.length; r++) {
                const ring = polygon[r];
                borderCentroidData.startRing(centroid, ring[0]);
                let isPrevCornerConcave = ring.length > 4 && isAOConcaveAngle(ring[ring.length - 2], ring[0], ring[1]);
                let offsetPrev = edgeRadius ? getRoundedEdgeOffset(ring[ring.length - 2], ring[0], ring[1], edgeRadius) : 0;
                // Geometry used by ground flood light and AO.
                const groundPolyline = [];
                let kFirst;
                // The following vectors are used to avoid duplicate normal calculations when going over the vertices.
                let na, nb;
                {
                    const p0 = ring[0];
                    const p1 = ring[1];
                    na = p1.sub(p0)._perp()._unit();
                }
                let cap = true;
                for (let i = 1, edgeDistance = 0; i < ring.length; i++) {
                    let p0 = ring[i - 1];
                    let p1 = ring[i];
                    const p2 = ring[i === ring.length - 1 ? 1 : i + 1];
                    borderCentroidData.appendEdge(centroid, p1, p0);
                    if (isEdgeOutsideBounds(p1, p0, bounds)) {
                        if (edgeRadius) {
                            na = p2.sub(p1)._perp()._unit();
                            cap = !cap;
                        }
                        continue;
                    }
                    const d = p1.sub(p0)._perp();
                    // Given that nz === 0, encode nx / (abs(nx) + abs(ny)) and signs.
                    // This information is sufficient to reconstruct normal vector in vertex shader.
                    const nxRatio = d.x / (Math.abs(d.x) + Math.abs(d.y));
                    const nySign = d.y > 0 ? 1 : 0;
                    const dist = p0.dist(p1);
                    if (edgeDistance + dist > 32768)
                        edgeDistance = 0;
                    // Next offset the vertices along the edges and create a chamfer space between them:
                    // So if we have the following (where 'x' denotes a vertex)
                    // x──────x
                    // |      |
                    // |      |
                    // |      |
                    // |      |
                    // x──────x
                    // we end up with:
                    //  x────x
                    // x      x
                    // |      |
                    // |      |
                    // x      x
                    //  x────x
                    // (drawing isn't exact but hopefully gets the point across).
                    if (edgeRadius) {
                        nb = p2.sub(p1)._perp()._unit();
                        const cosHalfAngle = getCosHalfAngle(na, nb);
                        let offsetNext = _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius);
                        if (isNaN(offsetNext))
                            offsetNext = 0;
                        const nEdge = p1.sub(p0)._unit();
                        p0 = p0.add(nEdge.mult(offsetPrev))._round();
                        p1 = p1.add(nEdge.mult(-offsetNext))._round();
                        offsetPrev = offsetNext;
                        na = nb;
                        if (onGround && this.zoom >= 17) {
                            if (!isDuplicate(groundPolyline, p0))
                                groundPolyline.push(p0);
                            if (!isDuplicate(groundPolyline, p1))
                                groundPolyline.push(p1);
                        }
                    }
                    const k = segment.vertexLength;
                    const isConcaveCorner = ring.length > 4 && isAOConcaveAngle(p0, p1, p2);
                    let encodedEdgeDistance = encodeAOToEdgeDistance(edgeDistance, isPrevCornerConcave, cap);
                    addVertex$1(this.layoutVertexArray, p0.x, p0.y, nxRatio, nySign, 0, 0, encodedEdgeDistance);
                    addVertex$1(this.layoutVertexArray, p0.x, p0.y, nxRatio, nySign, 0, 1, encodedEdgeDistance);
                    edgeDistance += dist;
                    encodedEdgeDistance = encodeAOToEdgeDistance(edgeDistance, isConcaveCorner, !cap);
                    isPrevCornerConcave = isConcaveCorner;
                    addVertex$1(this.layoutVertexArray, p1.x, p1.y, nxRatio, nySign, 0, 0, encodedEdgeDistance);
                    addVertex$1(this.layoutVertexArray, p1.x, p1.y, nxRatio, nySign, 0, 1, encodedEdgeDistance);
                    segment.vertexLength += 4;
                    // ┌──────┐
                    // │ 1  3 │ clockwise winding order.
                    // │      │ Triangle 1: 0 => 1 => 2
                    // │ 0  2 │ Triangle 2: 1 => 3 => 2
                    // └──────┘
                    this.indexArray.emplaceBack(k + 0, k + 1, k + 2);
                    this.indexArray.emplaceBack(k + 1, k + 3, k + 2);
                    segment.primitiveLength += 2;
                    if (edgeRadius) {
                        // Note that in the previous for-loop we start from index 1 to add the top vertices which explains the next line.
                        const t0 = topIndex + (i === 1 ? ring.length - 2 : i - 2);
                        const t1 = i === 1 ? topIndex : t0 + 1;
                        // top chamfer along the side (i.e. the space between the wall and the roof).
                        this.indexArray.emplaceBack(k + 1, t0, k + 3);
                        this.indexArray.emplaceBack(t0, t1, k + 3);
                        segment.primitiveLength += 2;
                        if (kFirst === undefined) {
                            kFirst = k;
                        }
                        // Make sure to fill in the gap in the corner only when both corresponding edges are in tile bounds.
                        if (!isEdgeOutsideBounds(p2, ring[i], bounds)) {
                            const l = i === ring.length - 1 ? kFirst : segment.vertexLength;
                            // vertical side chamfer i.e. the space between consecutive walls.
                            this.indexArray.emplaceBack(k + 2, k + 3, l);
                            this.indexArray.emplaceBack(k + 3, l + 1, l);
                            // top corner where the top(roof) and two sides(walls) meet.
                            this.indexArray.emplaceBack(k + 3, t1, l + 1);
                            segment.primitiveLength += 3;
                        }
                        cap = !cap;
                    }
                    if (isGlobe) {
                        const array = this.layoutVertexExtArray;
                        const projectedP0 = projection.projectTilePoint(p0.x, p0.y, canonical);
                        const projectedP1 = projection.projectTilePoint(p1.x, p1.y, canonical);
                        const n0 = projection.upVector(canonical, p0.x, p0.y);
                        const n1 = projection.upVector(canonical, p1.x, p1.y);
                        addGlobeExtVertex(array, projectedP0, n0);
                        addGlobeExtVertex(array, projectedP0, n0);
                        addGlobeExtVertex(array, projectedP1, n1);
                        addGlobeExtVertex(array, projectedP1, n1);
                    }
                }
                if (isPolygon)
                    topIndex += ring.length - 1;
                if (onGround && edgeRadius && this.zoom >= 17) {
                    if (groundPolyline.length !== 0 && isDuplicate(groundPolyline, groundPolyline[0])) {
                        groundPolyline.pop();
                    }
                    this.groundEffect.addData(groundPolyline, bounds, maxRadius, edgeRadius > 0);
                }
            }
            this.footprintSegments.push(fpSegment);
            ++centroid.footprintSegLen;
        }
        centroid.vertexCount = this.layoutVertexArray.length - centroid.vertexArrayOffset;
        centroid.groundVertexCount = this.groundEffect.vertexArray.length - centroid.groundVertexArrayOffset;
        if (centroid.vertexCount === 0) {
            return;
        }
        // hiddenCentroid {0, 1}: it is initially hidden as borders are processed later.
        centroid.centroidXY = borderCentroidData.borders ? HIDDEN_CENTROID : this.encodeCentroid(borderCentroidData, centroid);
        this.centroidData.push(centroid);
        if (borderCentroidData.borders) {
            this.featuresOnBorder.push(borderCentroidData);
            const borderIndex = this.featuresOnBorder.length - 1;
            for (let i = 0; i < borderCentroidData.borders.length; i++) {
                if (borderCentroidData.borders[i][0] !== Number.MAX_VALUE) {
                    this.borderFeatureIndices[i].push(borderIndex);
                }
            }
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical, brightness);
        this.groundEffect.addPaintPropertiesData(feature, index, imagePositions, availableImages, canonical, brightness);
        // compute maximum height of the bucket
        this.maxHeight = Math.max(this.maxHeight, height);
    }
    sortBorders() {
        for (let i = 0; i < this.borderFeatureIndices.length; i++) {
            const borders = this.borderFeatureIndices[i];
            borders.sort((a, b) => this.featuresOnBorder[a].borders[i][0] - this.featuresOnBorder[b].borders[i][0]);
        }
    }
    // Encoded centroid x and y:
    //     x     y
    // ---------------------------------------------
    //     0     0    Default, no flat roof.
    //     0     1    Hide, used to hide parts of buildings on border while expecting the other side to get loaded
    //    >0     0    Elevation encoded to uint16 word
    //    >0    >0    Encoded centroid position and x & y span
    encodeCentroid(borderCentroidData, data) {
        const c = borderCentroidData.centroid();
        const span = data.span();
        const spanX = Math.min(7, Math.round(span.x * this.tileToMeter / 10));
        const spanY = Math.min(7, Math.round(span.y * this.tileToMeter / 10));
        return new Point$2(clamp(c.x, 1, EXTENT - 1) << 3 | spanX, clamp(c.y, 1, EXTENT - 1) << 3 | spanY);
    }
    showCentroid(borderCentroidData) {
        const c = this.centroidData[borderCentroidData.centroidDataIndex];
        c.flags &= HIDDEN_BY_REPLACEMENT;
        c.centroidXY.x = 0;
        c.centroidXY.y = 0;
        this.writeCentroidToBuffer(c);
    }
    writeCentroidToBuffer(data) {
        this.groundEffect.updateHiddenByLandmark(data);
        const offset = data.vertexArrayOffset;
        const vertexArrayBounds = data.vertexCount + data.vertexArrayOffset;
        const c = data.flags & HIDDEN_BY_REPLACEMENT ? HIDDEN_CENTROID : data.centroidXY;
        // All the vertex data is the same, use the first to exit early if it is not needed to re-write all.
        const firstX = this.centroidVertexArray.geta_centroid_pos0(offset);
        const firstY = this.centroidVertexArray.geta_centroid_pos1(offset);
        if (firstY === c.y && firstX === c.x) {
            return;
        }
        for (let i = offset; i < vertexArrayBounds; ++i) {
            this.centroidVertexArray.emplace(i, c.x, c.y);
        }
        this.needsCentroidUpdate = true;
    }
    createCentroidsBuffer() {
        this.centroidVertexArray.resize(this.layoutVertexArray.length);
        this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);
        for (const centroid of this.centroidData) {
            this.writeCentroidToBuffer(centroid);
        }
    }
    updateReplacement(coord, source) {
        // Replacement has to be re-checked if the source has been updated since last time
        if (source.updateTime === this.replacementUpdateTime) {
            return;
        }
        this.replacementUpdateTime = source.updateTime;
        // Check if replacements have changed
        const newReplacements = source.getReplacementRegionsForTile(coord.toUnwrapped());
        if (regionsEquals(this.activeReplacements, newReplacements)) {
            return;
        }
        this.activeReplacements = newReplacements;
        if (this.centroidVertexArray.length === 0) {
            this.createCentroidsBuffer();
        } else {
            for (const centroid of this.centroidData) {
                centroid.flags &= ~HIDDEN_BY_REPLACEMENT;
            }
        }
        const transformedVertices = [];
        // Hide all centroids that are overlapping with footprints from the replacement source
        for (const region of this.activeReplacements) {
            // Apply slight padding (one unit) to fill extrusion footprints. This reduces false positives where
            // two adjacent lines would be reported overlapping due to limited precision (16 bit) of tile units.
            const padding = Math.pow(2, region.footprintTileId.canonical.z - coord.canonical.z);
            for (const centroid of this.centroidData) {
                if (centroid.flags & HIDDEN_BY_REPLACEMENT) {
                    continue;
                }
                // Perform a quick aabb-aabb check to determine
                // whether a more precise check is required
                if (region.min.x > centroid.max.x || centroid.min.x > region.max.x) {
                    continue;
                } else if (region.min.y > centroid.max.y || centroid.min.y > region.max.y) {
                    continue;
                }
                for (let i = 0; i < centroid.footprintSegLen; i++) {
                    const seg = this.footprintSegments[centroid.footprintSegIdx + i];
                    // Transform vertices to footprint's coordinate space
                    transformedVertices.length = 0;
                    transformFootprintVertices(this.footprintVertices, seg.vertexOffset, seg.vertexCount, region.footprintTileId.canonical, coord.canonical, transformedVertices);
                    if (footprintTrianglesIntersect(region.footprint, transformedVertices, this.footprintIndices.uint16, seg.indexOffset, seg.indexCount, -seg.vertexOffset, -padding)) {
                        centroid.flags |= HIDDEN_BY_REPLACEMENT;
                        break;
                    }
                }
            }
        }
        for (const centroid of this.centroidData) {
            this.writeCentroidToBuffer(centroid);
        }
        this.borderDoneWithNeighborZ = [
            -1,
            -1,
            -1,
            -1
        ];
    }
    footprintContainsPoint(x, y, centroid) {
        let c = false;
        for (let s = 0; s < centroid.footprintSegLen; s++) {
            const seg = this.footprintSegments[centroid.footprintSegIdx + s];
            let startRing = 0;
            for (const endRing of seg.ringIndices) {
                for (let i = startRing, j = endRing + startRing - 1; i < endRing + startRing; j = i++) {
                    const x1 = this.footprintVertices.int16[(i + seg.vertexOffset) * 2 + 0];
                    const y1 = this.footprintVertices.int16[(i + seg.vertexOffset) * 2 + 1];
                    const x2 = this.footprintVertices.int16[(j + seg.vertexOffset) * 2 + 0];
                    const y2 = this.footprintVertices.int16[(j + seg.vertexOffset) * 2 + 1];
                    if (y1 > y !== y2 > y && x < (x2 - x1) * (y - y1) / (y2 - y1) + x1) {
                        c = !c;
                    }
                }
                startRing = endRing;
            }
        }
        return c;
    }
    getHeightAtTileCoord(x, y) {
        let height = Number.NEGATIVE_INFINITY;
        let hidden = true;
        const lookupKey = (x + EXTENT) * 4 * EXTENT + (y + EXTENT);
        if (this.partLookup.hasOwnProperty(lookupKey)) {
            const centroid = this.partLookup[lookupKey];
            return centroid ? {
                height: centroid.height,
                hidden: !!(centroid.flags & HIDDEN_BY_REPLACEMENT)
            } : undefined;
        }
        for (const centroid of this.centroidData) {
            // Perform a quick aabb-aabb check to determine
            // whether a more precise check is required
            if (x > centroid.max.x || centroid.min.x > x || y > centroid.max.y || centroid.min.y > y) {
                continue;
            }
            if (this.footprintContainsPoint(x, y, centroid)) {
                if (centroid && centroid.height > height) {
                    height = centroid.height;
                    this.partLookup[lookupKey] = centroid;
                    hidden = !!(centroid.flags & HIDDEN_BY_REPLACEMENT);
                }
            }
        }
        if (height === Number.NEGATIVE_INFINITY) {
            // nothing found, cache that info too.
            this.partLookup[lookupKey] = undefined;
            return;
        }
        return {
            height,
            hidden
        };
    }
}
function getCosHalfAngle(na, nb) {
    const nm = na.add(nb)._unit();
    const cosHalfAngle = na.x * nm.x + na.y * nm.y;
    return cosHalfAngle;
}
function getRoundedEdgeOffset(p0, p1, p2, edgeRadius) {
    const na = p1.sub(p0)._perp()._unit();
    const nb = p2.sub(p1)._perp()._unit();
    const cosHalfAngle = getCosHalfAngle(na, nb);
    return _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius);
}
function _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius) {
    const sinHalfAngle = Math.sqrt(1 - cosHalfAngle * cosHalfAngle);
    return Math.min(p0.dist(p1) / 3, p1.dist(p2) / 3, edgeRadius * sinHalfAngle / cosHalfAngle);
}
register(FillExtrusionBucket, 'FillExtrusionBucket', {
    omit: [
        'layers',
        'features'
    ]
});
register(PartData, 'PartData');
register(FootprintSegment, 'FootprintSegment');
register(BorderCentroidData, 'BorderCentroidData');
register(GroundEffect, 'GroundEffect');
// Edges that are outside tile bounds are defined in tile across the border.
// Rendering them twice often results with Z-fighting.
// In case of globe and axis aligned bounds, it is also useful to
// discard edges that have the both endpoints outside the same bound.
function isEdgeOutsideBounds(p1, p2, bounds) {
    return p1.x < bounds[0].x && p2.x < bounds[0].x || p1.x > bounds[1].x && p2.x > bounds[1].x || p1.y < bounds[0].y && p2.y < bounds[0].y || p1.y > bounds[1].y && p2.y > bounds[1].y;
}
function pointOutsideBounds(p, bounds) {
    return p.x < bounds[0].x || p.x > bounds[1].x || p.y < bounds[0].y || p.y > bounds[1].y;
}
function isEntirelyOutside(ring) {
    // Discard rings with corners on border if all other vertices are outside: they get defined
    // also in the tile across the border. Eventual zero area rings at border are discarded by classifyRings
    // and there is no need to handle that case here.
    return ring.every(p => p.x <= 0) || ring.every(p => p.x >= EXTENT) || ring.every(p => p.y <= 0) || ring.every(p => p.y >= EXTENT);
}
function isAOConcaveAngle(p2, p1, p3) {
    if (p2.x < 0 || p2.x >= EXTENT || p1.x < 0 || p1.x >= EXTENT || p3.x < 0 || p3.x >= EXTENT) {
        return false;    // angles are not processed for edges that extend over tile borders
    }
    const a = p3.sub(p1);
    const an = a.perp();
    const b = p2.sub(p1);
    const ab = a.x * b.x + a.y * b.y;
    const cosAB = ab / Math.sqrt((a.x * a.x + a.y * a.y) * (b.x * b.x + b.y * b.y));
    const dotProductWithNormal = an.x * b.x + an.y * b.y;
    // Heuristics: don't shade concave angles above 150° (arccos(-0.866)).
    return cosAB > -0.866 && dotProductWithNormal < 0;
}
function encodeAOToEdgeDistance(edgeDistance, isConcaveCorner, edgeStart) {
    // Encode concavity and edge start/end using the least significant bits.
    // Second least significant bit 1 encodes concavity.
    // The least significant bit 1 marks the edge start, 0 for edge end.
    const encodedEdgeDistance = isConcaveCorner ? edgeDistance | 2 : edgeDistance & ~2;
    return edgeStart ? encodedEdgeDistance | 1 : encodedEdgeDistance & ~1;
}
function fillExtrusionHeightLift() {
    // A rectangle covering globe is subdivided into a grid of 32 cells
    // This information can be used to deduce a minimum lift value so that
    // fill extrusions with 0 height will never go below the ground.
    const angle = Math.PI / 32;
    const tanAngle = Math.tan(angle);
    const r = earthRadius;
    return r * Math.sqrt(1 + 2 * tanAngle * tanAngle) - r;
}
// Resamples fill extrusion polygons by subdividing them into 32x16 cells in mercator space.
// The idea is to allow reprojection of large continuous planar shapes on the surface of the globe
function resampleFillExtrusionPolygonsForGlobe(polygons, tileBounds, tileID) {
    const cellCount = 360 / 32;
    const tiles = 1 << tileID.z;
    const leftLng = lngFromMercatorX(tileID.x / tiles);
    const rightLng = lngFromMercatorX((tileID.x + 1) / tiles);
    const topLat = latFromMercatorY(tileID.y / tiles);
    const bottomLat = latFromMercatorY((tileID.y + 1) / tiles);
    const cellCountOnXAxis = Math.ceil((rightLng - leftLng) / cellCount);
    const cellCountOnYAxis = Math.ceil((topLat - bottomLat) / cellCount);
    const splitFn = (axis, min, max) => {
        if (axis === 0) {
            return 0.5 * (min + max);
        } else {
            const maxLat = latFromMercatorY((tileID.y + min / EXTENT) / tiles);
            const minLat = latFromMercatorY((tileID.y + max / EXTENT) / tiles);
            const midLat = 0.5 * (minLat + maxLat);
            return (mercatorYfromLat(midLat) * tiles - tileID.y) * EXTENT;
        }
    };
    return subdividePolygons(polygons, tileBounds, cellCountOnXAxis, cellCountOnYAxis, 1, splitFn);
}
function transformFootprintVertices(vertices, offset, count, footprintId, centroidId, out) {
    const zDiff = Math.pow(2, footprintId.z - centroidId.z);
    for (let i = 0; i < count; i++) {
        let x = vertices.int16[(i + offset) * 2 + 0];
        let y = vertices.int16[(i + offset) * 2 + 1];
        x = (x + centroidId.x * EXTENT) * zDiff - footprintId.x * EXTENT;
        y = (y + centroidId.y * EXTENT) * zDiff - footprintId.y * EXTENT;
        out.push(new Point$2(x, y));
    }
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$4 = new Properties({
    'visibility': new DataConstantProperty(spec['layout_fill-extrusion']['visibility']),
    'fill-extrusion-edge-radius': new DataConstantProperty(spec['layout_fill-extrusion']['fill-extrusion-edge-radius'])
});
const paint$5 = new Properties({
    'fill-extrusion-opacity': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-opacity']),
    'fill-extrusion-color': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-color']),
    'fill-extrusion-translate': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-translate']),
    'fill-extrusion-translate-anchor': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-translate-anchor']),
    'fill-extrusion-pattern': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-pattern']),
    'fill-extrusion-height': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-height']),
    'fill-extrusion-base': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-base']),
    'fill-extrusion-vertical-gradient': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-vertical-gradient']),
    'fill-extrusion-ambient-occlusion-intensity': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-ambient-occlusion-intensity']),
    'fill-extrusion-ambient-occlusion-radius': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-ambient-occlusion-radius']),
    'fill-extrusion-ambient-occlusion-wall-radius': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-ambient-occlusion-wall-radius']),
    'fill-extrusion-ambient-occlusion-ground-radius': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-ambient-occlusion-ground-radius']),
    'fill-extrusion-ambient-occlusion-ground-attenuation': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-ambient-occlusion-ground-attenuation']),
    'fill-extrusion-flood-light-color': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-flood-light-color']),
    'fill-extrusion-flood-light-intensity': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-flood-light-intensity']),
    'fill-extrusion-flood-light-wall-radius': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-flood-light-wall-radius']),
    'fill-extrusion-flood-light-ground-radius': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-flood-light-ground-radius']),
    'fill-extrusion-flood-light-ground-attenuation': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-flood-light-ground-attenuation']),
    'fill-extrusion-vertical-scale': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-vertical-scale']),
    'fill-extrusion-rounded-roof': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-rounded-roof']),
    'fill-extrusion-cutoff-fade-range': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-cutoff-fade-range'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$9 = {
    paint: paint$5,
    layout: layout$4
};

//      
class Point3D extends Point$2 {
    constructor(x, y, z) {
        super(x, y);
        this.z = z;
    }
}
class FillExtrusionStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$9, options);
    }
    createBucket(parameters) {
        return new FillExtrusionBucket(parameters);
    }
    // $FlowFixMe[method-unbinding]
    queryRadius() {
        return translateDistance(this.paint.get('fill-extrusion-translate'));
    }
    is3D() {
        return true;
    }
    hasShadowPass() {
        return true;
    }
    cutoffRange() {
        return this.paint.get('fill-extrusion-cutoff-fade-range');
    }
    canCastShadows() {
        return true;
    }
    getProgramIds() {
        const patternProperty = this.paint.get('fill-extrusion-pattern');
        const image = patternProperty.constantOr(1);
        return [image ? 'fillExtrusionPattern' : 'fillExtrusion'];
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelPosMatrix, elevationHelper, layoutVertexArrayOffset) {
        const translation = tilespaceTranslate(this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), transform.angle, queryGeometry.pixelToTileUnitsFactor);
        const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState);
        const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState);
        const centroid = [
            0,
            0
        ];
        const terrainVisible = elevationHelper && transform.elevation;
        const exaggeration = transform.elevation ? transform.elevation.exaggeration() : 1;
        const bucket = queryGeometry.tile.getBucket(this);
        if (terrainVisible && bucket instanceof FillExtrusionBucket) {
            const centroidVertexArray = bucket.centroidVertexArray;
            // See FillExtrusionBucket#encodeCentroid(), centroid is inserted at vertexOffset + 1
            const centroidOffset = layoutVertexArrayOffset + 1;
            if (centroidOffset < centroidVertexArray.length) {
                centroid[0] = centroidVertexArray.geta_centroid_pos0(centroidOffset);
                centroid[1] = centroidVertexArray.geta_centroid_pos1(centroidOffset);
            }
        }
        // Early exit if fill extrusion is still hidden while waiting for backfill
        const isHidden = centroid[0] === 0 && centroid[1] === 1;
        if (isHidden)
            return false;
        if (transform.projection.name === 'globe') {
            // Fill extrusion geometry has to be resampled so that large planar polygons
            // can be rendered on the curved surface
            const bounds = [
                new Point$2(0, 0),
                new Point$2(EXTENT, EXTENT)
            ];
            const resampledGeometry = resampleFillExtrusionPolygonsForGlobe([geometry], bounds, queryGeometry.tileID.canonical);
            geometry = resampledGeometry.map(clipped => clipped.polygon).flat();
        }
        const demSampler = terrainVisible ? elevationHelper : null;
        const [projectedBase, projectedTop] = projectExtrusion(transform, geometry, base, height, translation, pixelPosMatrix, demSampler, centroid, exaggeration, transform.center.lat, queryGeometry.tileID.canonical);
        const screenQuery = queryGeometry.queryGeometry;
        const projectedQueryGeometry = screenQuery.isPointQuery() ? screenQuery.screenBounds : screenQuery.screenGeometry;
        return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);
    }
}
function dot(a, b) {
    return a.x * b.x + a.y * b.y;
}
function getIntersectionDistance(projectedQueryGeometry, projectedFace) {
    if (projectedQueryGeometry.length === 1) {
        // For point queries calculate the z at which the point intersects the face
        // using barycentric coordinates.
        // Find the barycentric coordinates of the projected point within the first
        // triangle of the face, using only the xy plane. It doesn't matter if the
        // point is outside the first triangle because all the triangles in the face
        // are in the same plane.
        //
        // Check whether points are coincident and use other points if they are.
        let i = 0;
        const a = projectedFace[i++];
        let b;
        while (!b || a.equals(b)) {
            b = projectedFace[i++];
            if (!b)
                return Infinity;
        }
        // Loop until point `c` is not colinear with points `a` and `b`.
        for (; i < projectedFace.length; i++) {
            const c = projectedFace[i];
            const p = projectedQueryGeometry[0];
            const ab = b.sub(a);
            const ac = c.sub(a);
            const ap = p.sub(a);
            const dotABAB = dot(ab, ab);
            const dotABAC = dot(ab, ac);
            const dotACAC = dot(ac, ac);
            const dotAPAB = dot(ap, ab);
            const dotAPAC = dot(ap, ac);
            const denom = dotABAB * dotACAC - dotABAC * dotABAC;
            const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom;
            const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom;
            const u = 1 - v - w;
            // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection.
            const distance = a.z * u + b.z * v + c.z * w;
            if (isFinite(distance))
                return distance;
        }
        return Infinity;
    } else {
        // The counts as closest is less clear when the query is a box. This
        // returns the distance to the nearest point on the face, whether it is
        // within the query or not. It could be more correct to return the
        // distance to the closest point within the query box but this would be
        // more complicated and expensive to calculate with little benefit.
        let closestDistance = Infinity;
        for (const p of projectedFace) {
            closestDistance = Math.min(closestDistance, p.z);
        }
        return closestDistance;
    }
}
function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) {
    let closestDistance = Infinity;
    if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) {
        closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]);
    }
    for (let r = 0; r < projectedTop.length; r++) {
        const ringTop = projectedTop[r];
        const ringBase = projectedBase[r];
        for (let p = 0; p < ringTop.length - 1; p++) {
            const topA = ringTop[p];
            const topB = ringTop[p + 1];
            const baseA = ringBase[p];
            const baseB = ringBase[p + 1];
            const face = [
                topA,
                topB,
                baseB,
                baseA,
                topA
            ];
            if (polygonIntersectsPolygon(projectedQueryGeometry, face)) {
                closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face));
            }
        }
    }
    return closestDistance === Infinity ? false : closestDistance;
}
function projectExtrusion(tr, geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat, tileID) {
    if (tr.projection.name === 'globe') {
        return projectExtrusionGlobe(tr, geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat, tileID);
    } else {
        if (demSampler) {
            return projectExtrusion3D(geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat);
        } else {
            return projectExtrusion2D(geometry, zBase, zTop, translation, m);
        }
    }
}
function projectExtrusionGlobe(tr, geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat, tileID) {
    const projectedBase = [];
    const projectedTop = [];
    const elevationScale = tr.projection.upVectorScale(tileID, tr.center.lat, tr.worldSize).metersToTile;
    const basePoint = [
        0,
        0,
        0,
        1
    ];
    const topPoint = [
        0,
        0,
        0,
        1
    ];
    const setPoint = (point, x, y, z) => {
        point[0] = x;
        point[1] = y;
        point[2] = z;
        point[3] = 1;
    };
    // Fixed "lift" value is added to height so that 0-height fill extrusions wont clip with globe's surface
    const lift = fillExtrusionHeightLift();
    if (zBase > 0) {
        zBase += lift;
    }
    zTop += lift;
    for (const r of geometry) {
        const ringBase = [];
        const ringTop = [];
        for (const p of r) {
            const x = p.x + translation.x;
            const y = p.y + translation.y;
            // Reproject tile coordinate into ecef and apply elevation to correct direction
            const reproj = tr.projection.projectTilePoint(x, y, tileID);
            const dir = tr.projection.upVector(tileID, p.x, p.y);
            let zBasePoint = zBase;
            let zTopPoint = zTop;
            if (demSampler) {
                const offset = getTerrainHeightOffset(x, y, zBase, zTop, demSampler, centroid, exaggeration, lat);
                zBasePoint += offset.base;
                zTopPoint += offset.top;
            }
            if (zBase !== 0) {
                setPoint(basePoint, reproj.x + dir[0] * elevationScale * zBasePoint, reproj.y + dir[1] * elevationScale * zBasePoint, reproj.z + dir[2] * elevationScale * zBasePoint);
            } else {
                setPoint(basePoint, reproj.x, reproj.y, reproj.z);
            }
            setPoint(topPoint, reproj.x + dir[0] * elevationScale * zTopPoint, reproj.y + dir[1] * elevationScale * zTopPoint, reproj.z + dir[2] * elevationScale * zTopPoint);
            vec3_1.transformMat4(basePoint, basePoint, m);
            vec3_1.transformMat4(topPoint, topPoint, m);
            ringBase.push(new Point3D(basePoint[0], basePoint[1], basePoint[2]));
            ringTop.push(new Point3D(topPoint[0], topPoint[1], topPoint[2]));
        }
        projectedBase.push(ringBase);
        projectedTop.push(ringTop);
    }
    return [
        projectedBase,
        projectedTop
    ];
}
/*
 * Project the geometry using matrix `m`. This is essentially doing
 * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication
 * is inlined so that parts of the projection that are the same across
 * different points can only be done once. This produced a measurable
 * performance improvement.
 */
function projectExtrusion2D(geometry, zBase, zTop, translation, m) {
    const projectedBase = [];
    const projectedTop = [];
    const baseXZ = m[8] * zBase;
    const baseYZ = m[9] * zBase;
    const baseZZ = m[10] * zBase;
    const baseWZ = m[11] * zBase;
    const topXZ = m[8] * zTop;
    const topYZ = m[9] * zTop;
    const topZZ = m[10] * zTop;
    const topWZ = m[11] * zTop;
    for (const r of geometry) {
        const ringBase = [];
        const ringTop = [];
        for (const p of r) {
            const x = p.x + translation.x;
            const y = p.y + translation.y;
            const sX = m[0] * x + m[4] * y + m[12];
            const sY = m[1] * x + m[5] * y + m[13];
            const sZ = m[2] * x + m[6] * y + m[14];
            const sW = m[3] * x + m[7] * y + m[15];
            const baseX = sX + baseXZ;
            const baseY = sY + baseYZ;
            const baseZ = sZ + baseZZ;
            const baseW = Math.max(sW + baseWZ, 0.00001);
            const topX = sX + topXZ;
            const topY = sY + topYZ;
            const topZ = sZ + topZZ;
            const topW = Math.max(sW + topWZ, 0.00001);
            ringBase.push(new Point3D(baseX / baseW, baseY / baseW, baseZ / baseW));
            ringTop.push(new Point3D(topX / topW, topY / topW, topZ / topW));
        }
        projectedBase.push(ringBase);
        projectedTop.push(ringTop);
    }
    return [
        projectedBase,
        projectedTop
    ];
}
/*
 * Projects a fill extrusion vertices to screen while accounting for terrain.
 * This and its dependent functions are ported directly from `fill_extrusion.vertex.glsl`
 * with a few co-ordinate space differences.
 *
 * - Matrix `m` projects to screen-pixel space instead of to gl-coordinates (NDC)
 * - Texture querying is performed in texture pixel coordinates instead of  normalized uv coordinates.
 * - Height offset calculation for fill-extrusion-base is offset with -1 instead of -5 to prevent underground picking.
 */
function projectExtrusion3D(geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat) {
    const projectedBase = [];
    const projectedTop = [];
    const v = [
        0,
        0,
        0,
        1
    ];
    for (const r of geometry) {
        const ringBase = [];
        const ringTop = [];
        for (const p of r) {
            const x = p.x + translation.x;
            const y = p.y + translation.y;
            const heightOffset = getTerrainHeightOffset(x, y, zBase, zTop, demSampler, centroid, exaggeration, lat);
            v[0] = x;
            v[1] = y;
            v[2] = heightOffset.base;
            v[3] = 1;
            vec4_1.transformMat4(v, v, m);
            v[3] = Math.max(v[3], 0.00001);
            const base = new Point3D(v[0] / v[3], v[1] / v[3], v[2] / v[3]);
            v[0] = x;
            v[1] = y;
            v[2] = heightOffset.top;
            v[3] = 1;
            vec4_1.transformMat4(v, v, m);
            v[3] = Math.max(v[3], 0.00001);
            const top = new Point3D(v[0] / v[3], v[1] / v[3], v[2] / v[3]);
            ringBase.push(base);
            ringTop.push(top);
        }
        projectedBase.push(ringBase);
        projectedTop.push(ringTop);
    }
    return [
        projectedBase,
        projectedTop
    ];
}
function getTerrainHeightOffset(x, y, zBase, zTop, demSampler, centroid, exaggeration, lat) {
    const ele = exaggeration * demSampler.getElevationAt(x, y, true, true);
    const flatRoof = centroid[0] !== 0;
    const centroidElevation = flatRoof ? centroid[1] === 0 ? exaggeration * elevationFromUint16(centroid[0]) : exaggeration * flatElevation(demSampler, centroid, lat) : ele;
    return {
        base: ele + (zBase === 0) ? -1 : zBase,
        // Use -1 instead of -5 in shader to prevent picking underground
        top: flatRoof ? Math.max(centroidElevation + zTop, ele + zBase + 2) : ele + zTop
    };
}
// Elevation is encoded into unit16 in fill_extrusion_bucket.js FillExtrusionBucket#encodeCentroid
function elevationFromUint16(n) {
    return n / ELEVATION_SCALE - ELEVATION_OFFSET;
}
// Equivalent GPU side function is in _prelude_terrain.vertex.glsl
function flatElevation(demSampler, centroid, lat) {
    // Span and pos are packed two 16 bit uint16 values in fill_extrusion_bucket.js FillExtrusionBucket#encodeCentroid
    // pos is encoded by << by 3 bits thus dividing by 8 performs equivalent of right shifting it back.
    const posX = Math.floor(centroid[0] / 8);
    const posY = Math.floor(centroid[1] / 8);
    // Span is stored in the lower three bits in multiples of 10
    const spanX = 10 * (centroid[0] - posX * 8);
    const spanY = 10 * (centroid[1] - posY * 8);
    // Get height at centroid
    const z = demSampler.getElevationAt(posX, posY, true, true);
    const meterToDEM = demSampler.getMeterToDEM(lat);
    const wX = Math.floor(0.5 * (spanX * meterToDEM - 1));
    const wY = Math.floor(0.5 * (spanY * meterToDEM - 1));
    const posPx = demSampler.tileCoordToPixel(posX, posY);
    const offsetX = 2 * wX + 1;
    const offsetY = 2 * wY + 1;
    const corners = fourSample(demSampler, posPx.x - wX, posPx.y - wY, offsetX, offsetY);
    const diffX = Math.abs(corners[0] - corners[1]);
    const diffY = Math.abs(corners[2] - corners[3]);
    const diffZ = Math.abs(corners[0] - corners[2]);
    const diffW = Math.abs(corners[1] - corners[3]);
    const diffSumX = diffX + diffY;
    const diffSumY = diffZ + diffW;
    const slopeX = Math.min(0.25, meterToDEM * 0.5 * diffSumX / offsetX);
    const slopeY = Math.min(0.25, meterToDEM * 0.5 * diffSumY / offsetY);
    return z + Math.max(slopeX * spanX, slopeY * spanY);
}
function fourSample(demSampler, posX, posY, offsetX, offsetY) {
    return [
        demSampler.getElevationAtPixel(posX, posY, true),
        demSampler.getElevationAtPixel(posX + offsetY, posY, true),
        demSampler.getElevationAtPixel(posX, posY + offsetY, true),
        demSampler.getElevationAtPixel(posX + offsetX, posY + offsetY, true)
    ];
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$3 = new Properties({
    'line-cap': new DataDrivenProperty(spec['layout_line']['line-cap']),
    'line-join': new DataDrivenProperty(spec['layout_line']['line-join']),
    'line-miter-limit': new DataConstantProperty(spec['layout_line']['line-miter-limit']),
    'line-round-limit': new DataConstantProperty(spec['layout_line']['line-round-limit']),
    'line-sort-key': new DataDrivenProperty(spec['layout_line']['line-sort-key']),
    'visibility': new DataConstantProperty(spec['layout_line']['visibility'])
});
const paint$4 = new Properties({
    'line-opacity': new DataDrivenProperty(spec['paint_line']['line-opacity']),
    'line-color': new DataDrivenProperty(spec['paint_line']['line-color']),
    'line-translate': new DataConstantProperty(spec['paint_line']['line-translate']),
    'line-translate-anchor': new DataConstantProperty(spec['paint_line']['line-translate-anchor']),
    'line-width': new DataDrivenProperty(spec['paint_line']['line-width']),
    'line-gap-width': new DataDrivenProperty(spec['paint_line']['line-gap-width']),
    'line-offset': new DataDrivenProperty(spec['paint_line']['line-offset']),
    'line-blur': new DataDrivenProperty(spec['paint_line']['line-blur']),
    'line-dasharray': new DataDrivenProperty(spec['paint_line']['line-dasharray']),
    'line-pattern': new DataDrivenProperty(spec['paint_line']['line-pattern']),
    'line-gradient': new ColorRampProperty(spec['paint_line']['line-gradient']),
    'line-trim-offset': new DataConstantProperty(spec['paint_line']['line-trim-offset']),
    'line-emissive-strength': new DataConstantProperty(spec['paint_line']['line-emissive-strength']),
    'line-border-width': new DataDrivenProperty(spec['paint_line']['line-border-width']),
    'line-border-color': new DataDrivenProperty(spec['paint_line']['line-border-color'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$8 = {
    paint: paint$4,
    layout: layout$3
};

//      
const lineUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_pixels_to_tile_units': new UniformMatrix2f(context),
    'u_device_pixel_ratio': new Uniform1f(context),
    'u_units_to_pixels': new Uniform2f(context),
    'u_dash_image': new Uniform1i(context),
    'u_gradient_image': new Uniform1i(context),
    'u_image_height': new Uniform1f(context),
    'u_texsize': new Uniform2f(context),
    'u_tile_units_to_pixels': new Uniform1f(context),
    'u_alpha_discard_threshold': new Uniform1f(context),
    'u_trim_offset': new Uniform2f(context),
    'u_emissive_strength': new Uniform1f(context)
});
const linePatternUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_texsize': new Uniform2f(context),
    'u_pixels_to_tile_units': new UniformMatrix2f(context),
    'u_device_pixel_ratio': new Uniform1f(context),
    'u_image': new Uniform1i(context),
    'u_units_to_pixels': new Uniform2f(context),
    'u_tile_units_to_pixels': new Uniform1f(context),
    'u_alpha_discard_threshold': new Uniform1f(context)
});
const lineUniformValues = (painter, tile, layer, matrix, imageHeight, pixelRatio, trimOffset) => {
    const transform = painter.transform;
    const pixelsToTileUnits = transform.calculatePixelsToTileUnitsMatrix(tile);
    return {
        'u_matrix': calculateMatrix(painter, tile, layer, matrix),
        'u_pixels_to_tile_units': pixelsToTileUnits,
        'u_device_pixel_ratio': pixelRatio,
        'u_units_to_pixels': [
            1 / transform.pixelsToGLUnits[0],
            1 / transform.pixelsToGLUnits[1]
        ],
        'u_dash_image': 0,
        'u_gradient_image': 1,
        'u_image_height': imageHeight,
        'u_texsize': hasDash(layer) ? tile.lineAtlasTexture.size : [
            0,
            0
        ],
        'u_tile_units_to_pixels': calculateTileRatio(tile, painter.transform),
        'u_alpha_discard_threshold': 0,
        'u_trim_offset': trimOffset,
        'u_emissive_strength': layer.paint.get('line-emissive-strength')
    };
};
const linePatternUniformValues = (painter, tile, layer, matrix, pixelRatio) => {
    const transform = painter.transform;
    return {
        'u_matrix': calculateMatrix(painter, tile, layer, matrix),
        'u_texsize': tile.imageAtlasTexture.size,
        // camera zoom ratio
        'u_pixels_to_tile_units': transform.calculatePixelsToTileUnitsMatrix(tile),
        'u_device_pixel_ratio': pixelRatio,
        'u_image': 0,
        'u_tile_units_to_pixels': calculateTileRatio(tile, transform),
        'u_units_to_pixels': [
            1 / transform.pixelsToGLUnits[0],
            1 / transform.pixelsToGLUnits[1]
        ],
        'u_alpha_discard_threshold': 0
    };
};
function calculateTileRatio(tile, transform) {
    return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);
}
function calculateMatrix(painter, tile, layer, matrix) {
    return painter.translatePosMatrix(matrix ? matrix : tile.tileID.projMatrix, tile, layer.paint.get('line-translate'), layer.paint.get('line-translate-anchor'));
}
const lineDefinesValues = layer => {
    const values = [];
    if (hasDash(layer))
        values.push('RENDER_LINE_DASH');
    if (layer.paint.get('line-gradient'))
        values.push('RENDER_LINE_GRADIENT');
    const trimOffset = layer.paint.get('line-trim-offset');
    if (trimOffset[0] !== 0 || trimOffset[1] !== 0) {
        values.push('RENDER_LINE_TRIM_OFFSET');
    }
    const hasBorder = layer.paint.get('line-border-width').constantOr(1) !== 0;
    if (hasBorder)
        values.push('RENDER_LINE_BORDER');
    return values;
};
function hasDash(layer) {
    const dashPropertyValue = layer.paint.get('line-dasharray').value;
    return dashPropertyValue.value || dashPropertyValue.kind !== 'constant';
}

//      
class LineFloorwidthProperty extends DataDrivenProperty {
    possiblyEvaluate(value, parameters) {
        parameters = new EvaluationParameters(Math.floor(parameters.zoom), {
            now: parameters.now,
            fadeDuration: parameters.fadeDuration,
            transition: parameters.transition
        });
        return super.possiblyEvaluate(value, parameters);
    }
    evaluate(value, globals, feature, featureState) {
        globals = extend$1({}, globals, { zoom: Math.floor(globals.zoom) });
        return super.evaluate(value, globals, feature, featureState);
    }
}
const lineFloorwidthProperty = new LineFloorwidthProperty(properties$8.paint.properties['line-width'].specification);
lineFloorwidthProperty.useIntegerZoom = true;
class LineStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$8, options);
        this.gradientVersion = 0;
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'line-gradient') {
            const expression = this._transitionablePaint._values['line-gradient'].value.expression;
            this.stepInterpolant = expression._styleExpression && expression._styleExpression.expression instanceof Step$1;
            this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER;
        }
    }
    gradientExpression() {
        return this._transitionablePaint._values['line-gradient'].value.expression;
    }
    widthExpression() {
        return this._transitionablePaint._values['line-width'].value.expression;
    }
    recalculate(parameters, availableImages) {
        super.recalculate(parameters, availableImages);
        this.paint._values['line-floorwidth'] = lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters);
    }
    createBucket(parameters) {
        return new LineBucket(parameters);
    }
    getProgramIds() {
        const patternProperty = this.paint.get('line-pattern');
        const image = patternProperty.constantOr(1);
        const programId = image ? 'linePattern' : 'line';
        return [programId];
    }
    getDefaultProgramParams(name, zoom) {
        const definesValues = lineDefinesValues(this);
        return {
            config: new ProgramConfiguration(this, zoom),
            defines: definesValues,
            overrideFog: false
        };
    }
    // $FlowFixMe[method-unbinding]
    queryRadius(bucket) {
        const lineBucket = bucket;
        const width = getLineWidth(getMaximumPaintValue('line-width', this, lineBucket), getMaximumPaintValue('line-gap-width', this, lineBucket));
        const offset = getMaximumPaintValue('line-offset', this, lineBucket);
        return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate'));
    }
    // $FlowFixMe[method-unbinding]
    queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform) {
        if (queryGeometry.queryGeometry.isAboveHorizon)
            return false;
        const translatedPolygon = translate(queryGeometry.tilespaceGeometry, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), transform.angle, queryGeometry.pixelToTileUnitsFactor);
        const halfWidth = queryGeometry.pixelToTileUnitsFactor / 2 * getLineWidth(this.paint.get('line-width').evaluate(feature, featureState), this.paint.get('line-gap-width').evaluate(feature, featureState));
        const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState);
        if (lineOffset) {
            geometry = offsetLine(geometry, lineOffset * queryGeometry.pixelToTileUnitsFactor);
        }
        return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);
    }
    isTileClipped() {
        return true;
    }
}
function getLineWidth(lineWidth, lineGapWidth) {
    if (lineGapWidth > 0) {
        return lineGapWidth + 2 * lineWidth;
    } else {
        return lineWidth;
    }
}
function offsetLine(rings, offset) {
    const newRings = [];
    const zero = new Point$2(0, 0);
    for (let k = 0; k < rings.length; k++) {
        const ring = rings[k];
        const newRing = [];
        for (let i = 0; i < ring.length; i++) {
            const a = ring[i - 1];
            const b = ring[i];
            const c = ring[i + 1];
            const aToB = i === 0 ? zero : b.sub(a)._unit()._perp();
            const bToC = i === ring.length - 1 ? zero : c.sub(b)._unit()._perp();
            const extrude = aToB._add(bToC)._unit();
            const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y;
            extrude._mult(1 / cosHalfAngle);
            newRing.push(extrude._mult(offset)._add(b));
        }
        newRings.push(newRing);
    }
    return newRings;
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$2 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_background']['visibility']) });
const paint$3 = new Properties({
    'background-color': new DataConstantProperty(spec['paint_background']['background-color']),
    'background-pattern': new DataConstantProperty(spec['paint_background']['background-pattern']),
    'background-opacity': new DataConstantProperty(spec['paint_background']['background-opacity']),
    'background-emissive-strength': new DataConstantProperty(spec['paint_background']['background-emissive-strength'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$7 = {
    paint: paint$3,
    layout: layout$2
};

//      
class BackgroundStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$7, options);
    }
    getProgramIds() {
        const image = this.paint.get('background-pattern');
        return [image ? 'backgroundPattern' : 'background'];
    }
    // eslint-disable-next-line no-unused-vars
    getDefaultProgramParams(name, zoom) {
        return { overrideFog: false };
    }
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout$1 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_raster']['visibility']) });
const paint$2 = new Properties({
    'raster-opacity': new DataConstantProperty(spec['paint_raster']['raster-opacity']),
    'raster-color': new ColorRampProperty(spec['paint_raster']['raster-color']),
    'raster-color-mix': new DataConstantProperty(spec['paint_raster']['raster-color-mix']),
    'raster-color-range': new DataConstantProperty(spec['paint_raster']['raster-color-range']),
    'raster-hue-rotate': new DataConstantProperty(spec['paint_raster']['raster-hue-rotate']),
    'raster-brightness-min': new DataConstantProperty(spec['paint_raster']['raster-brightness-min']),
    'raster-brightness-max': new DataConstantProperty(spec['paint_raster']['raster-brightness-max']),
    'raster-saturation': new DataConstantProperty(spec['paint_raster']['raster-saturation']),
    'raster-contrast': new DataConstantProperty(spec['paint_raster']['raster-contrast']),
    'raster-resampling': new DataConstantProperty(spec['paint_raster']['raster-resampling']),
    'raster-fade-duration': new DataConstantProperty(spec['paint_raster']['raster-fade-duration'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$6 = {
    paint: paint$2,
    layout: layout$1
};

//      
// perspective correction for texture mapping, see https://github.com/mapbox/mapbox-gl-js/issues/9158
// adapted from https://math.stackexchange.com/a/339033/48653
function basisToPoints(x1, y1, x2, y2, x3, y3, x4, y4) {
    const m = [
        x1,
        x2,
        x3,
        y1,
        y2,
        y3,
        1,
        1,
        1
    ];
    const s = [
        x4,
        y4,
        1
    ];
    const ma = mat3_1.adjoint([], m);
    const [sx, sy, sz] = vec3_1.transformMat3(s, s, mat3_1.transpose(ma, ma));
    return mat3_1.multiply(m, [
        sx,
        0,
        0,
        0,
        sy,
        0,
        0,
        0,
        sz
    ], m);
}
function getPerspectiveTransform(w, h, x1, y1, x2, y2, x3, y3, x4, y4) {
    const s = basisToPoints(0, 0, w, 0, 0, h, w, h);
    const m = basisToPoints(x1, y1, x2, y2, x3, y3, x4, y4);
    mat3_1.multiply(m, mat3_1.adjoint(s, s), m);
    return [
        m[6] / m[8] * w / EXTENT,
        m[7] / m[8] * h / EXTENT
    ];
}
/**
 * A data source containing an image.
 * See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-image) for detailed documentation of options.
 *
 * @example
 * // add to map
 * map.addSource('some id', {
 *     type: 'image',
 *     url: 'https://www.mapbox.com/images/foo.png',
 *     coordinates: [
 *         [-76.54, 39.18],
 *         [-76.52, 39.18],
 *         [-76.52, 39.17],
 *         [-76.54, 39.17]
 *     ]
 * });
 *
 * // update coordinates
 * const mySource = map.getSource('some id');
 * mySource.setCoordinates([
 *     [-76.54335737228394, 39.18579907229748],
 *     [-76.52803659439087, 39.1838364847587],
 *     [-76.5295386314392, 39.17683392507606],
 *     [-76.54520273208618, 39.17876344106642]
 * ]);
 *
 * // update url and coordinates simultaneously
 * mySource.updateImage({
 *     url: 'https://www.mapbox.com/images/bar.png',
 *     coordinates: [
 *         [-76.54335737228394, 39.18579907229748],
 *         [-76.52803659439087, 39.1838364847587],
 *         [-76.5295386314392, 39.17683392507606],
 *         [-76.54520273208618, 39.17876344106642]
 *     ]
 * });
 *
 * map.removeSource('some id');  // remove
 * @see [Example: Add an image](https://www.mapbox.com/mapbox-gl-js/example/image-on-a-map/)
 * @see [Example: Animate a series of images](https://www.mapbox.com/mapbox-gl-js/example/animate-images/)
 */
class ImageSource extends Evented {
    // $FlowFixMe
    /**
     * @private
     */
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.id = id;
        this.dispatcher = dispatcher;
        this.coordinates = options.coordinates;
        this.type = 'image';
        this.minzoom = 0;
        this.maxzoom = 22;
        this.tileSize = 512;
        this.tiles = {};
        this._loaded = false;
        this.onNorthPole = false;
        this.onSouthPole = false;
        this.setEventedParent(eventedParent);
        this.options = options;
        this._dirty = false;
    }
    load(newCoordinates, loaded) {
        this._loaded = loaded || false;
        this.fire(new Event('dataloading', { dataType: 'source' }));
        this.url = this.options.url;
        if (!this.url) {
            if (newCoordinates) {
                this.coordinates = newCoordinates;
            }
            this._loaded = true;
            this._finishLoading();
            return;
        }
        this._imageRequest = getImage(this.map._requestManager.transformRequest(this.url, ResourceType.Image), (err, image) => {
            this._imageRequest = null;
            this._loaded = true;
            if (err) {
                this.fire(new ErrorEvent(err));
            } else if (image) {
                const {HTMLImageElement} = window$1;
                if (image instanceof HTMLImageElement) {
                    this.image = exported$1.getImageData(image);
                } else {
                    this.image = image;
                }
                this._dirty = true;
                this.width = this.image.width;
                this.height = this.image.height;
                if (newCoordinates) {
                    this.coordinates = newCoordinates;
                }
                this._finishLoading();
            }
        });
    }
    loaded() {
        return this._loaded;
    }
    /**
     * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing,
     * set the `raster-fade-duration` paint property on the raster layer to 0.
     *
     * @param {Object} options Options object.
     * @param {string} [options.url] Required image URL.
     * @param {Array<Array<number>>} [options.coordinates] Four geographical coordinates,
     *     represented as arrays of longitude and latitude numbers, which define the corners of the image.
     *     The coordinates start at the top left corner of the image and proceed in clockwise order.
     *     They do not have to represent a rectangle.
     * @returns {ImageSource} Returns itself to allow for method chaining.
     * @example
     * // Add to an image source to the map with some initial URL and coordinates
     * map.addSource('image_source_id', {
     *     type: 'image',
     *     url: 'https://www.mapbox.com/images/foo.png',
     *     coordinates: [
     *         [-76.54, 39.18],
     *         [-76.52, 39.18],
     *         [-76.52, 39.17],
     *         [-76.54, 39.17]
     *     ]
     * });
     * // Then update the image URL and coordinates
     * imageSource.updateImage({
     *     url: 'https://www.mapbox.com/images/bar.png',
     *     coordinates: [
     *         [-76.5433, 39.1857],
     *         [-76.5280, 39.1838],
     *         [-76.5295, 39.1768],
     *         [-76.5452, 39.1787]
     *     ]
     * });
     */
    updateImage(options) {
        if (!this.image || !options.url) {
            return this;
        }
        if (this._imageRequest && options.url !== this.options.url) {
            this._imageRequest.cancel();
            this._imageRequest = null;
        }
        this.options.url = options.url;
        this.load(options.coordinates, this._loaded);
        return this;
    }
    setTexture(texture) {
        if (!(texture.handle instanceof WebGLTexture)) {
            throw new Error(`The provided handle is not a WebGLTexture instance`);
        }
        const context = this.map.painter.context;
        this.texture = new UserManagedTexture(context, texture.handle);
        this.width = texture.dimensions[0];
        this.height = texture.dimensions[1];
        this._dirty = false;
        this._loaded = true;
        this._finishLoading();
        return this;
    }
    _finishLoading() {
        if (this.map) {
            this.setCoordinates(this.coordinates);
            this.fire(new Event('data', {
                dataType: 'source',
                sourceDataType: 'metadata'
            }));
        }
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.load();
    }
    // $FlowFixMe[method-unbinding]
    onRemove() {
        if (this._imageRequest) {
            this._imageRequest.cancel();
            this._imageRequest = null;
        }
        if (this.texture && !(this.texture instanceof UserManagedTexture))
            this.texture.destroy();
    }
    /**
     * Sets the image's coordinates and re-renders the map.
     *
     * @param {Array<Array<number>>} coordinates Four geographical coordinates,
     *     represented as arrays of longitude and latitude numbers, which define the corners of the image.
     *     The coordinates start at the top left corner of the image and proceed in clockwise order.
     *     They do not have to represent a rectangle.
     * @returns {ImageSource} Returns itself to allow for method chaining.
     * @example
     * // Add an image source to the map with some initial coordinates
     * map.addSource('image_source_id', {
     *     type: 'image',
     *     url: 'https://www.mapbox.com/images/foo.png',
     *     coordinates: [
     *         [-76.54, 39.18],
     *         [-76.52, 39.18],
     *         [-76.52, 39.17],
     *         [-76.54, 39.17]
     *     ]
     * });
     * // Then update the image coordinates
     * imageSource.setCoordinates([
     *     [-76.5433, 39.1857],
     *     [-76.5280, 39.1838],
     *     [-76.5295, 39.1768],
     *     [-76.5452, 39.1787]
     * ]);
     */
    setCoordinates(coordinates) {
        this.coordinates = coordinates;
        this._boundsArray = undefined;
        if (!coordinates.length) {
            return this;
        }
        this.onNorthPole = false;
        this.onSouthPole = false;
        let minLat = coordinates[0][1];
        let maxLat = coordinates[0][1];
        for (const coord of coordinates) {
            if (coord[1] > maxLat) {
                maxLat = coord[1];
            }
            if (coord[1] < minLat) {
                minLat = coord[1];
            }
        }
        const midLat = (maxLat + minLat) / 2;
        if (midLat > MAX_MERCATOR_LATITUDE) {
            this.onNorthPole = true;
        } else if (midLat < -MAX_MERCATOR_LATITUDE) {
            this.onSouthPole = true;
        }
        if (!this.onNorthPole && !this.onSouthPole) {
            // Calculate which mercator tile is suitable for rendering the video in
            // and create a buffer with the corner coordinates. These coordinates
            // may be outside the tile, because raster tiles aren't clipped when rendering.
            // transform the geo coordinates into (zoom 0) tile space coordinates
            // $FlowFixMe[method-unbinding]
            const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat);
            // Compute the coordinates of the tile we'll use to hold this image's
            // render data
            this.tileID = getCoordinatesCenterTileID(cornerCoords);
            // Constrain min/max zoom to our tile's zoom level in order to force
            // SourceCache to request this tile (no matter what the map's zoom
            // level)
            this.minzoom = this.maxzoom = this.tileID.z;
        }
        this.fire(new Event('data', {
            dataType: 'source',
            sourceDataType: 'content'
        }));
        return this;
    }
    // $FlowFixMe[method-unbinding]
    _clear() {
        this._boundsArray = undefined;
    }
    _prepareData(context) {
        for (const w in this.tiles) {
            const tile = this.tiles[w];
            if (tile.state !== 'loaded') {
                tile.state = 'loaded';
                tile.texture = this.texture;
            }
        }
        if (this._boundsArray)
            return;
        const tileTr = tileTransform(this.tileID, this.map.transform.projection);
        // Transform the corner coordinates into the coordinate space of our tile.
        const [tl, tr, br, bl] = this.coordinates.map(coord => {
            const projectedCoord = tileTr.projection.project(coord[0], coord[1]);
            return getTilePoint(tileTr, projectedCoord)._round();
        });
        this.perspectiveTransform = getPerspectiveTransform(this.width, this.height, tl.x, tl.y, tr.x, tr.y, bl.x, bl.y, br.x, br.y);
        const boundsArray = this._boundsArray = new StructArrayLayout4i8();
        boundsArray.emplaceBack(tl.x, tl.y, 0, 0);
        boundsArray.emplaceBack(tr.x, tr.y, EXTENT, 0);
        boundsArray.emplaceBack(bl.x, bl.y, 0, EXTENT);
        boundsArray.emplaceBack(br.x, br.y, EXTENT, EXTENT);
        if (this.boundsBuffer) {
            this.boundsBuffer.destroy();
        }
        this.boundsBuffer = context.createVertexBuffer(boundsArray, boundsAttributes.members);
        this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
    }
    // $FlowFixMe[method-unbinding]
    prepare() {
        const hasTiles = Object.keys(this.tiles).length !== 0;
        if (this.tileID && !hasTiles)
            return;
        const context = this.map.painter.context;
        const gl = context.gl;
        if (this._dirty && !(this.texture instanceof UserManagedTexture)) {
            if (!this.texture) {
                this.texture = new Texture(context, this.image, gl.RGBA);
                this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            } else {
                this.texture.update(this.image);
            }
            this._dirty = false;
        }
        if (!hasTiles)
            return;
        this._prepareData(context);
    }
    loadTile(tile, callback) {
        // We have a single tile -- whoose coordinates are this.tileID -- that
        // covers the image we want to render.  If that's the one being
        // requested, set it up with the image; otherwise, mark the tile as
        // `errored` to indicate that we have no data for it.
        // If the world wraps, we may have multiple "wrapped" copies of the
        // single tile.
        if (this.tileID && this.tileID.equals(tile.tileID.canonical)) {
            this.tiles[String(tile.tileID.wrap)] = tile;
            tile.buckets = {};
            callback(null);
        } else {
            tile.state = 'errored';
            callback(null);
        }
    }
    serialize() {
        return {
            type: 'image',
            url: this.options.url,
            coordinates: this.coordinates
        };
    }
    hasTransition() {
        return false;
    }
}
/**
 * Given a list of coordinates, get their center as a coordinate.
 *
 * @returns centerpoint
 * @private
 */
function getCoordinatesCenterTileID(coords) {
    let minX = Infinity;
    let minY = Infinity;
    let maxX = -Infinity;
    let maxY = -Infinity;
    for (const coord of coords) {
        minX = Math.min(minX, coord.x);
        minY = Math.min(minY, coord.y);
        maxX = Math.max(maxX, coord.x);
        maxY = Math.max(maxY, coord.y);
    }
    const dx = maxX - minX;
    const dy = maxY - minY;
    const dMax = Math.max(dx, dy);
    const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2));
    const tilesAtZoom = Math.pow(2, zoom);
    return new CanonicalTileID(zoom, Math.floor((minX + maxX) / 2 * tilesAtZoom), Math.floor((minY + maxY) / 2 * tilesAtZoom));
}

//      
const COLOR_RAMP_RES = 256;
class RasterStyleLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$6, options);
        this._updateColorRamp();
    }
    getProgramIds() {
        return ['raster'];
    }
    hasColorMap() {
        const expr = this._transitionablePaint._values['raster-color'].value;
        return !!expr.value;
    }
    // $FlowFixMe[method-unbinding]
    isLayerDraped(sourceCache) {
        // Special handling for raster, where the drapeability depends on the source
        // If tile ID is missing, it's rendered outside of the tile pyramid (eg. poles)
        if (sourceCache && sourceCache._source instanceof ImageSource && (sourceCache._source.onNorthPole || sourceCache._source.onSouthPole)) {
            return false;
        }
        return true;
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'raster-color' || name === 'raster-color-range') {
            this._updateColorRamp();
        }
    }
    _updateColorRamp() {
        if (!this.hasColorMap())
            return;
        const expression = this._transitionablePaint._values['raster-color'].value.expression;
        const [start, end] = this._transitionablePaint._values['raster-color-range'].value.expression.evaluate({ zoom: 0 });
        this.colorRamp = renderColorRamp({
            expression,
            evaluationKey: 'rasterValue',
            image: this.colorRamp,
            clips: [{
                    start,
                    end
                }],
            resolution: COLOR_RAMP_RES
        });
        this.colorRampTexture = null;
    }
}

//      
/**
 * Interface for custom style layers. This is a specification for
 * implementers to model: it is not an exported method or class.
 *
 * Custom layers allow a user to render directly into the map's GL context using the map's camera.
 * These layers can be added between any regular layers using {@link Map#addLayer}.
 *
 * Custom layers must have a unique `id` and must have the `type` of `"custom"`.
 * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`.
 * They can trigger rendering using {@link Map#triggerRepaint}
 * and they should appropriately handle {@link Map.event:webglcontextlost} and
 * {@link Map.event:webglcontextrestored}.
 *
 * The `renderingMode` property controls whether the layer is treated as a `"2d"` or `"3d"` map layer. Use:
 * - `"renderingMode": "3d"` to use the depth buffer and share it with other layers
 * - `"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
 *   framebuffer and {@link CustomLayerInterface#prerender}.
 *
 * @interface CustomLayerInterface
 * @property {string} id A unique layer id.
 * @property {string} type The layer's type. Must be `"custom"`.
 * @property {string} renderingMode Either `"2d"` or `"3d"`. Defaults to `"2d"`.
 * @example
 * // Custom layer implemented as ES6 class
 * class NullIslandLayer {
 *     constructor() {
 *         this.id = 'null-island';
 *         this.type = 'custom';
 *         this.renderingMode = '2d';
 *     }
 *
 *     onAdd(map, gl) {
 *         const vertexSource = `
 *         uniform mat4 u_matrix;
 *         void main() {
 *             gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);
 *             gl_PointSize = 20.0;
 *         }`;
 *
 *         const fragmentSource = `
 *         void main() {
 *             gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
 *         }`;
 *
 *         const vertexShader = gl.createShader(gl.VERTEX_SHADER);
 *         gl.shaderSource(vertexShader, vertexSource);
 *         gl.compileShader(vertexShader);
 *         const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
 *         gl.shaderSource(fragmentShader, fragmentSource);
 *         gl.compileShader(fragmentShader);
 *
 *         this.program = gl.createProgram();
 *         gl.attachShader(this.program, vertexShader);
 *         gl.attachShader(this.program, fragmentShader);
 *         gl.linkProgram(this.program);
 *     }
 *
 *     render(gl, matrix) {
 *         gl.useProgram(this.program);
 *         gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix);
 *         gl.drawArrays(gl.POINTS, 0, 1);
 *     }
 * }
 *
 * map.on('load', () => {
 *     map.addLayer(new NullIslandLayer());
 * });
 * @see [Example: Add a custom style layer](https://docs.mapbox.com/mapbox-gl-js/example/custom-style-layer/)
 * @see [Example: Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/)
 */
/**
 * Optional method called when the layer has been added to the Map with {@link Map#addLayer}. This
 * gives the layer a chance to initialize gl resources and register event listeners.
 *
 * @function
 * @memberof CustomLayerInterface
 * @instance
 * @name onAdd
 * @param {Map} map The Map this custom layer was just added to.
 * @param {WebGL2RenderingContext} gl The gl context for the map.
 */
/**
 * Optional method called when the layer has been removed from the Map with {@link Map#removeLayer}. This
 * gives the layer a chance to clean up gl resources and event listeners.
 *
 * @function
 * @memberof CustomLayerInterface
 * @instance
 * @name onRemove
 * @param {Map} map The Map this custom layer was just added to.
 * @param {WebGL2RenderingContext} gl The gl context for the map.
 */
/**
 * Optional method called during a render frame to allow a layer to prepare resources or render into a texture.
 *
 * The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.
 *
 * @function
 * @memberof CustomLayerInterface
 * @instance
 * @name prerender
 * @param {WebGL2RenderingContext} gl The map's gl context.
 * @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator
 * coordinates to gl coordinates. The mercator coordinate `[0, 0]` represents the
 * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When
 * the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z
 * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat
 * can be used to project a `LngLat` to a mercator coordinate.
 */
/**
 * Called during a render frame allowing the layer to draw into the GL context.
 *
 * The layer can assume blending and depth state is set to allow the layer to properly
 * blend and clip other layers. The layer cannot make any other assumptions about the
 * current GL state.
 *
 * If the layer needs to render to a texture, it should implement the `prerender` method
 * to do this and only use the `render` method for drawing directly into the main framebuffer.
 *
 * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects
 * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already
 * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you
 * may want to change the blend function to
 * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`.
 *
 * @function
 * @memberof CustomLayerInterface
 * @instance
 * @name render
 * @param {WebGL2RenderingContext} gl The map's gl context.
 * @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator
 * coordinates to gl coordinates. The spherical mercator coordinate `[0, 0]` represents the
 * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When
 * the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z
 * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat
 * can be used to project a `LngLat` to a mercator coordinate.
 */
function validateCustomStyleLayer(layerObject) {
    const errors = [];
    const id = layerObject.id;
    if (id === undefined) {
        errors.push({ message: `layers.${ id }: missing required property "id"` });
    }
    if (layerObject.render === undefined) {
        errors.push({ message: `layers.${ id }: missing required method "render"` });
    }
    if (layerObject.renderingMode && layerObject.renderingMode !== '2d' && layerObject.renderingMode !== '3d') {
        errors.push({ message: `layers.${ id }: property "renderingMode" must be either "2d" or "3d"` });
    }
    return errors;
}
class CustomStyleLayer extends StyleLayer {
    constructor(implementation) {
        super(implementation, {});
        this.implementation = implementation;
        if (implementation.slot)
            this.slot = implementation.slot;
    }
    is3D() {
        return this.implementation.renderingMode === '3d';
    }
    hasOffscreenPass() {
        return this.implementation.prerender !== undefined;
    }
    // $FlowFixMe[method-unbinding]
    isLayerDraped(_) {
        return this.implementation.renderToTile !== undefined;
    }
    shouldRedrape() {
        return !!this.implementation.shouldRerenderTiles && this.implementation.shouldRerenderTiles();
    }
    recalculate() {
    }
    updateTransitions() {
    }
    hasTransition() {
        return false;
    }
    // $FlowFixMe[incompatible-extend] - CustomStyleLayer is not serializable
    serialize() {
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        if (this.implementation.onAdd) {
            this.implementation.onAdd(map, map.painter.context.gl);
        }
    }
    // $FlowFixMe[method-unbinding]
    onRemove(map) {
        if (this.implementation.onRemove) {
            this.implementation.onRemove(map, map.painter.context.gl);
        }
    }
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const layout = new Properties({ 'visibility': new DataConstantProperty(spec['layout_sky']['visibility']) });
const paint$1 = new Properties({
    'sky-type': new DataConstantProperty(spec['paint_sky']['sky-type']),
    'sky-atmosphere-sun': new DataConstantProperty(spec['paint_sky']['sky-atmosphere-sun']),
    'sky-atmosphere-sun-intensity': new DataConstantProperty(spec['paint_sky']['sky-atmosphere-sun-intensity']),
    'sky-gradient-center': new DataConstantProperty(spec['paint_sky']['sky-gradient-center']),
    'sky-gradient-radius': new DataConstantProperty(spec['paint_sky']['sky-gradient-radius']),
    'sky-gradient': new ColorRampProperty(spec['paint_sky']['sky-gradient']),
    'sky-atmosphere-halo-color': new DataConstantProperty(spec['paint_sky']['sky-atmosphere-halo-color']),
    'sky-atmosphere-color': new DataConstantProperty(spec['paint_sky']['sky-atmosphere-color']),
    'sky-opacity': new DataConstantProperty(spec['paint_sky']['sky-opacity'])
});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$5 = {
    paint: paint$1,
    layout
};

//      
function getCelestialDirection(azimuth, altitude, leftHanded) {
    const up = [
        0,
        0,
        1
    ];
    const rotation = quat_1.identity([]);
    quat_1.rotateY(rotation, rotation, leftHanded ? -degToRad(azimuth) + Math.PI : degToRad(azimuth));
    quat_1.rotateX(rotation, rotation, -degToRad(altitude));
    vec3_1.transformQuat(up, up, rotation);
    return vec3_1.normalize(up, up);
}
class SkyLayer extends StyleLayer {
    constructor(layer, options) {
        super(layer, properties$5, options);
        this._updateColorRamp();
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'sky-gradient') {
            this._updateColorRamp();
        } else if (name === 'sky-atmosphere-sun' || name === 'sky-atmosphere-halo-color' || name === 'sky-atmosphere-color' || name === 'sky-atmosphere-sun-intensity') {
            this._skyboxInvalidated = true;
        }
    }
    _updateColorRamp() {
        const expression = this._transitionablePaint._values['sky-gradient'].value.expression;
        this.colorRamp = renderColorRamp({
            expression,
            evaluationKey: 'skyRadialProgress'
        });
        if (this.colorRampTexture) {
            this.colorRampTexture.destroy();
            this.colorRampTexture = null;
        }
    }
    needsSkyboxCapture(painter) {
        if (!!this._skyboxInvalidated || !this.skyboxTexture || !this.skyboxGeometry) {
            return true;
        }
        if (!this.paint.get('sky-atmosphere-sun')) {
            const lightPosition = painter.style.light.properties.get('position');
            return this._lightPosition.azimuthal !== lightPosition.azimuthal || this._lightPosition.polar !== lightPosition.polar;
        }
        return false;
    }
    getCenter(painter, leftHanded) {
        const type = this.paint.get('sky-type');
        if (type === 'atmosphere') {
            const sunPosition = this.paint.get('sky-atmosphere-sun');
            const useLightPosition = !sunPosition;
            const light = painter.style.light;
            const lightPosition = light.properties.get('position');
            if (useLightPosition && light.properties.get('anchor') === 'viewport') {
                warnOnce('The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly.');
            }
            return useLightPosition ? getCelestialDirection(lightPosition.azimuthal, -lightPosition.polar + 90, leftHanded) : getCelestialDirection(sunPosition[0], -sunPosition[1] + 90, leftHanded);
        }
        const direction = this.paint.get('sky-gradient-center');
        return getCelestialDirection(direction[0], -direction[1] + 90, leftHanded);
    }
    isSky() {
        return true;
    }
    markSkyboxValid(painter) {
        this._skyboxInvalidated = false;
        this._lightPosition = painter.style.light.properties.get('position');
    }
    hasOffscreenPass() {
        return true;
    }
    getProgramIds() {
        const type = this.paint.get('sky-type');
        if (type === 'atmosphere') {
            return [
                'skyboxCapture',
                'skybox'
            ];
        } else if (type === 'gradient') {
            return ['skyboxGradient'];
        }
        return null;
    }
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const paint = new Properties({});
// Note: without adding the explicit type annotation, Flow infers weaker types
// for these objects from their use in the constructor to StyleLayer, as
// {layout?: Properties<...>, paint: Properties<...>}
var properties$4 = { paint };

//      
class SlotStyleLayer extends StyleLayer {
    constructor(layer, _) {
        super(layer, properties$4);
    }
}

//      
const subclasses = {
    circle: CircleStyleLayer,
    heatmap: HeatmapStyleLayer,
    hillshade: HillshadeStyleLayer,
    fill: FillStyleLayer,
    'fill-extrusion': FillExtrusionStyleLayer,
    line: LineStyleLayer,
    symbol: SymbolStyleLayer,
    background: BackgroundStyleLayer,
    raster: RasterStyleLayer,
    sky: SkyLayer,
    slot: SlotStyleLayer,
    model: ModelStyleLayer
};
function createStyleLayer(layer, options) {
    if (layer.type === 'custom') {
        return new CustomStyleLayer(layer);
    } else {
        return new subclasses[layer.type](layer, options);
    }
}

//      
function loadSprite (baseURL, requestManager, callback) {
    let json, image, error;
    const format = exported$1.devicePixelRatio > 1 ? '@2x' : '';
    let jsonRequest = getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), ResourceType.SpriteJSON), (err, data) => {
        jsonRequest = null;
        if (!error) {
            error = err;
            json = data;
            maybeComplete();
        }
    });
    let imageRequest = getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), ResourceType.SpriteImage), (err, img) => {
        imageRequest = null;
        if (!error) {
            error = err;
            image = img;
            maybeComplete();
        }
    });
    function maybeComplete() {
        if (error) {
            callback(error);
        } else if (json && image) {
            const imageData = exported$1.getImageData(image);
            const result = {};
            for (const id in json) {
                const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content} = json[id];
                const data = new RGBAImage({
                    width,
                    height
                });
                RGBAImage.copy(imageData, data, {
                    x,
                    y
                }, {
                    x: 0,
                    y: 0
                }, {
                    width,
                    height
                });
                result[id] = {
                    data,
                    pixelRatio,
                    sdf,
                    stretchX,
                    stretchY,
                    content
                };
            }
            callback(null, result);
        }
    }
    return {
        cancel() {
            if (jsonRequest) {
                jsonRequest.cancel();
                jsonRequest = null;
            }
            if (imageRequest) {
                imageRequest.cancel();
                imageRequest = null;
            }
        }
    };
}

//      
function renderStyleImage(image) {
    const {userImage} = image;
    if (userImage && userImage.render) {
        const updated = userImage.render();
        if (updated) {
            image.data.replace(new Uint8Array(userImage.data.buffer));
            return true;
        }
    }
    return false;
}    /**
 * Interface for dynamically generated style images. This is a specification for
 * implementers to model: it is not an exported method or class.
 *
 * Images implementing this interface can be redrawn for every frame. They can be used to animate
 * icons and patterns or make them respond to user input. Style images can implement a
 * {@link StyleImageInterface#render} method. The method is called every frame and
 * can be used to update the image.
 *
 * @interface StyleImageInterface
 * @property {number} width Width in pixels.
 * @property {number} height Height in pixels.
 * @property {Uint8Array | Uint8ClampedArray} data Byte array representing the image. To ensure space for all four channels in an RGBA color, size must be width × height × 4.
 *
 * @see [Example: Add an animated icon to the map.](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/)
 *
 * @example
 * const flashingSquare = {
 *     width: 64,
 *     height: 64,
 *     data: new Uint8Array(64 * 64 * 4),
 *
 *     onAdd(map) {
 *         this.map = map;
 *     },
 *
 *     render() {
 *         // keep repainting while the icon is on the map
 *         this.map.triggerRepaint();
 *
 *         // alternate between black and white based on the time
 *         const value = Math.round(Date.now() / 1000) % 2 === 0  ? 255 : 0;
 *
 *         // check if image needs to be changed
 *         if (value !== this.previousValue) {
 *             this.previousValue = value;
 *
 *             const bytesPerPixel = 4;
 *             for (let x = 0; x < this.width; x++) {
 *                 for (let y = 0; y < this.height; y++) {
 *                     const offset = (y * this.width + x) * bytesPerPixel;
 *                     this.data[offset + 0] = value;
 *                     this.data[offset + 1] = value;
 *                     this.data[offset + 2] = value;
 *                     this.data[offset + 3] = 255;
 *                 }
 *             }
 *
 *             // return true to indicate that the image changed
 *             return true;
 *         }
 *     }
 * };
 *
 * map.addImage('flashing_square', flashingSquare);
 */
     /**
 * This method is called once before every frame where the icon will be used.
 * The method can optionally update the image's `data` member with a new image.
 *
 * If the method updates the image it must return `true` to commit the change.
 * If the method returns `false` or nothing the image is assumed to not have changed.
 *
 * If updates are infrequent it maybe easier to use {@link Map#updateImage} to update
 * the image instead of implementing this method.
 *
 * @function
 * @memberof StyleImageInterface
 * @instance
 * @name render
 * @return {boolean} `true` if this method updated the image. `false` if the image was not changed.
 */
     /**
 * Optional method called when the layer has been added to the Map with {@link Map#addImage}.
 *
 * @function
 * @memberof StyleImageInterface
 * @instance
 * @name onAdd
 * @param {Map} map The Map this custom layer was just added to.
 */
     /**
 * Optional method called when the icon is removed from the map with {@link Map#removeImage}.
 * This gives the image a chance to clean up resources and event listeners.
 *
 * @function
 * @memberof StyleImageInterface
 * @instance
 * @name onRemove
 */

//      
// When copied into the atlas texture, image data is padded by one pixel on each side. Icon
// images are padded with fully transparent pixels, while pattern images are padded with a
// copy of the image data wrapped from the opposite side. In both cases, this ensures the
// correct behavior of GL_LINEAR texture sampling mode.
const padding = 1;
/*
    ImageManager does three things:

        1. Tracks requests for icon images from tile workers and sends responses when the requests are fulfilled.
        2. Builds a texture atlas for pattern images.
        3. Rerenders renderable images once per frame

    These are disparate responsibilities and should eventually be handled by different classes. When we implement
    data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time
    to refactor this.
*/
class ImageManager extends Evented {
    constructor() {
        super();
        this.images = {};
        this.updatedImages = {};
        this.callbackDispatchedThisFrame = {};
        this.loaded = {};
        this.requestors = [];
        this.patterns = {};
        this.atlasImage = {};
        this.atlasTexture = {};
        this.dirty = true;
    }
    createScope(scope) {
        this.images[scope] = {};
        this.loaded[scope] = false;
        this.updatedImages[scope] = {};
        this.patterns[scope] = {};
        this.callbackDispatchedThisFrame[scope] = {};
        this.atlasImage[scope] = new RGBAImage({
            width: 1,
            height: 1
        });
    }
    isLoaded() {
        for (const scope in this.loaded) {
            if (!this.loaded[scope])
                return false;
        }
        return true;
    }
    setLoaded(loaded, scope) {
        if (this.loaded[scope] === loaded) {
            return;
        }
        this.loaded[scope] = loaded;
        if (loaded) {
            for (const {ids, callback} of this.requestors) {
                this._notify(ids, scope, callback);
            }
            this.requestors = [];
        }
    }
    hasImage(id, scope) {
        return !!this.getImage(id, scope);
    }
    getImage(id, scope) {
        return this.images[scope][id];
    }
    addImage(id, scope, image) {
        if (this._validate(id, image)) {
            this.images[scope][id] = image;
        }
    }
    _validate(id, image) {
        let valid = true;
        if (!this._validateStretch(image.stretchX, image.data && image.data.width)) {
            this.fire(new ErrorEvent(new Error(`Image "${ id }" has invalid "stretchX" value`)));
            valid = false;
        }
        if (!this._validateStretch(image.stretchY, image.data && image.data.height)) {
            this.fire(new ErrorEvent(new Error(`Image "${ id }" has invalid "stretchY" value`)));
            valid = false;
        }
        if (!this._validateContent(image.content, image)) {
            this.fire(new ErrorEvent(new Error(`Image "${ id }" has invalid "content" value`)));
            valid = false;
        }
        return valid;
    }
    _validateStretch(stretch, size) {
        if (!stretch)
            return true;
        let last = 0;
        for (const part of stretch) {
            if (part[0] < last || part[1] < part[0] || size < part[1])
                return false;
            last = part[1];
        }
        return true;
    }
    _validateContent(content, image) {
        if (!content)
            return true;
        if (content.length !== 4)
            return false;
        if (content[0] < 0 || image.data.width < content[0])
            return false;
        if (content[1] < 0 || image.data.height < content[1])
            return false;
        if (content[2] < 0 || image.data.width < content[2])
            return false;
        if (content[3] < 0 || image.data.height < content[3])
            return false;
        if (content[2] < content[0])
            return false;
        if (content[3] < content[1])
            return false;
        return true;
    }
    updateImage(id, scope, image) {
        const oldImage = this.images[scope][id];
        image.version = oldImage.version + 1;
        this.images[scope][id] = image;
        this.updatedImages[scope][id] = true;
    }
    removeImage(id, scope) {
        const image = this.images[scope][id];
        delete this.images[scope][id];
        delete this.patterns[scope][id];
        if (image.userImage && image.userImage.onRemove) {
            image.userImage.onRemove();
        }
    }
    listImages(scope) {
        return Object.keys(this.images[scope]);
    }
    getImages(ids, scope, callback) {
        // If the sprite has been loaded, or if all the icon dependencies are already present
        // (i.e. if they've been added via runtime styling), then notify the requestor immediately.
        // Otherwise, delay notification until the sprite is loaded. At that point, if any of the
        // dependencies are still unavailable, we'll just assume they are permanently missing.
        let hasAllDependencies = true;
        const isLoaded = !!this.loaded[scope];
        if (!isLoaded) {
            for (const id of ids) {
                if (!this.images[scope][id]) {
                    hasAllDependencies = false;
                }
            }
        }
        if (isLoaded || hasAllDependencies) {
            this._notify(ids, scope, callback);
        } else {
            this.requestors.push({
                ids,
                scope,
                callback
            });
        }
    }
    getUpdatedImages(scope) {
        return this.updatedImages[scope];
    }
    _notify(ids, scope, callback) {
        const response = {};
        for (const id of ids) {
            if (!this.images[scope][id]) {
                this.fire(new Event('styleimagemissing', { id }));
            }
            const image = this.images[scope][id];
            if (image) {
                // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred.
                response[id] = {
                    data: image.data.clone(),
                    pixelRatio: image.pixelRatio,
                    sdf: image.sdf,
                    version: image.version,
                    stretchX: image.stretchX,
                    stretchY: image.stretchY,
                    content: image.content,
                    hasRenderCallback: Boolean(image.userImage && image.userImage.render)
                };
            } else {
                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.`);
            }
        }
        callback(null, response);
    }
    // Pattern stuff
    getPixelSize(scope) {
        const {width, height} = this.atlasImage[scope];
        return {
            width,
            height
        };
    }
    getPattern(id, scope) {
        const pattern = this.patterns[scope][id];
        const image = this.getImage(id, scope);
        if (!image) {
            return null;
        }
        if (pattern && pattern.position.version === image.version) {
            return pattern.position;
        }
        if (!pattern) {
            const w = image.data.width + padding * 2;
            const h = image.data.height + padding * 2;
            const bin = {
                w,
                h,
                x: 0,
                y: 0
            };
            const position = new ImagePosition(bin, image);
            this.patterns[scope][id] = {
                bin,
                position
            };
        } else {
            pattern.position.version = image.version;
        }
        this._updatePatternAtlas(scope);
        return this.patterns[scope][id].position;
    }
    bind(context, scope) {
        const gl = context.gl;
        let atlasTexture = this.atlasTexture[scope];
        if (!atlasTexture) {
            atlasTexture = new Texture(context, this.atlasImage[scope], gl.RGBA);
            this.atlasTexture[scope] = atlasTexture;
        } else if (this.dirty) {
            atlasTexture.update(this.atlasImage[scope]);
            this.dirty = false;
        }
        atlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    }
    _updatePatternAtlas(scope) {
        const bins = [];
        for (const id in this.patterns[scope]) {
            bins.push(this.patterns[scope][id].bin);
        }
        const {w, h} = potpack(bins);
        const dst = this.atlasImage[scope];
        dst.resize({
            width: w || 1,
            height: h || 1
        });
        for (const id in this.patterns[scope]) {
            const {bin} = this.patterns[scope][id];
            const x = bin.x + padding;
            const y = bin.y + padding;
            const src = this.images[scope][id].data;
            const w = src.width;
            const h = src.height;
            RGBAImage.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x,
                y
            }, {
                width: w,
                height: h
            });
            // Add 1 pixel wrapped padding on each side of the image.
            RGBAImage.copy(src, dst, {
                x: 0,
                y: h - 1
            }, {
                x,
                y: y - 1
            }, {
                width: w,
                height: 1
            });
            // T
            RGBAImage.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x,
                y: y + h
            }, {
                width: w,
                height: 1
            });
            // B
            RGBAImage.copy(src, dst, {
                x: w - 1,
                y: 0
            }, {
                x: x - 1,
                y
            }, {
                width: 1,
                height: h
            });
            // L
            RGBAImage.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x: x + w,
                y
            }, {
                width: 1,
                height: h
            });    // R
        }
        this.dirty = true;
    }
    beginFrame() {
        for (const scope in this.images) {
            this.callbackDispatchedThisFrame[scope] = {};
        }
    }
    dispatchRenderCallbacks(ids, scope) {
        for (const id of ids) {
            // the callback for the image was already dispatched for a different frame
            if (this.callbackDispatchedThisFrame[scope][id])
                continue;
            this.callbackDispatchedThisFrame[scope][id] = true;
            const image = this.images[scope][id];
            const updated = renderStyleImage(image);
            if (updated) {
                this.updateImage(id, scope, image);
            }
        }
    }
}

//      
const properties$3 = new Properties({
    'anchor': new DataConstantProperty(spec.light.anchor),
    'position': new PositionProperty(spec.light.position),
    'color': new DataConstantProperty(spec.light.color),
    'intensity': new DataConstantProperty(spec.light.intensity)
});
/*
 * Represents the light used to light extruded features.
 * Note that these lights are part of the legacy light API.
 */
class Light extends Evented {
    constructor(lightOptions, id = 'flat') {
        super();
        this._transitionable = new Transitionable(properties$3);
        this.setLight(lightOptions, id);
        this._transitioning = this._transitionable.untransitioned();
    }
    getLight() {
        return this._transitionable.serialize();
    }
    setLight(light, id, options = {}) {
        if (this._validate(validateLight, light, options)) {
            return;
        }
        this._transitionable.setTransitionOrValue(light);
        this.id = id;
    }
    updateTransitions(parameters) {
        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
    }
    hasTransition() {
        return this._transitioning.hasTransition();
    }
    recalculate(parameters) {
        this.properties = this._transitioning.possiblyEvaluate(parameters);
    }
    _validate(validate, value, options) {
        if (options && options.validate === false) {
            return false;
        }
        return emitValidationErrors$1(this, validate.call(validateStyle, extend$1({
            value,
            // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407
            style: {
                glyphs: true,
                sprite: true
            },
            styleSpec: spec
        })));
    }
}

//      
const DrapeRenderMode = {
    deferred: 0,
    elevated: 1
};
const properties$2 = new Properties({
    'source': new DataConstantProperty(spec.terrain.source),
    'exaggeration': new DataConstantProperty(spec.terrain.exaggeration)
});
let Terrain$1 = class Terrain extends Evented {
    constructor(terrainOptions, drapeRenderMode) {
        super();
        this._transitionable = new Transitionable(properties$2);
        this.set(terrainOptions);
        this._transitioning = this._transitionable.untransitioned();
        this.drapeRenderMode = drapeRenderMode;
    }
    setScope(scope) {
        this.scope = scope;
    }
    get() {
        return this._transitionable.serialize();
    }
    set(terrain) {
        this._transitionable.setTransitionOrValue(terrain);
    }
    updateTransitions(parameters) {
        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
    }
    hasTransition() {
        return this._transitioning.hasTransition();
    }
    recalculate(parameters) {
        this.properties = this._transitioning.possiblyEvaluate(parameters);
    }
    getExaggeration(atZoom) {
        return this._transitioning.possiblyEvaluate(new EvaluationParameters(atZoom)).get('exaggeration');
    }
    isZoomDependent() {
        const exaggeration = this._transitionable._values['exaggeration'];
        return exaggeration != null && exaggeration.value != null && exaggeration.value.expression != null && exaggeration.value.expression instanceof ZoomDependentExpression;
    }
};

//      
const FOG_PITCH_START = 45;
const FOG_PITCH_END = 65;
const FOG_SYMBOL_CLIPPING_THRESHOLD = 0.9;
const FOG_OPACITY_THRESHOLD = 0.05;
// Minimum opacity for the fog to be enabled for a tile
// As defined in _prelude_fog.fragment.glsl#fog_opacity
function getFogOpacity(state, depth, pitch, fov) {
    const fogPitchOpacity = smoothstep(FOG_PITCH_START, FOG_PITCH_END, pitch);
    const [start, end] = getFovAdjustedFogRange(state, fov);
    // The output of this function must match _prelude_fog.fragment.glsl
    // For further details, refer to the implementation in the shader code
    const decay = 6;
    const fogRange = (depth - start) / (end - start);
    let falloff = 1 - Math.min(1, Math.exp(-decay * fogRange));
    falloff *= falloff * falloff;
    falloff = Math.min(1, 1.00747 * falloff);
    return falloff * fogPitchOpacity * state.alpha;
}
function getFovAdjustedFogRange(state, fov) {
    // This function computes a shifted fog range so that the appearance is unchanged
    // when the fov changes. We define range=0 starting at the camera position given
    // the default fov. We avoid starting the fog range at the camera center so that
    // ranges aren't generally negative unless the FOV is modified.
    const shift = 0.5 / Math.tan(fov * 0.5);
    return [
        state.range[0] + shift,
        state.range[1] + shift
    ];
}
function getFogOpacityAtTileCoord(state, x, y, z, tileId, transform) {
    const mat = transform.calculateFogTileMatrix(tileId);
    const pos = [
        x,
        y,
        z
    ];
    vec3_1.transformMat4(pos, pos, mat);
    return getFogOpacity(state, vec3_1.length(pos), transform.pitch, transform._fov);
}
function getFogOpacityAtLngLat(state, lngLat, transform) {
    const meters = MercatorCoordinate.fromLngLat(lngLat);
    const elevation = transform.elevation ? transform.elevation.getAtPointOrZero(meters) : 0;
    return getFogOpacityAtMercCoord(state, meters.x, meters.y, elevation, transform);
}
function getFogOpacityAtMercCoord(state, x, y, elevation, transform) {
    const pos = vec3_1.transformMat4([], [
        x,
        y,
        elevation
    ], transform.mercatorFogMatrix);
    return getFogOpacity(state, vec3_1.length(pos), transform.pitch, transform._fov);
}
function getFogOpacityForBounds(state, matrix, x0, y0, x1, y1, transform) {
    const points = [
        [
            x0,
            y0,
            0
        ],
        [
            x1,
            y0,
            0
        ],
        [
            x1,
            y1,
            0
        ],
        [
            x0,
            y1,
            0
        ]
    ];
    let min = Number.MAX_VALUE;
    let max = -Number.MAX_VALUE;
    for (const point of points) {
        const transformedPoint = vec3_1.transformMat4([], point, matrix);
        const distance = vec3_1.length(transformedPoint);
        min = Math.min(min, distance);
        max = Math.max(max, distance);
    }
    return [
        getFogOpacity(state, min, transform.pitch, transform._fov),
        getFogOpacity(state, max, transform.pitch, transform._fov)
    ];
}

//      
const fogProperties = new Properties({
    'range': new DataConstantProperty(spec.fog.range),
    'color': new DataConstantProperty(spec.fog.color),
    'high-color': new DataConstantProperty(spec.fog['high-color']),
    'space-color': new DataConstantProperty(spec.fog['space-color']),
    'horizon-blend': new DataConstantProperty(spec.fog['horizon-blend']),
    'star-intensity': new DataConstantProperty(spec.fog['star-intensity']),
    'vertical-range': new DataConstantProperty(spec.fog['vertical-range'])
});
class Fog extends Evented {
    // Alternate projections do not yet support fog.
    // Hold on to transform so that we know whether a projection is set.
    constructor(fogOptions, transform) {
        super();
        this._transitionable = new Transitionable(fogProperties);
        this.set(fogOptions);
        this._transitioning = this._transitionable.untransitioned();
        this._transform = transform;
    }
    get state() {
        const tr = this._transform;
        const isGlobe = tr.projection.name === 'globe';
        const transitionT = globeToMercatorTransition(tr.zoom);
        const range = this.properties.get('range');
        const globeFixedFogRange = [
            0.5,
            3
        ];
        return {
            range: isGlobe ? [
                number(globeFixedFogRange[0], range[0], transitionT),
                number(globeFixedFogRange[1], range[1], transitionT)
            ] : range,
            horizonBlend: this.properties.get('horizon-blend'),
            alpha: this.properties.get('color').a
        };
    }
    get() {
        return this._transitionable.serialize();
    }
    set(fog, options = {}) {
        if (this._validate(validateFog, fog, options)) {
            return;
        }
        const properties = extend$1({}, fog);
        for (const name of Object.keys(spec.fog)) {
            // Fallback to use default style specification when the properties wasn't set
            if (properties[name] === undefined) {
                properties[name] = spec.fog[name].default;
            }
        }
        this._transitionable.setTransitionOrValue(properties);
    }
    getOpacity(pitch) {
        if (!this._transform.projection.supportsFog)
            return 0;
        const fogColor = this.properties && this.properties.get('color') || 1;
        const isGlobe = this._transform.projection.name === 'globe';
        const pitchFactor = isGlobe ? 1 : smoothstep(FOG_PITCH_START, FOG_PITCH_END, pitch);
        return pitchFactor * fogColor.a;
    }
    getOpacityAtLatLng(lngLat, transform) {
        if (!this._transform.projection.supportsFog)
            return 0;
        return getFogOpacityAtLngLat(this.state, lngLat, transform);
    }
    getOpacityForTile(id) {
        if (!this._transform.projection.supportsFog)
            return [
                1,
                1
            ];
        const fogMatrix = this._transform.calculateFogTileMatrix(id.toUnwrapped());
        return getFogOpacityForBounds(this.state, fogMatrix, 0, 0, EXTENT, EXTENT, this._transform);
    }
    getOpacityForBounds(matrix, x0, y0, x1, y1) {
        if (!this._transform.projection.supportsFog)
            return [
                1,
                1
            ];
        return getFogOpacityForBounds(this.state, matrix, x0, y0, x1, y1, this._transform);
    }
    getFovAdjustedRange(fov) {
        // We can return any arbitrary range because we expect opacity=0 to clean it up
        if (!this._transform.projection.supportsFog)
            return [
                0,
                1
            ];
        return getFovAdjustedFogRange(this.state, fov);
    }
    isVisibleOnFrustum(frustum) {
        if (!this._transform.projection.supportsFog)
            return false;
        // Compute locations where frustum edges intersects with the ground plane
        // and determine if all of these points are closer to the camera than
        // the starting point (near range) of the fog.
        const farPoints = [
            4,
            5,
            6,
            7
        ];
        for (const pointIdx of farPoints) {
            const farPoint = frustum.points[pointIdx];
            let flatPoint;
            if (farPoint[2] >= 0) {
                flatPoint = farPoint;
            } else {
                const nearPoint = frustum.points[pointIdx - 4];
                flatPoint = array(nearPoint, farPoint, nearPoint[2] / (nearPoint[2] - farPoint[2]));
            }
            if (getFogOpacityAtMercCoord(this.state, flatPoint[0], flatPoint[1], 0, this._transform) >= FOG_OPACITY_THRESHOLD) {
                return true;
            }
        }
        return false;
    }
    updateTransitions(parameters) {
        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
    }
    hasTransition() {
        return this._transitioning.hasTransition();
    }
    recalculate(parameters) {
        this.properties = this._transitioning.possiblyEvaluate(parameters);
    }
    _validate(validate, value, options) {
        if (options && options.validate === false) {
            return false;
        }
        return emitValidationErrors$1(this, validate.call(validateStyle, extend$1({
            value,
            style: {
                glyphs: true,
                sprite: true
            },
            styleSpec: spec
        })));
    }
}

//      
/**
 * Invokes the wrapped function in a non-blocking way when trigger() is called. Invocation requests
 * are ignored until the function was actually invoked.
 *
 * @private
 */
class ThrottledInvoker {
    constructor(callback) {
        this._callback = callback;
        this._triggered = false;
        if (typeof MessageChannel !== 'undefined') {
            this._channel = new MessageChannel();
            this._channel.port2.onmessage = () => {
                this._triggered = false;
                this._callback();
            };
        }
    }
    trigger() {
        if (!this._triggered) {
            this._triggered = true;
            if (this._channel) {
                this._channel.port1.postMessage(true);
            } else {
                setTimeout(() => {
                    this._triggered = false;
                    this._callback();
                }, 0);
            }
        }
    }
    remove() {
        this._channel = undefined;
        this._callback = () => {
        };
    }
}

//      
class Scheduler {
    constructor() {
        this.tasks = {};
        this.taskQueue = [];
        bindAll(['process'], this);
        // $FlowFixMe[method-unbinding]
        this.invoker = new ThrottledInvoker(this.process);
        this.nextId = 0;
    }
    add(fn, metadata) {
        const id = this.nextId++;
        const priority = getPriority(metadata);
        if (priority === 0) {
            // Process tasks with priority 0 immediately. Do not yield to the event loop.
            isWorker() ? void 0 : undefined;
            try {
                fn();
            } finally {
            }
            return {
                cancel: () => {
                }
            };
        }
        this.tasks[id] = {
            fn,
            metadata,
            priority,
            id
        };
        this.taskQueue.push(id);
        this.invoker.trigger();
        return {
            cancel: () => {
                delete this.tasks[id];
            }
        };
    }
    process() {
        isWorker() ? void 0 : undefined;
        try {
            this.taskQueue = this.taskQueue.filter(id => !!this.tasks[id]);
            if (!this.taskQueue.length) {
                return;
            }
            const id = this.pick();
            if (id === null)
                return;
            const task = this.tasks[id];
            delete this.tasks[id];
            // Schedule another process call if we know there's more to process _before_ invoking the
            // current task. This is necessary so that processing continues even if the current task
            // doesn't execute successfully.
            if (this.taskQueue.length) {
                this.invoker.trigger();
            }
            if (!task) {
                // If the task ID doesn't have associated task data anymore, it was canceled.
                return;
            }
            task.fn();
        } finally {
        }
    }
    pick() {
        let minIndex = null;
        let minPriority = Infinity;
        for (let i = 0; i < this.taskQueue.length; i++) {
            const id = this.taskQueue[i];
            const task = this.tasks[id];
            if (task.priority < minPriority) {
                minPriority = task.priority;
                minIndex = i;
            }
        }
        if (minIndex === null)
            return null;
        const id = this.taskQueue[minIndex];
        this.taskQueue.splice(minIndex, 1);
        return id;
    }
    remove() {
        this.invoker.remove();
    }
}
function getPriority({type, isSymbolTile, zoom}) {
    zoom = zoom || 0;
    if (type === 'message')
        return 0;
    if (type === 'maybePrepare' && !isSymbolTile)
        return 100 - zoom;
    if (type === 'parseTile' && !isSymbolTile)
        return 200 - zoom;
    if (type === 'parseTile' && isSymbolTile)
        return 300 - zoom;
    if (type === 'maybePrepare' && isSymbolTile)
        return 400 - zoom;
    return 500;
}

//      
/**
 * An implementation of the [Actor design pattern](http://en.wikipedia.org/wiki/Actor_model)
 * that maintains the relationship between asynchronous tasks and the objects
 * that spin them off - in this case, tasks like parsing parts of styles,
 * owned by the styles
 *
 * @param {WebWorker} target
 * @param {WebWorker} parent
 * @param {string|number} mapId A unique identifier for the Map instance using this Actor.
 * @private
 */
class Actor {
    constructor(target, parent, mapId) {
        this.target = target;
        this.parent = parent;
        this.mapId = mapId;
        this.callbacks = {};
        this.cancelCallbacks = {};
        bindAll(['receive'], this);
        // $FlowFixMe[method-unbinding]
        this.target.addEventListener('message', this.receive, false);
        this.scheduler = new Scheduler();
    }
    /**
     * Sends a message from a main-thread map to a Worker or from a Worker back to
     * a main-thread map instance.
     *
     * @param type The name of the target method to invoke or '[source-type].[source-name].name' for a method on a WorkerSource.
     * @param targetMapId A particular mapId to which to send this message.
     * @private
     */
    send(type, data, callback, targetMapId, mustQueue = false, callbackMetadata) {
        // We're using a string ID instead of numbers because they are being used as object keys
        // anyway, and thus stringified implicitly. We use random IDs because an actor may receive
        // message from multiple other actors which could run in different execution context. A
        // linearly increasing ID could produce collisions.
        const id = Math.round(Math.random() * 1000000000000000000).toString(36).substring(0, 10);
        if (callback) {
            callback.metadata = callbackMetadata;
            this.callbacks[id] = callback;
        }
        const buffers = new Set();
        this.target.postMessage({
            id,
            type,
            hasCallback: !!callback,
            targetMapId,
            mustQueue,
            sourceMapId: this.mapId,
            data: serialize(data, buffers)
        }, buffers);
        return {
            cancel: () => {
                if (callback) {
                    // Set the callback to null so that it never fires after the request is aborted.
                    delete this.callbacks[id];
                }
                this.target.postMessage({
                    id,
                    type: '<cancel>',
                    targetMapId,
                    sourceMapId: this.mapId
                });
            }
        };
    }
    receive(message) {
        const data = message.data, id = data.id;
        if (!id) {
            return;
        }
        if (data.targetMapId && this.mapId !== data.targetMapId) {
            return;
        }
        if (data.type === '<cancel>') {
            // Remove the original request from the queue. This is only possible if it
            // hasn't been kicked off yet. The id will remain in the queue, but because
            // there is no associated task, it will be dropped once it's time to execute it.
            const cancel = this.cancelCallbacks[id];
            delete this.cancelCallbacks[id];
            if (cancel) {
                cancel.cancel();
            }
        } else {
            if (data.mustQueue || isWorker()) {
                // for worker tasks that are often cancelled, such as loadTile, store them before actually
                // processing them. This is necessary because we want to keep receiving <cancel> messages.
                // Some tasks may take a while in the worker thread, so before executing the next task
                // in our queue, postMessage preempts this and <cancel> messages can be processed.
                // We're using a MessageChannel object to get throttle the process() flow to one at a time.
                const callback = this.callbacks[id];
                const metadata = callback && callback.metadata || { type: 'message' };
                this.cancelCallbacks[id] = this.scheduler.add(() => this.processTask(id, data), metadata);
            } else {
                // In the main thread, process messages immediately so that other work does not slip in
                // between getting partial data back from workers.
                this.processTask(id, data);
            }
        }
    }
    processTask(id, task) {
        if (task.type === '<response>') {
            // The done() function in the counterpart has been called, and we are now
            // firing the callback in the originating actor, if there is one.
            const callback = this.callbacks[id];
            delete this.callbacks[id];
            if (callback) {
                // If we get a response, but don't have a callback, the request was canceled.
                if (task.error) {
                    callback(deserialize$1(task.error));
                } else {
                    callback(null, deserialize$1(task.data));
                }
            }
        } else {
            const buffers = new Set();
            const done = task.hasCallback ? (err, data) => {
                delete this.cancelCallbacks[id];
                this.target.postMessage({
                    id,
                    type: '<response>',
                    sourceMapId: this.mapId,
                    error: err ? serialize(err) : null,
                    data: serialize(data, buffers)
                }, buffers);
            } : _ => {
            };
            const params = deserialize$1(task.data);
            if (this.parent[task.type]) {
                // task.type == 'loadTile', 'removeTile', etc.
                this.parent[task.type](task.sourceMapId, params, done);
            } else if (this.parent.getWorkerSource) {
                // task.type == sourcetype.method
                const keys = task.type.split('.');
                const scope = this.parent.getWorkerSource(task.sourceMapId, keys[0], params.source, params.scope);
                scope[keys[1]](params, done);
            } else {
                // No function was found.
                done(new Error(`Could not find function ${ task.type }`));
            }
        }
    }
    remove() {
        this.scheduler.remove();
        // $FlowFixMe[method-unbinding]
        this.target.removeEventListener('message', this.receive, false);
    }
}

//      
/**
 * Responsible for sending messages from a {@link Source} to an associated
 * {@link WorkerSource}.
 *
 * @private
 */
class Dispatcher {
    // exposed to allow stubbing in unit tests
    constructor(workerPool, parent) {
        this.workerPool = workerPool;
        this.actors = [];
        this.currentActor = 0;
        this.id = uniqueId();
        const workers = this.workerPool.acquire(this.id);
        for (let i = 0; i < workers.length; i++) {
            const worker = workers[i];
            const actor = new Dispatcher.Actor(worker, parent, this.id);
            actor.name = `Worker ${ i }`;
            this.actors.push(actor);
        }
        // track whether all workers are instantiated and ready to receive messages;
        // used for optimizations on initial map load
        this.ready = false;
        this.broadcast('checkIfReady', null, () => {
            this.ready = true;
        });
    }
    /**
     * Broadcast a message to all Workers.
     * @private
     */
    broadcast(type, data, cb) {
        cb = cb || function () {
        };
        asyncAll(this.actors, (actor, done) => {
            actor.send(type, data, done);
        }, cb);
    }
    /**
     * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion.
     * @returns {Actor} An actor object backed by a web worker for processing messages.
     */
    getActor() {
        this.currentActor = (this.currentActor + 1) % this.actors.length;
        return this.actors[this.currentActor];
    }
    remove() {
        this.actors.forEach(actor => {
            actor.remove();
        });
        this.actors = [];
        this.workerPool.release(this.id);
    }
}
Dispatcher.Actor = Actor;

//      
class Lights extends Evented {
    constructor(options, properties, scope, configOptions) {
        super();
        this.scope = scope;
        this._options = options;
        this.properties = new PossiblyEvaluated(properties);
        this._transitionable = new Transitionable(properties, new Map(configOptions));
        this._transitionable.setTransitionOrValue(options.properties);
        this._transitioning = this._transitionable.untransitioned();
    }
    updateConfig(configOptions) {
        this._transitionable.setTransitionOrValue(this._options.properties, new Map(configOptions));
    }
    updateTransitions(parameters) {
        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
    }
    hasTransition() {
        return this._transitioning.hasTransition();
    }
    recalculate(parameters) {
        this.properties = this._transitioning.possiblyEvaluate(parameters);
    }
    get() {
        this._options.properties = this._transitionable.serialize();
        return this._options;
    }
    set(options, configOptions) {
        this._options = options;
        this._transitionable.setTransitionOrValue(options.properties, configOptions);
    }
    shadowsEnabled() {
        if (!this.properties)
            return false;
        return this.properties.get('cast-shadows') === true;
    }
}

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const properties$1 = new Properties({
    'color': new DataConstantProperty(spec['properties_light_ambient']['color']),
    'intensity': new DataConstantProperty(spec['properties_light_ambient']['intensity'])
});

// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.
//      
/* eslint-disable */
const properties = new Properties({
    'direction': new DirectionProperty(spec['properties_light_directional']['direction']),
    'color': new DataConstantProperty(spec['properties_light_directional']['color']),
    'intensity': new DataConstantProperty(spec['properties_light_directional']['intensity']),
    'cast-shadows': new DataConstantProperty(spec['properties_light_directional']['cast-shadows']),
    'shadow-intensity': new DataConstantProperty(spec['properties_light_directional']['shadow-intensity'])
});

//      
/**
 * A data-class that represents a screenspace query from `Map#queryRenderedFeatures`.
 * All the internal geometries and data are intented to be immutable and read-only.
 * Its lifetime is only for the duration of the query and fixed state of the map while the query is being processed.
 *
 * @class QueryGeometry
 */
class QueryGeometry {
    constructor(screenBounds, cameraPoint, aboveHorizon, transform) {
        this.screenBounds = screenBounds;
        this.cameraPoint = cameraPoint;
        this._screenRaycastCache = {};
        this._cameraRaycastCache = {};
        this.isAboveHorizon = aboveHorizon;
        this.screenGeometry = this.bufferedScreenGeometry(0);
        this.screenGeometryMercator = this._bufferedScreenMercator(0, transform);
    }
    /**
     * Factory method to help contruct an instance  while accounting for current map state.
     *
     * @static
     * @param {(PointLike | [PointLike, PointLike])} geometry The query geometry.
     * @param {Transform} transform The current map transform.
     * @returns {QueryGeometry} An instance of the QueryGeometry class.
     */
    static createFromScreenPoints(geometry, transform) {
        let screenGeometry;
        let aboveHorizon;
        // $FlowFixMe: Flow can't refine that this will be PointLike but we can
        if (geometry instanceof Point$2 || typeof geometry[0] === 'number') {
            // $FlowFixMe
            const pt = Point$2.convert(geometry);
            screenGeometry = [pt];
            aboveHorizon = transform.isPointAboveHorizon(pt);
        } else {
            // $FlowFixMe
            const tl = Point$2.convert(geometry[0]);
            // $FlowFixMe
            const br = Point$2.convert(geometry[1]);
            screenGeometry = [
                tl,
                br
            ];
            aboveHorizon = polygonizeBounds(tl, br).every(p => transform.isPointAboveHorizon(p));
        }
        return new QueryGeometry(screenGeometry, transform.getCameraPoint(), aboveHorizon, transform);
    }
    /**
     * Returns true if the initial query by the user was a single point.
     *
     * @returns {boolean} Returns `true` if the initial query geometry was a single point.
     */
    isPointQuery() {
        return this.screenBounds.length === 1;
    }
    /**
     * Due to data-driven styling features do not uniform size(eg `circle-radius`) and can be offset differntly
     * from their original location(for example with `*-translate`). This means we have to expand our query region for
     * each tile to account for variation in these properties.
     * Each tile calculates a tile level max padding value (in screenspace pixels) when its parsed, this function
     * lets us calculate a buffered version of the screenspace query geometry for each tile.
     *
     * @param {number} buffer The tile padding in screenspace pixels.
     * @returns {Point[]} The buffered query geometry.
     */
    bufferedScreenGeometry(buffer) {
        return polygonizeBounds(this.screenBounds[0], this.screenBounds.length === 1 ? this.screenBounds[0] : this.screenBounds[1], buffer);
    }
    /**
     * When the map is pitched, some of the 3D features that intersect a query will not intersect
     * the query at the surface of the earth. Instead the feature may be closer and only intersect
     * the query because it extrudes into the air.
     *
     * This returns a geometry that is a convex polygon that encompasses the query frustum and the point underneath the camera.
     * Similar to `bufferedScreenGeometry`, buffering is added to account for variation in paint properties.
     *
     * Case 1: point underneath camera is exactly behind query volume
     *              +----------+
     *              |          |
     *              |          |
     *              |          |
     *              +          +
     *               X        X
     *                X      X
     *                 X    X
     *                  X  X
     *                   XX.
     *
     * Case 2: point is behind and to the right
     *              +----------+
     *              |          X
     *              |           X
     *              |           XX
     *              +            X
     *              XXX          XX
     *                 XXXX       X
     *                    XXX     XX
     *                        XX   X
     *                           XXX.
     *
     * Case 3: point is behind and to the left
     *              +----------+
     *             X           |
     *             X           |
     *            XX           |
     *            X            +
     *           X          XXXX
     *          XX       XXX
     *          X    XXXX
     *         X XXXX
     *         XXX.
     *
     * @param {number} buffer The tile padding in screenspace pixels.
     * @returns {Point[]} The buffered query geometry.
     */
    bufferedCameraGeometry(buffer) {
        const min = this.screenBounds[0];
        const max = this.screenBounds.length === 1 ? this.screenBounds[0].add(new Point$2(1, 1)) : this.screenBounds[1];
        const cameraPolygon = polygonizeBounds(min, max, 0, false);
        // Only need to account for point underneath camera if its behind query volume
        if (this.cameraPoint.y > max.y) {
            //case 1: insert point in the middle
            if (this.cameraPoint.x > min.x && this.cameraPoint.x < max.x) {
                cameraPolygon.splice(3, 0, this.cameraPoint);    //case 2: replace btm right point
            } else if (this.cameraPoint.x >= max.x) {
                cameraPolygon[2] = this.cameraPoint;    //case 3: replace btm left point
            } else if (this.cameraPoint.x <= min.x) {
                cameraPolygon[3] = this.cameraPoint;
            }
        }
        return bufferConvexPolygon(cameraPolygon, buffer);
    }
    // Creates a convex polygon in screen coordinates that encompasses the query frustum and
    // the camera location at globe's surface. Camera point can be at any side of the query polygon as
    // opposed to `bufferedCameraGeometry` which restricts the location to underneath the polygon.
    bufferedCameraGeometryGlobe(buffer) {
        const min = this.screenBounds[0];
        const max = this.screenBounds.length === 1 ? this.screenBounds[0].add(new Point$2(1, 1)) : this.screenBounds[1];
        // Padding is added to the query polygon before inclusion of the camera location.
        // Otherwise the buffered (narrow) polygon could penetrate the globe creating a lot of false positives
        const cameraPolygon = polygonizeBounds(min, max, buffer);
        const camPos = this.cameraPoint.clone();
        const column = (camPos.x > min.x) + (camPos.x > max.x);
        const row = (camPos.y > min.y) + (camPos.y > max.y);
        const sector = row * 3 + column;
        switch (sector) {
        case 0:
            // replace top-left point (closed polygon)
            cameraPolygon[0] = camPos;
            cameraPolygon[4] = camPos.clone();
            break;
        case 1:
            // insert point in the middle of top-left and top-right
            cameraPolygon.splice(1, 0, camPos);
            break;
        case 2:
            // replace top-right point
            cameraPolygon[1] = camPos;
            break;
        case 3:
            // insert point in the middle of top-left and bottom-left
            cameraPolygon.splice(4, 0, camPos);
            break;
        case 5:
            // insert point in the middle of top-right and bottom-right
            cameraPolygon.splice(2, 0, camPos);
            break;
        case 6:
            // replace bottom-left point
            cameraPolygon[3] = camPos;
            break;
        case 7:
            // insert point in the middle of bottom-left and bottom-right
            cameraPolygon.splice(3, 0, camPos);
            break;
        case 8:
            // replace bottom-right point
            cameraPolygon[2] = camPos;
            break;
        }
        return cameraPolygon;
    }
    /**
     * Checks if a tile is contained within this query geometry.
     *
     * @param {Tile} tile The tile to check.
     * @param {Transform} transform The current map transform.
     * @param {boolean} use3D A boolean indicating whether to query 3D features.
     * @param {number} cameraWrap A wrap value for offsetting the camera position.
     * @returns {?TilespaceQueryGeometry} Returns `undefined` if the tile does not intersect.
     */
    containsTile(tile, transform, use3D, cameraWrap = 0) {
        // The buffer around the query geometry is applied in screen-space.
        // transform._pixelsPerMercatorPixel is used to compensate any extra scaling applied from the currently active projection.
        // Floating point errors when projecting into tilespace could leave a feature
        // outside the query volume even if it looks like it overlaps visually, a 1px bias value overcomes that.
        const bias = 1;
        const padding = tile.queryPadding / transform._pixelsPerMercatorPixel + bias;
        const cachedQuery = use3D ? this._bufferedCameraMercator(padding, transform) : this._bufferedScreenMercator(padding, transform);
        let wrap = tile.tileID.wrap + (cachedQuery.unwrapped ? cameraWrap : 0);
        const geometryForTileCheck = cachedQuery.polygon.map(p => getTilePoint(tile.tileTransform, p, wrap));
        if (!polygonIntersectsBox(geometryForTileCheck, 0, 0, EXTENT, EXTENT)) {
            return undefined;
        }
        wrap = tile.tileID.wrap + (this.screenGeometryMercator.unwrapped ? cameraWrap : 0);
        const tilespaceVec3s = this.screenGeometryMercator.polygon.map(p => getTileVec3(tile.tileTransform, p, wrap));
        const tilespaceGeometry = tilespaceVec3s.map(v => new Point$2(v[0], v[1]));
        const cameraMercator = transform.getFreeCameraOptions().position || new MercatorCoordinate(0, 0, 0);
        const tilespaceCameraPosition = getTileVec3(tile.tileTransform, cameraMercator, wrap);
        const tilespaceRays = tilespaceVec3s.map(tileVec => {
            const dir = vec3_1.sub(tileVec, tileVec, tilespaceCameraPosition);
            vec3_1.normalize(dir, dir);
            return new Ray(tilespaceCameraPosition, dir);
        });
        const pixelToTileUnitsFactor = pixelsToTileUnits(tile, 1, transform.zoom) * transform._pixelsPerMercatorPixel;
        return {
            queryGeometry: this,
            tilespaceGeometry,
            tilespaceRays,
            bufferedTilespaceGeometry: geometryForTileCheck,
            bufferedTilespaceBounds: clampBoundsToTileExtents(getBounds(geometryForTileCheck)),
            tile,
            tileID: tile.tileID,
            pixelToTileUnitsFactor
        };
    }
    /**
     * These methods add caching on top of the terrain raycasting provided by `Transform#pointCoordinate3d`.
     * Tiles come with different values of padding, however its very likely that multiple tiles share the same value of padding
     * based on the style. In that case we want to reuse the result from a previously computed terrain raycast.
     */
    _bufferedScreenMercator(padding, transform) {
        const key = cacheKey(padding);
        if (this._screenRaycastCache[key]) {
            return this._screenRaycastCache[key];
        } else {
            let poly;
            if (transform.projection.name === 'globe') {
                poly = this._projectAndResample(this.bufferedScreenGeometry(padding), transform);
            } else {
                poly = {
                    polygon: this.bufferedScreenGeometry(padding).map(p => transform.pointCoordinate3D(p)),
                    unwrapped: true
                };
            }
            this._screenRaycastCache[key] = poly;
            return poly;
        }
    }
    _bufferedCameraMercator(padding, transform) {
        const key = cacheKey(padding);
        if (this._cameraRaycastCache[key]) {
            return this._cameraRaycastCache[key];
        } else {
            let poly;
            if (transform.projection.name === 'globe') {
                poly = this._projectAndResample(this.bufferedCameraGeometryGlobe(padding), transform);
            } else {
                poly = {
                    polygon: this.bufferedCameraGeometry(padding).map(p => transform.pointCoordinate3D(p)),
                    unwrapped: true
                };
            }
            this._cameraRaycastCache[key] = poly;
            return poly;
        }
    }
    _projectAndResample(polygon, transform) {
        // Handle a special case where either north or south pole is inside the query polygon
        const polePolygon = projectPolygonCoveringPoles(polygon, transform);
        if (polePolygon) {
            return polePolygon;
        }
        // Resample the polygon by adding intermediate points so that straight lines of the shape
        // are correctly projected on the surface of the globe.
        const resampled = unwrapQueryPolygon(resamplePolygon(polygon, transform).map(p => new Point$2(wrap(p.x), p.y)), transform);
        return {
            polygon: resampled.polygon.map(p => new MercatorCoordinate(p.x, p.y)),
            unwrapped: resampled.unwrapped
        };
    }
}
// Checks whether the provided polygon is crossing the antimeridian line and unwraps it if necessary.
// The resulting polygon is continuous
function unwrapQueryPolygon(polygon, tr) {
    let unwrapped = false;
    // Traverse edges of the polygon and unwrap vertices that are crossing the antimeridian.
    let maxX = -Infinity;
    let startEdge = 0;
    for (let e = 0; e < polygon.length - 1; e++) {
        if (polygon[e].x > maxX) {
            maxX = polygon[e].x;
            startEdge = e;
        }
    }
    for (let i = 0; i < polygon.length - 1; i++) {
        const edge = (startEdge + i) % (polygon.length - 1);
        const a = polygon[edge];
        const b = polygon[edge + 1];
        if (Math.abs(a.x - b.x) > 0.5) {
            // A straight line drawn on the globe can't have longer length than 0.5 on the x-axis
            // without crossing the antimeridian
            if (a.x < b.x) {
                a.x += 1;
                if (edge === 0) {
                    // First and last points are duplicate for closed polygons
                    polygon[polygon.length - 1].x += 1;
                }
            } else {
                b.x += 1;
                if (edge + 1 === polygon.length - 1) {
                    polygon[0].x += 1;
                }
            }
            unwrapped = true;
        }
    }
    const cameraX = mercatorXfromLng(tr.center.lng);
    if (unwrapped && cameraX < Math.abs(cameraX - 1)) {
        polygon.forEach(p => {
            p.x -= 1;
        });
    }
    return {
        polygon,
        unwrapped
    };
}
// Special function for handling scenarios where one of the poles is inside the query polygon.
// Finding projection of these kind of polygons is more involving as projecting just the corners will
// produce a degenerate (self-intersecting, non-continuous, etc.) polygon in mercator coordinates
function projectPolygonCoveringPoles(polygon, tr) {
    const matrix = mat4_1.multiply([], tr.pixelMatrix, tr.globeMatrix);
    // Transform north and south pole coordinates to the screen to see if they're
    // inside the query polygon
    const northPole = [
        0,
        -GLOBE_RADIUS,
        0,
        1
    ];
    const southPole = [
        0,
        GLOBE_RADIUS,
        0,
        1
    ];
    const center = [
        0,
        0,
        0,
        1
    ];
    vec4_1.transformMat4(northPole, northPole, matrix);
    vec4_1.transformMat4(southPole, southPole, matrix);
    vec4_1.transformMat4(center, center, matrix);
    const screenNp = new Point$2(northPole[0] / northPole[3], northPole[1] / northPole[3]);
    const screenSp = new Point$2(southPole[0] / southPole[3], southPole[1] / southPole[3]);
    const containsNp = polygonContainsPoint(polygon, screenNp) && northPole[3] < center[3];
    const containsSp = polygonContainsPoint(polygon, screenSp) && southPole[3] < center[3];
    if (!containsNp && !containsSp) {
        return null;
    }
    // Project corner points of the polygon and traverse the ring to find the edge that's
    // crossing the zero longitude border.
    const result = findEdgeCrossingAntimeridian(polygon, tr, containsNp ? -1 : 1);
    if (!result) {
        return null;
    }
    // Start constructing the new polygon by resampling edges until the crossing edge
    const {idx, t} = result;
    let partA = idx > 1 ? resamplePolygon(polygon.slice(0, idx), tr) : [];
    let partB = idx < polygon.length ? resamplePolygon(polygon.slice(idx), tr) : [];
    partA = partA.map(p => new Point$2(wrap(p.x), p.y));
    partB = partB.map(p => new Point$2(wrap(p.x), p.y));
    // Resample first section of the ring (up to the edge that crosses the 0-line)
    const resampled = [...partA];
    if (resampled.length === 0) {
        resampled.push(partB[partB.length - 1]);
    }
    // Find location of the crossing by interpolating mercator coordinates.
    // This will produce slightly off result as the crossing edge is not actually
    // linear on the globe.
    const a = resampled[resampled.length - 1];
    const b = partB.length === 0 ? partA[0] : partB[0];
    const intersectionY = number(a.y, b.y, t);
    let mid;
    if (containsNp) {
        mid = [
            new Point$2(0, intersectionY),
            new Point$2(0, 0),
            new Point$2(1, 0),
            new Point$2(1, intersectionY)
        ];
    } else {
        mid = [
            new Point$2(1, intersectionY),
            new Point$2(1, 1),
            new Point$2(0, 1),
            new Point$2(0, intersectionY)
        ];
    }
    resampled.push(...mid);
    // Resample to the second section of the ring
    if (partB.length === 0) {
        resampled.push(partA[0]);
    } else {
        resampled.push(...partB);
    }
    return {
        polygon: resampled.map(p => new MercatorCoordinate(p.x, p.y)),
        unwrapped: false
    };
}
function resamplePolygon(polygon, transform) {
    // Choose a tolerance value for the resampling logic that produces sufficiently
    // accurate polygons without creating too many points. The value 1 / 256 was chosen
    // based on empirical testing
    const tolerance = 1 / 256;
    return resample$1(polygon, p => {
        const mc = transform.pointCoordinate3D(p);
        p.x = mc.x;
        p.y = mc.y;
    }, tolerance);
}
function wrap(mercatorX) {
    return mercatorX < 0 ? 1 + mercatorX % 1 : mercatorX % 1;
}
function findEdgeCrossingAntimeridian(polygon, tr, direction) {
    for (let i = 1; i < polygon.length; i++) {
        const a = wrap(tr.pointCoordinate3D(polygon[i - 1]).x);
        const b = wrap(tr.pointCoordinate3D(polygon[i]).x);
        // direction < 0: mercator coordinate 0 will be crossed from left
        // direction > 0: mercator coordinate 1 will be crossed from right
        if (direction < 0) {
            if (a < b) {
                return {
                    idx: i,
                    t: -a / (b - 1 - a)
                };
            }
        } else {
            if (b < a) {
                return {
                    idx: i,
                    t: (1 - a) / (b + 1 - a)
                };
            }
        }
    }
    return null;
}
//Padding is in screen pixels and is only used as a coarse check, so 2 decimal places of precision should be good enough for a cache.
function cacheKey(padding) {
    return padding * 100 | 0;
}
function clampBoundsToTileExtents(bounds) {
    bounds.min.x = clamp(bounds.min.x, 0, EXTENT);
    bounds.min.y = clamp(bounds.min.y, 0, EXTENT);
    bounds.max.x = clamp(bounds.max.x, 0, EXTENT);
    bounds.max.y = clamp(bounds.max.y, 0, EXTENT);
    return bounds;
}

//      
function loadTileJSON (options, requestManager, language, worldview, callback) {
    const loaded = function (err, tileJSON) {
        if (err) {
            return callback(err);
        } else if (tileJSON) {
            // Prefer TileJSON tiles, if both URL and tiles options are set
            if (options.url && tileJSON.tiles && options.tiles)
                delete options.tiles;
            const result = pick(// explicit source options take precedence over TileJSON
            extend$1(tileJSON, options), [
                'tiles',
                'minzoom',
                'maxzoom',
                'attribution',
                'mapbox_logo',
                'bounds',
                'scheme',
                'tileSize',
                'encoding'
            ]);
            if (tileJSON.vector_layers) {
                result.vectorLayers = tileJSON.vector_layers;
                result.vectorLayerIds = result.vectorLayers.map(layer => {
                    return layer.id;
                });
            }
            result.tiles = requestManager.canonicalizeTileset(result, options.url);
            callback(null, result);
        }
    };
    if (options.url) {
        return getJSON(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url, null, language, worldview), ResourceType.Source), loaded);
    } else {
        return exported$1.frame(() => loaded(null, options));
    }
}

//      
class TileBounds {
    constructor(bounds, minzoom, maxzoom) {
        this.bounds = LngLatBounds.convert(this.validateBounds(bounds));
        this.minzoom = minzoom || 0;
        this.maxzoom = maxzoom || 24;
    }
    validateBounds(bounds) {
        // make sure the bounds property contains valid longitude and latitudes
        if (!Array.isArray(bounds) || bounds.length !== 4)
            return [
                -180,
                -90,
                180,
                90
            ];
        return [
            Math.max(-180, bounds[0]),
            Math.max(-90, bounds[1]),
            Math.min(180, bounds[2]),
            Math.min(90, bounds[3])
        ];
    }
    contains(tileID) {
        const worldSize = Math.pow(2, tileID.z);
        const level = {
            minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize),
            minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize),
            maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize),
            maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize)
        };
        const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
        return hit;
    }
}

//      
/**
 * A LineAtlas lets us reuse rendered dashed lines
 * by writing many of them to a texture and then fetching their positions
 * using .getDash.
 *
 * @param {number} width
 * @param {number} height
 * @private
 */
class LineAtlas {
    constructor(width, height) {
        this.width = width;
        this.height = height;
        this.nextRow = 0;
        this.image = new AlphaImage({
            width,
            height
        });
        this.positions = {};
        this.uploaded = false;
    }
    /**
     * Get a dash line pattern.
     *
     * @param {Array<number>} dasharray
     * @param {string} lineCap the type of line caps to be added to dashes
     * @returns {Object} position of dash texture in { y, height, width }
     * @private
     */
    getDash(dasharray, lineCap) {
        const key = this.getKey(dasharray, lineCap);
        return this.positions[key];
    }
    trim() {
        const width = this.width;
        const height = this.height = nextPowerOfTwo(this.nextRow);
        this.image.resize({
            width,
            height
        });
    }
    getKey(dasharray, lineCap) {
        return dasharray.join(',') + lineCap;
    }
    getDashRanges(dasharray, lineAtlasWidth, stretch) {
        // If dasharray has an odd length, both the first and last parts
        // are dashes and should be joined seamlessly.
        const oddDashArray = dasharray.length % 2 === 1;
        const ranges = [];
        let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;
        let right = dasharray[0] * stretch;
        let isDash = true;
        ranges.push({
            left,
            right,
            isDash,
            zeroLength: dasharray[0] === 0
        });
        let currentDashLength = dasharray[0];
        for (let i = 1; i < dasharray.length; i++) {
            isDash = !isDash;
            const dashLength = dasharray[i];
            left = currentDashLength * stretch;
            currentDashLength += dashLength;
            right = currentDashLength * stretch;
            ranges.push({
                left,
                right,
                isDash,
                zeroLength: dashLength === 0
            });
        }
        return ranges;
    }
    addRoundDash(ranges, stretch, n) {
        const halfStretch = stretch / 2;
        for (let y = -n; y <= n; y++) {
            const row = this.nextRow + n + y;
            const index = this.width * row;
            let currIndex = 0;
            let range = ranges[currIndex];
            for (let x = 0; x < this.width; x++) {
                if (x / range.right > 1) {
                    range = ranges[++currIndex];
                }
                const distLeft = Math.abs(x - range.left);
                const distRight = Math.abs(x - range.right);
                const minDist = Math.min(distLeft, distRight);
                let signedDistance;
                const distMiddle = y / n * (halfStretch + 1);
                if (range.isDash) {
                    const distEdge = halfStretch - Math.abs(distMiddle);
                    signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);
                } else {
                    signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);
                }
                this.image.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));
            }
        }
    }
    addRegularDash(ranges, capLength) {
        // Collapse any zero-length range
        // Collapse neighbouring same-type parts into a single part
        for (let i = ranges.length - 1; i >= 0; --i) {
            const part = ranges[i];
            const next = ranges[i + 1];
            if (part.zeroLength) {
                ranges.splice(i, 1);
            } else if (next && next.isDash === part.isDash) {
                next.left = part.left;
                ranges.splice(i, 1);
            }
        }
        // Combine the first and last parts if possible
        const first = ranges[0];
        const last = ranges[ranges.length - 1];
        if (first.isDash === last.isDash) {
            first.left = last.left - this.width;
            last.right = first.right + this.width;
        }
        const index = this.width * this.nextRow;
        let currIndex = 0;
        let range = ranges[currIndex];
        for (let x = 0; x < this.width; x++) {
            if (x / range.right > 1) {
                range = ranges[++currIndex];
            }
            const distLeft = Math.abs(x - range.left);
            const distRight = Math.abs(x - range.right);
            const minDist = Math.min(distLeft, distRight);
            const signedDistance = (range.isDash ? minDist : -minDist) + capLength;
            this.image.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));
        }
    }
    addDash(dasharray, lineCap) {
        const key = this.getKey(dasharray, lineCap);
        if (this.positions[key])
            return this.positions[key];
        const round = lineCap === 'round';
        const n = round ? 7 : 0;
        const height = 2 * n + 1;
        if (this.nextRow + height > this.height) {
            warnOnce('LineAtlas out of space');
            return null;
        }
        // dasharray is empty, draws a full line (no dash or no gap length represented, default behavior)
        if (dasharray.length === 0) {
            // insert a single dash range in order to draw a full line
            dasharray.push(1);
        }
        let length = 0;
        for (let i = 0; i < dasharray.length; i++) {
            if (dasharray[i] < 0) {
                warnOnce('Negative value is found in line dasharray, replacing values with 0');
                dasharray[i] = 0;
            }
            length += dasharray[i];
        }
        if (length !== 0) {
            const stretch = this.width / length;
            const ranges = this.getDashRanges(dasharray, this.width, stretch);
            if (round) {
                this.addRoundDash(ranges, stretch, n);
            } else {
                const capLength = lineCap === 'square' ? 0.5 * stretch : 0;
                this.addRegularDash(ranges, capLength);
            }
        }
        const y = this.nextRow + n;
        this.nextRow += height;
        const pos = {
            tl: [
                y,
                n
            ],
            br: [
                length,
                0
            ]
        };
        this.positions[key] = pos;
        return pos;
    }
}
register(LineAtlas, 'LineAtlas');

//      
const glyphPadding = 1;
/*
    The glyph padding is just to prevent sampling errors at the boundaries between
    glyphs in the atlas texture, and for that purpose there's no need to make it
    bigger with high-res SDFs. However, layout is done based on the glyph size
    including this padding, so scaling this padding is the easiest way to keep
    layout exactly the same as the SDF_SCALE changes.
*/
const localGlyphPadding = glyphPadding * SDF_SCALE;
// {glyphID: glyphRect}
// {fontStack: glyphPoistionMap}
class GlyphAtlas {
    constructor(stacks) {
        const positions = {};
        const bins = [];
        for (const stack in stacks) {
            const glyphData = stacks[stack];
            const glyphPositionMap = positions[stack] = {};
            for (const id in glyphData.glyphs) {
                const src = glyphData.glyphs[+id];
                if (!src || src.bitmap.width === 0 || src.bitmap.height === 0)
                    continue;
                const padding = src.metrics.localGlyph ? localGlyphPadding : glyphPadding;
                const bin = {
                    x: 0,
                    y: 0,
                    w: src.bitmap.width + 2 * padding,
                    h: src.bitmap.height + 2 * padding
                };
                bins.push(bin);
                glyphPositionMap[id] = bin;
            }
        }
        const {w, h} = potpack(bins);
        const image = new AlphaImage({
            width: w || 1,
            height: h || 1
        });
        for (const stack in stacks) {
            const glyphData = stacks[stack];
            for (const id in glyphData.glyphs) {
                const src = glyphData.glyphs[+id];
                if (!src || src.bitmap.width === 0 || src.bitmap.height === 0)
                    continue;
                const bin = positions[stack][id];
                const padding = src.metrics.localGlyph ? localGlyphPadding : glyphPadding;
                AlphaImage.copy(src.bitmap, image, {
                    x: 0,
                    y: 0
                }, {
                    x: bin.x + padding,
                    y: bin.y + padding
                }, src.bitmap);
            }
        }
        this.image = image;
        this.positions = positions;
    }
}
register(GlyphAtlas, 'GlyphAtlas');

//      
class WorkerTile {
    constructor(params) {
        this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);
        this.tileZoom = params.tileZoom;
        this.uid = params.uid;
        this.zoom = params.zoom;
        this.canonical = params.tileID.canonical;
        this.pixelRatio = params.pixelRatio;
        this.tileSize = params.tileSize;
        this.source = params.source;
        this.scope = params.scope;
        this.overscaling = this.tileID.overscaleFactor();
        this.showCollisionBoxes = params.showCollisionBoxes;
        this.collectResourceTiming = !!params.collectResourceTiming;
        this.promoteId = params.promoteId;
        this.isSymbolTile = params.isSymbolTile;
        this.tileTransform = tileTransform(params.tileID.canonical, params.projection);
        this.projection = params.projection;
        this.brightness = params.brightness;
        this.extraShadowCaster = !!params.extraShadowCaster;
    }
    parse(data, layerIndex, availableImages, actor, callback) {
        this.status = 'parsing';
        this.data = data;
        this.collisionBoxArray = new CollisionBoxArray();
        const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort());
        const featureIndex = new FeatureIndex(this.tileID, this.promoteId);
        featureIndex.bucketLayerIDs = [];
        const buckets = {};
        // we initially reserve space for a 256x256 atlas, but trim it after processing all line features
        const lineAtlas = new LineAtlas(256, 256);
        const options = {
            featureIndex,
            iconDependencies: {},
            patternDependencies: {},
            glyphDependencies: {},
            lineAtlas,
            availableImages,
            brightness: this.brightness
        };
        const layerFamilies = layerIndex.familiesBySource[this.source];
        for (const sourceLayerId in layerFamilies) {
            const sourceLayer = data.layers[sourceLayerId];
            if (!sourceLayer) {
                continue;
            }
            let anySymbolLayers = false;
            let anyOtherLayers = false;
            let any3DLayer = false;
            for (const family of layerFamilies[sourceLayerId]) {
                if (family[0].type === 'symbol') {
                    anySymbolLayers = true;
                } else {
                    anyOtherLayers = true;
                }
                if (family[0].is3D() && family[0].type !== 'model') {
                    any3DLayer = true;
                }
            }
            if (this.extraShadowCaster && !any3DLayer) {
                continue;
            }
            if (this.isSymbolTile === true && !anySymbolLayers) {
                continue;
            } else if (this.isSymbolTile === false && !anyOtherLayers) {
                continue;
            }
            if (sourceLayer.version === 1) {
                warnOnce(`Vector tile source "${ this.source }" layer "${ sourceLayerId }" ` + `does not use vector tile spec v2 and therefore may have some rendering errors.`);
            }
            const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId);
            const features = [];
            for (let index = 0; index < sourceLayer.length; index++) {
                const feature = sourceLayer.feature(index);
                const id = featureIndex.getId(feature, sourceLayerId);
                features.push({
                    feature,
                    id,
                    index,
                    sourceLayerIndex
                });
            }
            for (const family of layerFamilies[sourceLayerId]) {
                const layer = family[0];
                if (this.extraShadowCaster && (!layer.is3D() || layer.type === 'model')) {
                    // avoid to spend resources in 2D layers or 3D model layers (trees) for extra shadow casters
                    continue;
                }
                if (this.isSymbolTile !== undefined && layer.type === 'symbol' !== this.isSymbolTile)
                    continue;
                if (layer.minzoom && this.zoom < Math.floor(layer.minzoom))
                    continue;
                if (layer.maxzoom && this.zoom >= layer.maxzoom)
                    continue;
                if (layer.visibility === 'none')
                    continue;
                recalculateLayers(family, this.zoom, options.brightness, availableImages);
                const bucket = buckets[layer.id] = layer.createBucket({
                    index: featureIndex.bucketLayerIDs.length,
                    // $FlowFixMe[incompatible-call] - Flow can't infer proper `family` type from `layer` above
                    layers: family,
                    zoom: this.zoom,
                    canonical: this.canonical,
                    pixelRatio: this.pixelRatio,
                    overscaling: this.overscaling,
                    collisionBoxArray: this.collisionBoxArray,
                    sourceLayerIndex,
                    sourceID: this.source,
                    projection: this.projection.spec
                });
                bucket.populate(features, options, this.tileID.canonical, this.tileTransform);
                featureIndex.bucketLayerIDs.push(family.map(l => l.id));
            }
        }
        lineAtlas.trim();
        let error;
        let glyphMap;
        let iconMap;
        let patternMap;
        const taskMetadata = {
            type: 'maybePrepare',
            isSymbolTile: this.isSymbolTile,
            zoom: this.zoom
        };
        const maybePrepare = () => {
            if (error) {
                return callback(error);
            } else if (this.extraShadowCaster) {
                this.status = 'done';
                // $FlowIgnore[incompatible-call]
                callback(null, {
                    buckets: values(buckets).filter(b => !b.isEmpty()),
                    featureIndex,
                    // $FlowIgnore[incompatible-call] setting null on purpose
                    collisionBoxArray: null,
                    // $FlowIgnore[incompatible-call] setting null on purpose
                    glyphAtlasImage: null,
                    // $FlowIgnore[incompatible-call] setting null on purpose
                    lineAtlas: null,
                    // $FlowIgnore[incompatible-call] setting null on purpose
                    imageAtlas: null,
                    brightness: options.brightness,
                    // Only used for benchmarking:
                    glyphMap: null,
                    iconMap: null,
                    glyphPositions: null
                });
            } else if (glyphMap && iconMap && patternMap) {
                const glyphAtlas = new GlyphAtlas(glyphMap);
                const imageAtlas = new ImageAtlas(iconMap, patternMap);
                for (const key in buckets) {
                    const bucket = buckets[key];
                    if (bucket instanceof SymbolBucket$1) {
                        recalculateLayers(bucket.layers, this.zoom, options.brightness, availableImages);
                        performSymbolLayout(bucket, glyphMap, glyphAtlas.positions, iconMap, imageAtlas.iconPositions, this.showCollisionBoxes, availableImages, this.tileID.canonical, this.tileZoom, this.projection, this.brightness);
                    } else if (bucket.hasPattern && (bucket instanceof LineBucket || bucket instanceof FillBucket || bucket instanceof FillExtrusionBucket)) {
                        recalculateLayers(bucket.layers, this.zoom, options.brightness, availableImages);
                        // $FlowFixMe[incompatible-type] Flow can't interpret ImagePosition as SpritePosition for some reason here
                        const imagePositions = imageAtlas.patternPositions;
                        bucket.addFeatures(options, this.tileID.canonical, imagePositions, availableImages, this.tileTransform, this.brightness);
                    }
                }
                this.status = 'done';
                callback(null, {
                    buckets: values(buckets).filter(b => !b.isEmpty()),
                    featureIndex,
                    collisionBoxArray: this.collisionBoxArray,
                    glyphAtlasImage: glyphAtlas.image,
                    lineAtlas,
                    imageAtlas,
                    brightness: options.brightness
                });
            }
        };
        if (!this.extraShadowCaster) {
            const stacks = mapObject(options.glyphDependencies, glyphs => Object.keys(glyphs).map(Number));
            if (Object.keys(stacks).length) {
                actor.send('getGlyphs', {
                    uid: this.uid,
                    stacks,
                    scope: this.scope
                }, (err, result) => {
                    if (!error) {
                        error = err;
                        glyphMap = result;
                        maybePrepare();
                    }
                }, undefined, false, taskMetadata);
            } else {
                glyphMap = {};
            }
            const icons = Object.keys(options.iconDependencies);
            if (icons.length) {
                actor.send('getImages', {
                    icons,
                    source: this.source,
                    scope: this.scope,
                    tileID: this.tileID,
                    type: 'icons'
                }, (err, result) => {
                    if (!error) {
                        error = err;
                        iconMap = result;
                        maybePrepare();
                    }
                }, undefined, false, taskMetadata);
            } else {
                iconMap = {};
            }
            const patterns = Object.keys(options.patternDependencies);
            if (patterns.length) {
                actor.send('getImages', {
                    icons: patterns,
                    source: this.source,
                    scope: this.scope,
                    tileID: this.tileID,
                    type: 'patterns'
                }, (err, result) => {
                    if (!error) {
                        error = err;
                        patternMap = result;
                        maybePrepare();
                    }
                }, undefined, false, taskMetadata);
            } else {
                patternMap = {};
            }
        }
        maybePrepare();
    }
}
function recalculateLayers(layers, zoom, brightness, availableImages) {
    // Layers are shared and may have been used by a WorkerTile with a different zoom.
    const parameters = new EvaluationParameters(zoom, { brightness });
    for (const layer of layers) {
        layer.recalculate(parameters, availableImages);
    }
}

//      
/**
 * @callback LoadVectorDataCallback
 * @param error
 * @param vectorTile
 * @private
 */
class DedupedRequest {
    constructor(scheduler) {
        this.entries = {};
        this.scheduler = scheduler;
    }
    request(key, metadata, request, callback) {
        const entry = this.entries[key] = this.entries[key] || { callbacks: [] };
        if (entry.result) {
            const [err, result] = entry.result;
            if (this.scheduler) {
                this.scheduler.add(() => {
                    callback(err, result);
                }, metadata);
            } else {
                callback(err, result);
            }
            return () => {
            };
        }
        entry.callbacks.push(callback);
        if (!entry.cancel) {
            entry.cancel = request((err, result) => {
                entry.result = [
                    err,
                    result
                ];
                for (const cb of entry.callbacks) {
                    if (this.scheduler) {
                        this.scheduler.add(() => {
                            cb(err, result);
                        }, metadata);
                    } else {
                        cb(err, result);
                    }
                }
                setTimeout(() => delete this.entries[key], 1000 * 3);
            });
        }
        return () => {
            if (entry.result)
                return;
            entry.callbacks = entry.callbacks.filter(cb => cb !== callback);
            if (!entry.callbacks.length) {
                entry.cancel();
                delete this.entries[key];
            }
        };
    }
}
/**
 * @private
 */
// $FlowFixMe[missing-this-annot]
function loadVectorTile(params, callback, skipParse) {
    const key = JSON.stringify(params.request);
    const makeRequest = callback => {
        const request = getArrayBuffer(params.request, (err, data, cacheControl, expires) => {
            if (err) {
                callback(err);
            } else if (data) {
                callback(null, {
                    vectorTile: skipParse ? undefined : new VectorTile(new Protobuf(data)),
                    rawData: data,
                    cacheControl,
                    expires
                });
            }
        });
        return () => {
            request.cancel();
            callback();
        };
    };
    if (params.data) {
        // if we already got the result earlier (on the main thread), return it directly
        this.deduped.entries[key] = {
            result: [
                null,
                params.data
            ]
        };
    }
    const callbackMetadata = {
        type: 'parseTile',
        isSymbolTile: params.isSymbolTile,
        zoom: params.tileZoom
    };
    return this.deduped.request(key, callbackMetadata, makeRequest, callback);
}
/**
 * The {@link WorkerSource} implementation that supports {@link VectorTileSource}.
 * This class is designed to be easily reused to support custom source types
 * for data formats that can be parsed/converted into an in-memory VectorTile
 * representation.  To do so, create it with
 * `new VectorTileWorkerSource(actor, styleLayers, customLoadVectorDataFunction)`.
 *
 * @private
 */
class VectorTileWorkerSource extends Evented {
    /**
     * @param [loadVectorData] Optional method for custom loading of a VectorTile
     * object based on parameters passed from the main-thread Source. See
     * {@link VectorTileWorkerSource#loadTile}. The default implementation simply
     * loads the pbf at `params.url`.
     * @private
     */
    constructor(actor, layerIndex, availableImages, isSpriteLoaded, loadVectorData, brightness) {
        super();
        this.actor = actor;
        this.layerIndex = layerIndex;
        this.availableImages = availableImages;
        this.loadVectorData = loadVectorData || loadVectorTile;
        this.loading = {};
        this.loaded = {};
        this.deduped = new DedupedRequest(actor.scheduler);
        this.isSpriteLoaded = isSpriteLoaded;
        this.scheduler = actor.scheduler;
        this.brightness = brightness;
    }
    /**
     * Implements {@link WorkerSource#loadTile}. Delegates to
     * {@link VectorTileWorkerSource#loadVectorData} (which by default expects
     * a `params.url` property) for fetching and producing a VectorTile object.
     * @private
     */
    loadTile(params, callback) {
        const uid = params.uid;
        const requestParam = params && params.request;
        const perf = requestParam && requestParam.collectResourceTiming;
        const workerTile = this.loading[uid] = new WorkerTile(params);
        workerTile.abort = this.loadVectorData(params, (err, response) => {
            const aborted = !this.loading[uid];
            delete this.loading[uid];
            if (aborted || err || !response) {
                workerTile.status = 'done';
                if (!aborted)
                    this.loaded[uid] = workerTile;
                return callback(err);
            }
            const rawTileData = response.rawData;
            const cacheControl = {};
            if (response.expires)
                cacheControl.expires = response.expires;
            if (response.cacheControl)
                cacheControl.cacheControl = response.cacheControl;
            // response.vectorTile will be present in the GeoJSON worker case (which inherits from this class)
            // because we stub the vector tile interface around JSON data instead of parsing it directly
            workerTile.vectorTile = response.vectorTile || new VectorTile(new Protobuf(rawTileData));
            const parseTile = () => {
                const workerTileCallback = (err, result) => {
                    if (err || !result)
                        return callback(err);
                    const resourceTiming = {};
                    if (perf) {
                        // Transferring a copy of rawTileData because the worker needs to retain its copy.
                        const resourceTimingData = getPerformanceMeasurement(requestParam);
                        // it's necessary to eval the result of getEntriesByName() here via parse/stringify
                        // late evaluation in the main thread causes TypeError: illegal invocation
                        if (resourceTimingData.length > 0) {
                            resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));
                        }
                    }
                    callback(null, extend$1({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming));
                };
                workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, workerTileCallback);
            };
            if (this.isSpriteLoaded) {
                parseTile();
            } else {
                this.once('isSpriteLoaded', () => {
                    if (this.scheduler) {
                        const metadata = {
                            type: 'parseTile',
                            isSymbolTile: params.isSymbolTile,
                            zoom: params.tileZoom
                        };
                        this.scheduler.add(parseTile, metadata);
                    } else {
                        parseTile();
                    }
                });
            }
            this.loaded = this.loaded || {};
            this.loaded[uid] = workerTile;
        });
    }
    /**
     * Implements {@link WorkerSource#reloadTile}.
     * @private
     */
    reloadTile(params, callback) {
        const loaded = this.loaded, uid = params.uid, vtSource = this;
        if (loaded && loaded[uid]) {
            const workerTile = loaded[uid];
            workerTile.showCollisionBoxes = params.showCollisionBoxes;
            workerTile.projection = params.projection;
            workerTile.brightness = params.brightness;
            workerTile.tileTransform = tileTransform(params.tileID.canonical, params.projection);
            workerTile.extraShadowCaster = params.extraShadowCaster;
            const done = (err, data) => {
                const reloadCallback = workerTile.reloadCallback;
                if (reloadCallback) {
                    delete workerTile.reloadCallback;
                    workerTile.parse(workerTile.vectorTile, vtSource.layerIndex, this.availableImages, vtSource.actor, reloadCallback);
                }
                callback(err, data);
            };
            if (workerTile.status === 'parsing') {
                workerTile.reloadCallback = done;
            } else if (workerTile.status === 'done') {
                // if there was no vector tile data on the initial load, don't try and re-parse tile
                if (workerTile.vectorTile) {
                    workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done);
                } else {
                    done();
                }
            }
        }
    }
    /**
     * Implements {@link WorkerSource#abortTile}.
     *
     * @param params
     * @param params.uid The UID for this tile.
     * @private
     */
    abortTile(params, callback) {
        const uid = params.uid;
        const tile = this.loading[uid];
        if (tile) {
            if (tile.abort)
                tile.abort();
            delete this.loading[uid];
        }
        callback();
    }
    /**
     * Implements {@link WorkerSource#removeTile}.
     *
     * @param params
     * @param params.uid The UID for this tile.
     * @private
     */
    removeTile(params, callback) {
        const loaded = this.loaded, uid = params.uid;
        if (loaded && loaded[uid]) {
            delete loaded[uid];
        }
        callback();
    }
}

//      
/**
 * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/).
 * See the [Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector) for detailed documentation of options.
 *
 * @example
 * map.addSource('some id', {
 *     type: 'vector',
 *     url: 'mapbox://mapbox.mapbox-streets-v8'
 * });
 *
 * @example
 * map.addSource('some id', {
 *     type: 'vector',
 *     tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],
 *     minzoom: 6,
 *     maxzoom: 14
 * });
 *
 * @example
 * map.getSource('some id').setUrl("mapbox://mapbox.mapbox-streets-v8");
 *
 * @example
 * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);
 * @see [Example: Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/)
 * @see [Example: Add a third party vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/third-party/)
 */
class VectorTileSource extends Evented {
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.id = id;
        this.dispatcher = dispatcher;
        this.type = 'vector';
        this.minzoom = 0;
        this.maxzoom = 22;
        this.scheme = 'xyz';
        this.tileSize = 512;
        this.reparseOverscaled = true;
        this.isTileClipped = true;
        this._loaded = false;
        extend$1(this, pick(options, [
            'url',
            'scheme',
            'tileSize',
            'promoteId'
        ]));
        this._options = extend$1({ type: 'vector' }, options);
        this._collectResourceTiming = !!options.collectResourceTiming;
        if (this.tileSize !== 512) {
            throw new Error('vector tile sources must have a tileSize of 512');
        }
        this.setEventedParent(eventedParent);
        this._tileWorkers = {};
        this._deduped = new DedupedRequest();
    }
    load(callback) {
        this._loaded = false;
        this.fire(new Event('dataloading', { dataType: 'source' }));
        const language = Array.isArray(this.map._language) ? this.map._language.join() : this.map._language;
        const worldview = this.map._worldview;
        this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, language, worldview, (err, tileJSON) => {
            this._tileJSONRequest = null;
            this._loaded = true;
            if (err) {
                if (language)
                    console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${ language }`);
                if (worldview && worldview.length !== 2)
                    console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${ worldview }`);
                this.fire(new ErrorEvent(err));
            } else if (tileJSON) {
                extend$1(this, tileJSON);
                if (tileJSON.bounds)
                    this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
                postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);
                // `content` is included here to prevent a race condition where `Style#_updateSources` is called
                // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives
                // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088
                this.fire(new Event('data', {
                    dataType: 'source',
                    sourceDataType: 'metadata'
                }));
                this.fire(new Event('data', {
                    dataType: 'source',
                    sourceDataType: 'content'
                }));
            }
            if (callback)
                callback(err);
        });
    }
    loaded() {
        return this._loaded;
    }
    // $FlowFixMe[method-unbinding]
    hasTile(tileID) {
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.load();
    }
    /**
     * Reloads the source data and re-renders the map.
     *
     * @example
     * map.getSource('source-id').reload();
     */
    // $FlowFixMe[method-unbinding]
    reload() {
        this.cancelTileJSONRequest();
        const fqid = makeFQID(this.id, this.scope);
        this.load(() => this.map.style.clearSource(fqid));
    }
    /**
     * Sets the source `tiles` property and re-renders the map.
     *
     * @param {string[]} tiles An array of one or more tile source URLs, as in the TileJSON spec.
     * @returns {VectorTileSource} Returns itself to allow for method chaining.
     * @example
     * map.addSource('source-id', {
     *     type: 'vector',
     *     tiles: ['https://some_end_point.net/{z}/{x}/{y}.mvt'],
     *     minzoom: 6,
     *     maxzoom: 14
     * });
     *
     * // Set the endpoint associated with a vector tile source.
     * map.getSource('source-id').setTiles(['https://another_end_point.net/{z}/{x}/{y}.mvt']);
     */
    setTiles(tiles) {
        this._options.tiles = tiles;
        this.reload();
        return this;
    }
    /**
     * Sets the source `url` property and re-renders the map.
     *
     * @param {string} url A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://<Tileset ID>`.
     * @returns {VectorTileSource} Returns itself to allow for method chaining.
     * @example
     * map.addSource('source-id', {
     *     type: 'vector',
     *     url: 'mapbox://mapbox.mapbox-streets-v7'
     * });
     *
     * // Update vector tile source to a new URL endpoint
     * map.getSource('source-id').setUrl("mapbox://mapbox.mapbox-streets-v8");
     */
    setUrl(url) {
        this.url = url;
        this._options.url = url;
        this.reload();
        return this;
    }
    // $FlowFixMe[method-unbinding]
    onRemove() {
        this.cancelTileJSONRequest();
    }
    serialize() {
        return extend$1({}, this._options);
    }
    loadTile(tile, callback) {
        const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme));
        const request = this.map._requestManager.transformRequest(url, ResourceType.Tile);
        const params = {
            request,
            data: undefined,
            uid: tile.uid,
            tileID: tile.tileID,
            tileZoom: tile.tileZoom,
            zoom: tile.tileID.overscaledZ,
            tileSize: this.tileSize * tile.tileID.overscaleFactor(),
            type: this.type,
            source: this.id,
            scope: this.scope,
            pixelRatio: exported$1.devicePixelRatio,
            showCollisionBoxes: this.map.showCollisionBoxes,
            promoteId: this.promoteId,
            isSymbolTile: tile.isSymbolTile,
            brightness: this.map.style ? this.map.style.getBrightness() || 0 : 0,
            extraShadowCaster: tile.isExtraShadowCaster
        };
        params.request.collectResourceTiming = this._collectResourceTiming;
        if (!tile.actor || tile.state === 'expired') {
            tile.actor = this._tileWorkers[url] = this._tileWorkers[url] || this.dispatcher.getActor();
            // if workers are not ready to receive messages yet, use the idle time to preemptively
            // load tiles on the main thread and pass the result instead of requesting a worker to do so
            if (!this.dispatcher.ready) {
                const cancel = loadVectorTile.call({ deduped: this._deduped }, params, (err, data) => {
                    if (err || !data) {
                        done.call(this, err);
                    } else {
                        // the worker will skip the network request if the data is already there
                        params.data = {
                            cacheControl: data.cacheControl,
                            expires: data.expires,
                            rawData: data.rawData.slice(0)
                        };
                        if (tile.actor)
                            tile.actor.send('loadTile', params, done.bind(this), undefined, true);
                    }
                }, true);
                tile.request = { cancel };
            } else {
                tile.request = tile.actor.send('loadTile', params, done.bind(this), undefined, true);
            }
        } else if (tile.state === 'loading') {
            // schedule tile reloading after it has been loaded
            tile.reloadCallback = callback;
        } else {
            tile.request = tile.actor.send('reloadTile', params, done.bind(this));
        }
        // $FlowFixMe[missing-this-annot]
        function done(err, data) {
            delete tile.request;
            if (tile.aborted)
                return callback(null);
            // $FlowFixMe[prop-missing] - generic Error type doesn't have status
            if (err && err.status !== 404) {
                return callback(err);
            }
            if (data && data.resourceTiming)
                tile.resourceTiming = data.resourceTiming;
            if (this.map._refreshExpiredTiles && data)
                tile.setExpiryData(data);
            tile.loadVectorData(data, this.map.painter);
            cacheEntryPossiblyAdded(this.dispatcher);
            callback(null);
            if (tile.reloadCallback) {
                this.loadTile(tile, tile.reloadCallback);
                tile.reloadCallback = null;
            }
        }
    }
    // $FlowFixMe[method-unbinding]
    abortTile(tile) {
        if (tile.request) {
            tile.request.cancel();
            delete tile.request;
        }
        if (tile.actor) {
            tile.actor.send('abortTile', {
                uid: tile.uid,
                type: this.type,
                source: this.id,
                scope: this.scope
            });
        }
    }
    // $FlowFixMe[method-unbinding]
    unloadTile(tile) {
        tile.unloadVectorData();
        if (tile.actor) {
            tile.actor.send('removeTile', {
                uid: tile.uid,
                type: this.type,
                source: this.id,
                scope: this.scope
            });
        }
    }
    hasTransition() {
        return false;
    }
    // $FlowFixMe[method-unbinding]
    afterUpdate() {
        this._tileWorkers = {};
    }
    cancelTileJSONRequest() {
        if (!this._tileJSONRequest)
            return;
        this._tileJSONRequest.cancel();
        this._tileJSONRequest = null;
    }
}

//      
/**
 * A source containing raster tiles.
 * See the [Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#raster) for detailed documentation of options.
 *
 * @example
 * map.addSource('some id', {
 *     type: 'raster',
 *     url: 'mapbox://mapbox.satellite',
 *     tileSize: 256
 * });
 *
 * @example
 * map.addSource('some id', {
 *     type: 'raster',
 *     tiles: ['https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015'],
 *     tileSize: 256
 * });
 *
 * @see [Example: Add a raster tile source](https://docs.mapbox.com/mapbox-gl-js/example/map-tiles/)
 * @see [Example: Add a WMS source](https://docs.mapbox.com/mapbox-gl-js/example/wms/)
 */
class RasterTileSource extends Evented {
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.id = id;
        this.dispatcher = dispatcher;
        this.setEventedParent(eventedParent);
        this.type = 'raster';
        this.minzoom = 0;
        this.maxzoom = 22;
        this.roundZoom = true;
        this.scheme = 'xyz';
        this.tileSize = 512;
        this._loaded = false;
        this._options = extend$1({ type: 'raster' }, options);
        extend$1(this, pick(options, [
            'url',
            'scheme',
            'tileSize'
        ]));
    }
    load(callback) {
        this._loaded = false;
        this.fire(new Event('dataloading', { dataType: 'source' }));
        this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, null, null, (err, tileJSON) => {
            this._tileJSONRequest = null;
            this._loaded = true;
            if (err) {
                this.fire(new ErrorEvent(err));
            } else if (tileJSON) {
                extend$1(this, tileJSON);
                if (tileJSON.bounds)
                    this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
                postTurnstileEvent(tileJSON.tiles);
                // `content` is included here to prevent a race condition where `Style#_updateSources` is called
                // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives
                // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088
                this.fire(new Event('data', {
                    dataType: 'source',
                    sourceDataType: 'metadata'
                }));
                this.fire(new Event('data', {
                    dataType: 'source',
                    sourceDataType: 'content'
                }));
            }
            if (callback)
                callback(err);
        });
    }
    loaded() {
        return this._loaded;
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.load();
    }
    /**
     * Reloads the source data and re-renders the map.
     *
     * @example
     * map.getSource('source-id').reload();
     */
    // $FlowFixMe[method-unbinding]
    reload() {
        this.cancelTileJSONRequest();
        const fqid = makeFQID(this.id, this.scope);
        this.load(() => this.map.style.clearSource(fqid));
    }
    /**
     * Sets the source `tiles` property and re-renders the map.
     *
     * @param {string[]} tiles An array of one or more tile source URLs, as in the TileJSON spec.
     * @returns {RasterTileSource} Returns itself to allow for method chaining.
     * @example
     * map.addSource('source-id', {
     *     type: 'raster',
     *     tiles: ['https://some_end_point.net/{z}/{x}/{y}.png'],
     *     tileSize: 256
     * });
     *
     * // Set the endpoint associated with a raster tile source.
     * map.getSource('source-id').setTiles(['https://another_end_point.net/{z}/{x}/{y}.png']);
     */
    setTiles(tiles) {
        this._options.tiles = tiles;
        this.reload();
        return this;
    }
    /**
     * Sets the source `url` property and re-renders the map.
     *
     * @param {string} url A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://<Tileset ID>`.
     * @returns {RasterTileSource} Returns itself to allow for method chaining.
     * @example
     * map.addSource('source-id', {
     *     type: 'raster',
     *     url: 'mapbox://mapbox.satellite'
     * });
     *
     * // Update raster tile source to a new URL endpoint
     * map.getSource('source-id').setUrl('mapbox://mapbox.satellite');
     */
    setUrl(url) {
        this.url = url;
        this._options.url = url;
        this.reload();
        return this;
    }
    // $FlowFixMe[method-unbinding]
    onRemove() {
        this.cancelTileJSONRequest();
    }
    serialize() {
        return extend$1({}, this._options);
    }
    // $FlowFixMe[method-unbinding]
    hasTile(tileID) {
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    loadTile(tile, callback) {
        const use2x = exported$1.devicePixelRatio >= 2;
        const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), use2x, this.tileSize);
        tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), (error, data, cacheControl, expires) => {
            delete tile.request;
            if (tile.aborted) {
                tile.state = 'unloaded';
                return callback(null);
            }
            if (error) {
                tile.state = 'errored';
                return callback(error);
            }
            if (!data)
                return callback(null);
            if (this.map._refreshExpiredTiles)
                tile.setExpiryData({
                    cacheControl,
                    expires
                });
            tile.setTexture(data, this.map.painter);
            tile.state = 'loaded';
            cacheEntryPossiblyAdded(this.dispatcher);
            callback(null);
        });
    }
    static loadTileData(tile, data, painter) {
        tile.setTexture(data, painter);
    }
    static unloadTileData(tile, painter) {
        if (tile.texture) {
            painter.saveTileTexture(tile.texture);
        }
    }
    // $FlowFixMe[method-unbinding]
    abortTile(tile, callback) {
        if (tile.request) {
            tile.request.cancel();
            delete tile.request;
        }
        callback();
    }
    // $FlowFixMe[method-unbinding]
    unloadTile(tile, callback) {
        if (tile.texture)
            this.map.painter.saveTileTexture(tile.texture);
        callback();
    }
    hasTransition() {
        return false;
    }
    cancelTileJSONRequest() {
        if (!this._tileJSONRequest)
            return;
        this._tileJSONRequest.cancel();
        this._tileJSONRequest = null;
    }
}

//      
let supportsOffscreenCanvas;
function offscreenCanvasSupported() {
    if (supportsOffscreenCanvas == null) {
        supportsOffscreenCanvas = window$1.OffscreenCanvas && new window$1.OffscreenCanvas(1, 1).getContext('2d') && typeof window$1.createImageBitmap === 'function';
    }
    return supportsOffscreenCanvas;
}

//      
// $FlowFixMe[method-unbinding]
class RasterDEMTileSource extends RasterTileSource {
    constructor(id, options, dispatcher, eventedParent) {
        super(id, options, dispatcher, eventedParent);
        this.type = 'raster-dem';
        this.maxzoom = 22;
        this._options = extend$1({ type: 'raster-dem' }, options);
        this.encoding = options.encoding || 'mapbox';
    }
    loadTile(tile, callback) {
        const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), false, this.tileSize);
        tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), imageLoaded.bind(this));
        const convertDEMTexturesToFloatFormat = this.map?.painter?.terrainUseFloatDEM();
        // $FlowFixMe[missing-this-annot]
        function imageLoaded(err, img, cacheControl, expires) {
            delete tile.request;
            if (tile.aborted) {
                tile.state = 'unloaded';
                callback(null);
            } else if (err) {
                tile.state = 'errored';
                callback(err);
            } else if (img) {
                if (this.map._refreshExpiredTiles)
                    tile.setExpiryData({
                        cacheControl,
                        expires
                    });
                const transfer = window$1.ImageBitmap && img instanceof window$1.ImageBitmap && offscreenCanvasSupported();
                // DEMData uses 1px padding. Handle cases with image buffer of 1 and 2 pxs, the rest assume default buffer 0
                // in order to keep the previous implementation working (no validation against tileSize).
                const buffer = (img.width - prevPowerOfTwo(img.width)) / 2;
                // padding is used in getImageData. As DEMData has 1px padding, if DEM tile buffer is 2px, discard outermost pixels.
                const padding = 1 - buffer;
                const borderReady = padding < 1;
                if (!borderReady && !tile.neighboringTiles) {
                    tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);
                }
                // $FlowFixMe[incompatible-call]
                const rawImageData = transfer ? img : exported$1.getImageData(img, padding);
                const params = {
                    uid: tile.uid,
                    coord: tile.tileID,
                    source: this.id,
                    scope: this.scope,
                    rawImageData,
                    encoding: this.encoding,
                    padding,
                    convertToFloat: convertDEMTexturesToFloatFormat
                };
                if (!tile.actor || tile.state === 'expired') {
                    tile.actor = this.dispatcher.getActor();
                    tile.actor.send('loadDEMTile', params, done.bind(this), undefined, true);
                }
            }
        }
        // $FlowFixMe[missing-this-annot]
        function done(err, dem) {
            if (err) {
                tile.state = 'errored';
                callback(err);
            }
            if (dem) {
                tile.dem = dem;
                tile.dem.onDeserialize();
                tile.needsHillshadePrepare = true;
                tile.needsDEMTextureUpload = true;
                tile.state = 'loaded';
                callback(null);
            }
        }
    }
    _getNeighboringTiles(tileID) {
        const canonical = tileID.canonical;
        const dim = Math.pow(2, canonical.z);
        const px = (canonical.x - 1 + dim) % dim;
        const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;
        const nx = (canonical.x + 1 + dim) % dim;
        const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;
        const neighboringTiles = {};
        // add adjacent tiles
        neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false };
        neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false };
        // Add upper neighboringTiles
        if (canonical.y > 0) {
            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false };
            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false };
            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false };
        }
        // Add lower neighboringTiles
        if (canonical.y + 1 < dim) {
            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false };
            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false };
            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false };
        }
        return neighboringTiles;
    }
    // $FlowFixMe[method-unbinding]
    unloadTile(tile) {
        if (tile.demTexture)
            this.map.painter.saveTileTexture(tile.demTexture);
        if (tile.hillshadeFBO) {
            tile.hillshadeFBO.destroy();
            delete tile.hillshadeFBO;
        }
        if (tile.dem)
            delete tile.dem;
        delete tile.neighboringTiles;
        tile.state = 'unloaded';
    }
}

//      
/**
 * A source containing GeoJSON.
 * See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson) for detailed documentation of options.
 *
 * @example
 * map.addSource('some id', {
 *     type: 'geojson',
 *     data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
 * });
 *
 * @example
 * map.addSource('some id', {
 *     type: 'geojson',
 *     data: {
 *         "type": "FeatureCollection",
 *         "features": [{
 *             "type": "Feature",
 *             "properties": {},
 *             "geometry": {
 *                 "type": "Point",
 *                 "coordinates": [
 *                     -76.53063297271729,
 *                     39.18174077994108
 *                 ]
 *             }
 *         }]
 *     }
 * });
 *
 * @example
 * map.getSource('some id').setData({
 *     "type": "FeatureCollection",
 *     "features": [{
 *         "type": "Feature",
 *         "properties": {"name": "Null Island"},
 *         "geometry": {
 *             "type": "Point",
 *             "coordinates": [ 0, 0 ]
 *         }
 *     }]
 * });
 * @see [Example: Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)
 * @see [Example: Add a GeoJSON line](https://www.mapbox.com/mapbox-gl-js/example/geojson-line/)
 * @see [Example: Create a heatmap from points](https://www.mapbox.com/mapbox-gl-js/example/heatmap/)
 * @see [Example: Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/)
 */
class GeoJSONSource extends Evented {
    /**
     * @private
     */
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.id = id;
        // `type` is a property rather than a constant to make it easy for 3rd
        // parties to use GeoJSONSource to build their own source types.
        this.type = 'geojson';
        this.minzoom = 0;
        this.maxzoom = 18;
        this.tileSize = 512;
        this.isTileClipped = true;
        this.reparseOverscaled = true;
        this._loaded = false;
        this.actor = dispatcher.getActor();
        this.setEventedParent(eventedParent);
        this._data = options.data;
        this._options = extend$1({}, options);
        this._collectResourceTiming = options.collectResourceTiming;
        if (options.maxzoom !== undefined)
            this.maxzoom = options.maxzoom;
        if (options.type)
            this.type = options.type;
        if (options.attribution)
            this.attribution = options.attribution;
        this.promoteId = options.promoteId;
        const scale = EXTENT / this.tileSize;
        // sent to the worker, along with `url: ...` or `data: literal geojson`,
        // so that it can load/parse/index the geojson data
        // extending with `options.workerOptions` helps to make it easy for
        // third-party sources to hack/reuse GeoJSONSource.
        this.workerOptions = extend$1({
            source: this.id,
            scope: this.scope,
            cluster: options.cluster || false,
            geojsonVtOptions: {
                buffer: (options.buffer !== undefined ? options.buffer : 128) * scale,
                tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale,
                extent: EXTENT,
                maxZoom: this.maxzoom,
                lineMetrics: options.lineMetrics || false,
                generateId: options.generateId || false
            },
            superclusterOptions: {
                maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1,
                minPoints: Math.max(2, options.clusterMinPoints || 2),
                extent: EXTENT,
                radius: (options.clusterRadius !== undefined ? options.clusterRadius : 50) * scale,
                log: false,
                generateId: options.generateId || false
            },
            clusterProperties: options.clusterProperties,
            filter: options.filter
        }, options.workerOptions);
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.setData(this._data);
    }
    /**
     * Sets the GeoJSON data and re-renders the map.
     *
     * @param {Object | string} data A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.
     * @returns {GeoJSONSource} Returns itself to allow for method chaining.
     * @example
     * map.addSource('source_id', {
     *     type: 'geojson',
     *     data: {
     *         type: 'FeatureCollection',
     *         features: []
     *     }
     * });
     * const geojsonSource = map.getSource('source_id');
     * // Update the data after the GeoJSON source was created
     * geojsonSource.setData({
     *     "type": "FeatureCollection",
     *     "features": [{
     *         "type": "Feature",
     *         "properties": {"name": "Null Island"},
     *         "geometry": {
     *             "type": "Point",
     *             "coordinates": [ 0, 0 ]
     *         }
     *     }]
     * });
     */
    setData(data) {
        this._data = data;
        this._updateWorkerData();
        return this;
    }
    /**
     * For clustered sources, fetches the zoom at which the given cluster expands.
     *
     * @param {number} clusterId The value of the cluster's `cluster_id` property.
     * @param {Function} callback A callback to be called when the zoom value is retrieved (`(error, zoom) => { ... }`).
     * @returns {GeoJSONSource} Returns itself to allow for method chaining.
     * @example
     * // Assuming the map has a layer named 'clusters' and a source 'earthquakes'
     * // The following creates a camera animation on cluster feature click
     * // the clicked layer should be filtered to only include clusters, e.g. `filter: ['has', 'point_count']`
     * map.on('click', 'clusters', (e) => {
     *     const features = map.queryRenderedFeatures(e.point, {
     *         layers: ['clusters']
     *     });
     *
     *     const clusterId = features[0].properties.cluster_id;
     *
     *     // Ease the camera to the next cluster expansion
     *     map.getSource('earthquakes').getClusterExpansionZoom(
     *         clusterId,
     *         (err, zoom) => {
     *             if (!err) {
     *                 map.easeTo({
     *                     center: features[0].geometry.coordinates,
     *                     zoom
     *                 });
     *             }
     *         }
     *     );
     * });
     */
    getClusterExpansionZoom(clusterId, callback) {
        this.actor.send('geojson.getClusterExpansionZoom', {
            clusterId,
            source: this.id,
            scope: this.scope
        }, callback);
        return this;
    }
    /**
     * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).
     *
     * @param {number} clusterId The value of the cluster's `cluster_id` property.
     * @param {Function} callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).
     * @returns {GeoJSONSource} Returns itself to allow for method chaining.
     * @example
     * // Retrieve cluster children on click
     * // the clicked layer should be filtered to only include clusters, e.g. `filter: ['has', 'point_count']`
     * map.on('click', 'clusters', (e) => {
     *     const features = map.queryRenderedFeatures(e.point, {
     *         layers: ['clusters']
     *     });
     *
     *     const clusterId = features[0].properties.cluster_id;
     *
     *     clusterSource.getClusterChildren(clusterId, (error, features) => {
     *         if (!error) {
     *             console.log('Cluster children:', features);
     *         }
     *     });
     * });
     */
    getClusterChildren(clusterId, callback) {
        this.actor.send('geojson.getClusterChildren', {
            clusterId,
            source: this.id,
            scope: this.scope
        }, callback);
        return this;
    }
    /**
     * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).
     *
     * @param {number} clusterId The value of the cluster's `cluster_id` property.
     * @param {number} limit The maximum number of features to return. Defaults to `10` if a falsy value is given.
     * @param {number} offset The number of features to skip (for example, for pagination). Defaults to `0` if a falsy value is given.
     * @param {Function} callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).
     * @returns {GeoJSONSource} Returns itself to allow for method chaining.
     * @example
     * // Retrieve cluster leaves on click
     * // the clicked layer should be filtered to only include clusters, e.g. `filter: ['has', 'point_count']`
     * map.on('click', 'clusters', (e) => {
     *     const features = map.queryRenderedFeatures(e.point, {
     *         layers: ['clusters']
     *     });
     *
     *     const clusterId = features[0].properties.cluster_id;
     *     const pointCount = features[0].properties.point_count;
     *     const clusterSource = map.getSource('clusters');
     *
     *     clusterSource.getClusterLeaves(clusterId, pointCount, 0, (error, features) => {
     *     // Print cluster leaves in the console
     *         console.log('Cluster leaves:', error, features);
     *     });
     * });
     */
    getClusterLeaves(clusterId, limit, offset, callback) {
        this.actor.send('geojson.getClusterLeaves', {
            source: this.id,
            scope: this.scope,
            clusterId,
            limit,
            offset
        }, callback);
        return this;
    }
    /*
     * Responsible for invoking WorkerSource's geojson.loadData target, which
     * handles loading the geojson data and preparing to serve it up as tiles,
     * using geojson-vt or supercluster as appropriate.
     */
    _updateWorkerData() {
        // if there's an earlier loadData to finish, wait until it finishes and then do another update
        if (this._pendingLoad) {
            this._coalesce = true;
            return;
        }
        this.fire(new Event('dataloading', { dataType: 'source' }));
        this._loaded = false;
        const options = extend$1({}, this.workerOptions);
        options.scope = this.scope;
        const data = this._data;
        if (typeof data === 'string') {
            options.request = this.map._requestManager.transformRequest(exported$1.resolveURL(data), ResourceType.Source);
            options.request.collectResourceTiming = this._collectResourceTiming;
        } else {
            options.data = JSON.stringify(data);
        }
        // target {this.type}.loadData rather than literally geojson.loadData,
        // so that other geojson-like source types can easily reuse this
        // implementation
        this._pendingLoad = this.actor.send(`${ this.type }.loadData`, options, (err, result) => {
            this._loaded = true;
            this._pendingLoad = null;
            if (err) {
                this.fire(new ErrorEvent(err));
            } else {
                // although GeoJSON sources contain no metadata, we fire this event at first
                // to let the SourceCache know its ok to start requesting tiles.
                const data = {
                    dataType: 'source',
                    sourceDataType: this._metadataFired ? 'content' : 'metadata'
                };
                if (this._collectResourceTiming && result && result.resourceTiming && result.resourceTiming[this.id]) {
                    data.resourceTiming = result.resourceTiming[this.id];
                }
                this.fire(new Event('data', data));
                this._metadataFired = true;
            }
            if (this._coalesce) {
                this._updateWorkerData();
                this._coalesce = false;
            }
        });
    }
    loaded() {
        return this._loaded;
    }
    loadTile(tile, callback) {
        const message = !tile.actor ? 'loadTile' : 'reloadTile';
        tile.actor = this.actor;
        const params = {
            type: this.type,
            uid: tile.uid,
            tileID: tile.tileID,
            tileZoom: tile.tileZoom,
            zoom: tile.tileID.overscaledZ,
            maxZoom: this.maxzoom,
            tileSize: this.tileSize,
            source: this.id,
            scope: this.scope,
            pixelRatio: exported$1.devicePixelRatio,
            showCollisionBoxes: this.map.showCollisionBoxes,
            promoteId: this.promoteId,
            brightness: this.map.style ? this.map.style.getBrightness() || 0 : 0
        };
        tile.request = this.actor.send(message, params, (err, data) => {
            delete tile.request;
            tile.unloadVectorData();
            if (tile.aborted) {
                return callback(null);
            }
            if (err) {
                return callback(err);
            }
            tile.loadVectorData(data, this.map.painter, message === 'reloadTile');
            return callback(null);
        }, undefined, message === 'loadTile');
    }
    // $FlowFixMe[method-unbinding]
    abortTile(tile) {
        if (tile.request) {
            tile.request.cancel();
            delete tile.request;
        }
        tile.aborted = true;
    }
    // $FlowFixMe[method-unbinding]
    unloadTile(tile) {
        tile.unloadVectorData();
        this.actor.send('removeTile', {
            uid: tile.uid,
            type: this.type,
            source: this.id,
            scope: this.scope
        });
    }
    // $FlowFixMe[method-unbinding]
    onRemove() {
        if (this._pendingLoad) {
            this._pendingLoad.cancel();
        }
    }
    serialize() {
        return extend$1({}, this._options, {
            type: this.type,
            data: this._data
        });
    }
    hasTransition() {
        return false;
    }
}

//      
/**
 * A data source containing video.
 * See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-video) for detailed documentation of options.
 *
 * @example
 * // add to map
 * map.addSource('some id', {
 *     type: 'video',
 *     url: [
 *         'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',
 *         'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'
 *     ],
 *     coordinates: [
 *         [-76.54, 39.18],
 *         [-76.52, 39.18],
 *         [-76.52, 39.17],
 *         [-76.54, 39.17]
 *     ]
 * });
 *
 * // update
 * const mySource = map.getSource('some id');
 * mySource.setCoordinates([
 *     [-76.54335737228394, 39.18579907229748],
 *     [-76.52803659439087, 39.1838364847587],
 *     [-76.5295386314392, 39.17683392507606],
 *     [-76.54520273208618, 39.17876344106642]
 * ]);
 *
 * map.removeSource('some id');  // remove
 * @see [Example: Add a video](https://www.mapbox.com/mapbox-gl-js/example/video-on-a-map/)
 */
class VideoSource extends ImageSource {
    /**
     * @private
     */
    constructor(id, options, dispatcher, eventedParent) {
        super(id, options, dispatcher, eventedParent);
        this.roundZoom = true;
        this.type = 'video';
        this.options = options;
    }
    load() {
        this._loaded = false;
        const options = this.options;
        this.urls = [];
        for (const url of options.urls) {
            this.urls.push(this.map._requestManager.transformRequest(url, ResourceType.Source).url);
        }
        getVideo(this.urls, (err, video) => {
            this._loaded = true;
            if (err) {
                this.fire(new ErrorEvent(err));
            } else if (video) {
                this.video = video;
                this.video.loop = true;
                // Prevent the video from taking over the screen in iOS
                this.video.setAttribute('playsinline', '');
                // Start repainting when video starts playing. hasTransition() will then return
                // true to trigger additional frames as long as the videos continues playing.
                this.video.addEventListener('playing', () => {
                    this.map.triggerRepaint();
                });
                if (this.map) {
                    this.video.play();
                }
                this._finishLoading();
            }
        });
    }
    /**
     * Pauses the video.
     *
     * @example
     * // Assuming a video source identified by video_source_id was added to the map
     * const videoSource = map.getSource('video_source_id');
     *
     * // Pauses the video
     * videoSource.pause();
     */
    pause() {
        if (this.video) {
            this.video.pause();
        }
    }
    /**
     * Plays the video.
     *
     * @example
     * // Assuming a video source identified by video_source_id was added to the map
     * const videoSource = map.getSource('video_source_id');
     *
     * // Starts the video
     * videoSource.play();
     */
    play() {
        if (this.video) {
            this.video.play();
        }
    }
    /**
     * Sets playback to a timestamp, in seconds.
     * @private
     */
    seek(seconds) {
        if (this.video) {
            const seekableRange = this.video.seekable;
            if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) {
                this.fire(new ErrorEvent(new ValidationError(`sources.${ this.id }`, null, `Playback for this video can be set only between the ${ seekableRange.start(0) } and ${ seekableRange.end(0) }-second mark.`)));
            } else
                this.video.currentTime = seconds;
        }
    }
    /**
     * Returns the HTML `video` element.
     *
     * @returns {HTMLVideoElement} The HTML `video` element.
     * @example
     * // Assuming a video source identified by video_source_id was added to the map
     * const videoSource = map.getSource('video_source_id');
     *
     * videoSource.getVideo(); // <video crossorigin="Anonymous" loop="">...</video>
     */
    getVideo() {
        return this.video;
    }
    onAdd(map) {
        if (this.map)
            return;
        this.map = map;
        this.load();
        if (this.video) {
            this.video.play();
            this.setCoordinates(this.coordinates);
        }
    }
    /**
     * Sets the video's coordinates and re-renders the map.
     *
     * @method setCoordinates
     * @instance
     * @memberof VideoSource
     * @returns {VideoSource} Returns itself to allow for method chaining.
     * @example
     * // Add a video source to the map to map
     * map.addSource('video_source_id', {
     *     type: 'video',
     *     urls: [
     *         'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',
     *         'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'
     *     ],
     *     coordinates: [
     *         [-76.54, 39.18],
     *         [-76.52, 39.18],
     *         [-76.52, 39.17],
     *         [-76.54, 39.17]
     *     ]
     * });
     *
     * // Then update the video source coordinates by new coordinates
     * const videoSource = map.getSource('video_source_id');
     * videoSource.setCoordinates([
     *     [-76.5433, 39.1857],
     *     [-76.5280, 39.1838],
     *     [-76.5295, 39.1768],
     *     [-76.5452, 39.1787]
     * ]);
     */
    // setCoordinates inherited from ImageSource
    prepare() {
        if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) {
            return;    // not enough data for current position
        }
        const context = this.map.painter.context;
        const gl = context.gl;
        if (!this.texture) {
            this.texture = new Texture(context, this.video, gl.RGBA);
            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            this.width = this.video.videoWidth;
            this.height = this.video.videoHeight;
        } else if (!this.video.paused) {
            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video);
        }
        this._prepareData(context);
    }
    serialize() {
        return {
            type: 'video',
            urls: this.urls,
            coordinates: this.coordinates
        };
    }
    hasTransition() {
        return this.video && !this.video.paused;
    }
}

//      
/**
 * Options to add a canvas source type to the map.
 *
 * @typedef {Object} CanvasSourceOptions
 * @property {string} type Source type. Must be `"canvas"`.
 * @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.
 * @property {Array<Array<number>>} coordinates Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs.
 * @property {boolean} [animate=true] Whether the canvas source is animated. If the canvas is static (pixels do not need to be re-read on every frame), `animate` should be set to `false` to improve performance.
 */
/**
 * A data source containing the contents of an HTML canvas. See {@link CanvasSourceOptions} for detailed documentation of options.
 *
 * @example
 * // add to map
 * map.addSource('some id', {
 *     type: 'canvas',
 *     canvas: 'idOfMyHTMLCanvas',
 *     animate: true,
 *     coordinates: [
 *         [-76.54, 39.18],
 *         [-76.52, 39.18],
 *         [-76.52, 39.17],
 *         [-76.54, 39.17]
 *     ]
 * });
 *
 * // update
 * const mySource = map.getSource('some id');
 * mySource.setCoordinates([
 *     [-76.54335737228394, 39.18579907229748],
 *     [-76.52803659439087, 39.1838364847587],
 *     [-76.5295386314392, 39.17683392507606],
 *     [-76.54520273208618, 39.17876344106642]
 * ]);
 *
 * map.removeSource('some id');  // remove
 * @see [Example: Add a canvas source](https://docs.mapbox.com/mapbox-gl-js/example/canvas-source/)
 */
class CanvasSource extends ImageSource {
    /**
     * @private
     */
    constructor(id, options, dispatcher, eventedParent) {
        super(id, options, dispatcher, eventedParent);
        // We build in some validation here, since canvas sources aren't included in the style spec:
        if (!options.coordinates) {
            this.fire(new ErrorEvent(new ValidationError(`sources.${ id }`, null, 'missing required property "coordinates"')));
        } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) {
            this.fire(new ErrorEvent(new ValidationError(`sources.${ id }`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs')));
        }
        if (options.animate && typeof options.animate !== 'boolean') {
            this.fire(new ErrorEvent(new ValidationError(`sources.${ id }`, null, 'optional "animate" property must be a boolean value')));
        }
        if (!options.canvas) {
            this.fire(new ErrorEvent(new ValidationError(`sources.${ id }`, null, 'missing required property "canvas"')));
        } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof window$1.HTMLCanvasElement)) {
            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')));
        }
        this.options = options;
        this.animate = options.animate !== undefined ? options.animate : true;
    }
    /**
     * Enables animation. The image will be copied from the canvas to the map on each frame.
     *
     * @method play
     * @instance
     * @memberof CanvasSource
     */
    /**
     * Disables animation. The map will display a static copy of the canvas image.
     *
     * @method pause
     * @instance
     * @memberof CanvasSource
     */
    load() {
        this._loaded = true;
        if (!this.canvas) {
            this.canvas = this.options.canvas instanceof window$1.HTMLCanvasElement ? this.options.canvas : window$1.document.getElementById(this.options.canvas);
        }
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        if (this._hasInvalidDimensions()) {
            this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.')));
            return;
        }
        // $FlowFixMe[missing-this-annot]
        this.play = function () {
            this._playing = true;
            this.map.triggerRepaint();
        };
        // $FlowFixMe[missing-this-annot]
        this.pause = function () {
            if (this._playing) {
                this.prepare();
                this._playing = false;
            }
        };
        this._finishLoading();
    }
    /**
     * Returns the HTML `canvas` element.
     *
     * @returns {HTMLCanvasElement} The HTML `canvas` element.
     * @example
     * // Assuming the following canvas is added to your page
     * // <canvas id="canvasID" width="400" height="400"></canvas>
     * map.addSource('canvas-source', {
     *     type: 'canvas',
     *     canvas: 'canvasID',
     *     coordinates: [
     *         [91.4461, 21.5006],
     *         [100.3541, 21.5006],
     *         [100.3541, 13.9706],
     *         [91.4461, 13.9706]
     *     ]
     * });
     * map.getSource('canvas-source').getCanvas(); // <canvas id="canvasID" width="400" height="400"></canvas>
     */
    getCanvas() {
        return this.canvas;
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.load();
        if (this.canvas) {
            if (this.animate)
                this.play();
        }
    }
    // $FlowFixMe[method-unbinding]
    onRemove() {
        this.pause();
    }
    /**
     * Sets the canvas's coordinates and re-renders the map.
     *
     * @method setCoordinates
     * @instance
     * @memberof CanvasSource
     * @param {Array<Array<number>>} coordinates Four geographical coordinates,
     *     represented as arrays of longitude and latitude numbers, which define the corners of the canvas.
     *     The coordinates start at the top left corner of the canvas and proceed in clockwise order.
     *     They do not have to represent a rectangle.
     * @returns {CanvasSource} Returns itself to allow for method chaining.
     */
    // setCoordinates inherited from ImageSource
    // $FlowFixMe[method-unbinding]
    prepare() {
        let resize = false;
        if (this.canvas.width !== this.width) {
            this.width = this.canvas.width;
            resize = true;
        }
        if (this.canvas.height !== this.height) {
            this.height = this.canvas.height;
            resize = true;
        }
        if (this._hasInvalidDimensions())
            return;
        if (Object.keys(this.tiles).length === 0)
            return;
        // not enough data for current position
        const context = this.map.painter.context;
        if (!this.texture) {
            this.texture = new Texture(context, this.canvas, context.gl.RGBA, { premultiply: true });
        } else if ((resize || this._playing) && !(this.texture instanceof UserManagedTexture)) {
            this.texture.update(this.canvas, { premultiply: true });
        }
        this._prepareData(context);
    }
    serialize() {
        return {
            type: 'canvas',
            coordinates: this.coordinates
        };
    }
    hasTransition() {
        return this._playing;
    }
    _hasInvalidDimensions() {
        for (const x of [
                this.canvas.width,
                this.canvas.height
            ]) {
            if (isNaN(x) || x <= 0)
                return true;
        }
        return false;
    }
}

//      
function isRaster(data) {
    return data instanceof window$1.ImageData || data instanceof window$1.HTMLCanvasElement || data instanceof window$1.ImageBitmap || data instanceof window$1.HTMLImageElement;
}
/* eslint-disable jsdoc/check-examples */
/**
 * Interface for custom sources. This is a specification for
 * implementers to model: it is not an exported method or class.
 *
 * Custom sources allow a user to load and modify their own tiles.
 * These sources can be added between any regular sources using {@link Map#addSource}.
 *
 * Custom sources must have a unique `id` and must have the `type` of `"custom"`.
 * They must implement `loadTile` and may implement `unloadTile`, `onAdd` and `onRemove`.
 * They can trigger rendering using {@link Map#triggerRepaint}.
 *
 * @interface CustomSourceInterface
 * @property {string} id A unique source id.
 * @property {string} type The source's type. Must be `"custom"`.
 * @example
 * // Custom source implemented as ES6 class
 * class CustomSource {
 *     constructor() {
 *         this.id = 'custom-source';
 *         this.type = 'custom';
 *         this.tileSize = 256;
 *         this.tilesUrl = 'https://stamen-tiles.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.jpg';
 *         this.attribution = 'Map tiles by Stamen Design, under CC BY 3.0';
 *     }
 *
 *     async loadTile(tile, {signal}) {
 *         const url = this.tilesUrl
 *             .replace('{z}', String(tile.z))
 *             .replace('{x}', String(tile.x))
 *             .replace('{y}', String(tile.y));
 *
 *         const response = await fetch(url, {signal});
 *         const data = await response.arrayBuffer();
 *
 *         const blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'});
 *         const imageBitmap = await window.createImageBitmap(blob);
 *
 *         return imageBitmap;
 *     }
 * }
 *
 * map.on('load', () => {
 *     map.addSource('custom-source', new CustomSource());
 *     map.addLayer({
 *         id: 'layer',
 *         type: 'raster',
 *         source: 'custom-source'
 *     });
 * });
 */
/* eslint-enable jsdoc/check-examples */
/**
 * Optional method called when the source has been added to the Map with {@link Map#addSource}.
 * This gives the source a chance to initialize resources and register event listeners.
 *
 * @function
 * @memberof CustomSourceInterface
 * @instance
 * @name onAdd
 * @param {Map} map The Map this custom source was just added to.
 */
/**
 * Optional method called when the source has been removed from the Map with {@link Map#removeSource}.
 * This gives the source a chance to clean up resources and event listeners.
 *
 * @function
 * @memberof CustomSourceInterface
 * @instance
 * @name onRemove
 * @param {Map} map The Map this custom source was added to.
 */
/**
 * Optional method called after the tile is unloaded from the map viewport. This
 * gives the source a chance to clean up resources and event listeners.
 *
 * @function
 * @memberof CustomSourceInterface
 * @instance
 * @name unloadTile
 * @param {{ z: number, x: number, y: number }} tile Tile name to unload in the XYZ scheme format.
 */
/**
 * Optional method called during a render frame to check if there is a tile to render.
 *
 * @function
 * @memberof CustomSourceInterface
 * @instance
 * @name hasTile
 * @param {{ z: number, x: number, y: number }} tile Tile name to prepare in the XYZ scheme format.
 * @returns {boolean} True if tile exists, otherwise false.
 */
/**
 * Called when the map starts loading tile for the current animation frame.
 *
 * @function
 * @memberof CustomSourceInterface
 * @instance
 * @name loadTile
 * @param {{ z: number, x: number, y: number }} tile Tile name to load in the XYZ scheme format.
 * @param {Object} options Options.
 * @param {AbortSignal} options.signal A signal object that communicates when the map cancels the tile loading request.
 * @returns {Promise<TextureImage | undefined | null>} The promise that resolves to the tile image data as an `HTMLCanvasElement`, `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`.
 *     If `loadTile` resolves to `undefined`, a map will render an overscaled parent tile in the tile’s space. If `loadTile` resolves to `null`, a map will render nothing in the tile’s space.
 */
class CustomSource extends Evented {
    constructor(id, implementation, dispatcher, eventedParent) {
        super();
        this.id = id;
        this.type = 'custom';
        this._dataType = 'raster';
        this._dispatcher = dispatcher;
        this._implementation = implementation;
        this.setEventedParent(eventedParent);
        this.scheme = 'xyz';
        this.minzoom = 0;
        this.maxzoom = 22;
        this.tileSize = 512;
        this._loaded = false;
        this.roundZoom = true;
        if (!this._implementation) {
            this.fire(new ErrorEvent(new Error(`Missing implementation for ${ this.id } custom source`)));
        }
        if (!this._implementation.loadTile) {
            this.fire(new ErrorEvent(new Error(`Missing loadTile implementation for ${ this.id } custom source`)));
        }
        if (this._implementation.bounds) {
            this.tileBounds = new TileBounds(this._implementation.bounds, this.minzoom, this.maxzoom);
        }
        // $FlowFixMe[prop-missing]
        // $FlowFixMe[method-unbinding]
        implementation.update = this._update.bind(this);
        // $FlowFixMe[prop-missing]
        // $FlowFixMe[method-unbinding]
        implementation.clearTiles = this._clearTiles.bind(this);
        // $FlowFixMe[prop-missing]
        // $FlowFixMe[method-unbinding]
        implementation.coveringTiles = this._coveringTiles.bind(this);
        extend$1(this, pick(implementation, [
            'dataType',
            'scheme',
            'minzoom',
            'maxzoom',
            'tileSize',
            'attribution',
            'minTileCacheSize',
            'maxTileCacheSize'
        ]));
    }
    serialize() {
        return pick(this, [
            'type',
            'scheme',
            'minzoom',
            'maxzoom',
            'tileSize',
            'attribution'
        ]);
    }
    load() {
        this._loaded = true;
        this.fire(new Event('data', {
            dataType: 'source',
            sourceDataType: 'metadata'
        }));
        this.fire(new Event('data', {
            dataType: 'source',
            sourceDataType: 'content'
        }));
    }
    loaded() {
        return this._loaded;
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this._map = map;
        this._loaded = false;
        this.fire(new Event('dataloading', { dataType: 'source' }));
        if (this._implementation.onAdd)
            this._implementation.onAdd(map);
        this.load();
    }
    // $FlowFixMe[method-unbinding]
    onRemove(map) {
        if (this._implementation.onRemove) {
            this._implementation.onRemove(map);
        }
    }
    // $FlowFixMe[method-unbinding]
    hasTile(tileID) {
        if (this._implementation.hasTile) {
            const {x, y, z} = tileID.canonical;
            return this._implementation.hasTile({
                x,
                y,
                z
            });
        }
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    loadTile(tile, callback) {
        const {x, y, z} = tile.tileID.canonical;
        const controller = new window$1.AbortController();
        const signal = controller.signal;
        // $FlowFixMe[prop-missing]
        tile.request = Promise.resolve(this._implementation.loadTile({
            x,
            y,
            z
        }, { signal })).then(tileLoaded.bind(this)).catch(error => {
            // silence AbortError
            if (error.code === 20)
                return;
            tile.state = 'errored';
            callback(error);
        });
        // $FlowFixMe[prop-missing]
        tile.request.cancel = () => controller.abort();
        // $FlowFixMe[missing-this-annot]
        function tileLoaded(data) {
            delete tile.request;
            if (tile.aborted) {
                tile.state = 'unloaded';
                return callback(null);
            }
            // If the implementation returned `undefined` as tile data,
            // mark the tile as `errored` to indicate that we have no data for it.
            // A map will render an overscaled parent tile in the tile’s space.
            if (data === undefined) {
                tile.state = 'errored';
                return callback(null);
            }
            // If the implementation returned `null` as tile data,
            // mark the tile as `loaded` and use an an empty image as tile data.
            // A map will render nothing in the tile’s space.
            if (data === null) {
                const emptyImage = {
                    width: this.tileSize,
                    height: this.tileSize,
                    data: null
                };
                this.loadTileData(tile, emptyImage);
                tile.state = 'loaded';
                return callback(null);
            }
            if (!isRaster(data)) {
                tile.state = 'errored';
                return callback(new Error(`Can't infer data type for ${ this.id }, only raster data supported at the moment`));
            }
            this.loadTileData(tile, data);
            tile.state = 'loaded';
            callback(null);
        }
    }
    loadTileData(tile, data) {
        // Only raster data supported at the moment
        RasterTileSource.loadTileData(tile, data, this._map.painter);
    }
    unloadTileData(tile) {
        // Only raster data supported at the moment
        RasterTileSource.unloadTileData(tile, this._map.painter);
    }
    // $FlowFixMe[method-unbinding]
    unloadTile(tile, callback) {
        this.unloadTileData(tile);
        if (this._implementation.unloadTile) {
            const {x, y, z} = tile.tileID.canonical;
            this._implementation.unloadTile({
                x,
                y,
                z
            });
        }
        callback();
    }
    // $FlowFixMe[method-unbinding]
    abortTile(tile, callback) {
        if (tile.request && tile.request.cancel) {
            tile.request.cancel();
            delete tile.request;
        }
        callback();
    }
    hasTransition() {
        return false;
    }
    _coveringTiles() {
        const tileIDs = this._map.transform.coveringTiles({
            tileSize: this.tileSize,
            minzoom: this.minzoom,
            maxzoom: this.maxzoom,
            roundZoom: this.roundZoom
        });
        return tileIDs.map(tileID => ({
            x: tileID.canonical.x,
            y: tileID.canonical.y,
            z: tileID.canonical.z
        }));
    }
    _clearTiles() {
        const fqid = makeFQID(this.id, this.scope);
        this._map.style.clearSource(fqid);
    }
    _update() {
        this.fire(new Event('data', {
            dataType: 'source',
            sourceDataType: 'content'
        }));
    }
}

//      
function WebWorker () {
    return exported.workerClass != null ? new exported.workerClass() : new window$1.Worker(exported.workerUrl);    // eslint-disable-line new-cap
}

//      
const PRELOAD_POOL_ID = 'mapboxgl_preloaded_worker_pool';
/**
 * Constructs a worker pool.
 * @private
 */
class WorkerPool {
    constructor() {
        this.active = {};
    }
    acquire(mapId) {
        if (!this.workers) {
            // Lazily look up the value of mapboxgl.workerCount so that
            // client code has had a chance to set it.
            this.workers = [];
            while (this.workers.length < WorkerPool.workerCount) {
                // $FlowFixMe[invalid-constructor]
                this.workers.push(new WebWorker());
            }
        }
        this.active[mapId] = true;
        return this.workers.slice();
    }
    release(mapId) {
        delete this.active[mapId];
        if (this.workers && this.numActive() === 0) {
            this.workers.forEach(w => {
                w.terminate();
            });
            this.workers = null;
        }
    }
    isPreloaded() {
        return !!this.active[PRELOAD_POOL_ID];
    }
    numActive() {
        return Object.keys(this.active).length;
    }
}
// extensive benchmarking showed 2 to be the best default for both desktop and mobile devices;
// we can't rely on hardwareConcurrency because of wild inconsistency of reported numbers between browsers
WorkerPool.workerCount = 2;

//      
let globalWorkerPool;
/**
 * Creates (if necessary) and returns the single, global WorkerPool instance
 * to be shared across each Map
 * @private
 */
function getGlobalWorkerPool() {
    if (!globalWorkerPool) {
        globalWorkerPool = new WorkerPool();
    }
    return globalWorkerPool;
}
function prewarm() {
    const workerPool = getGlobalWorkerPool();
    workerPool.acquire(PRELOAD_POOL_ID);
}
function clearPrewarmedResources() {
    const pool = globalWorkerPool;
    if (pool) {
        // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed.
        if (pool.isPreloaded() && pool.numActive() === 1) {
            pool.release(PRELOAD_POOL_ID);
            globalWorkerPool = null;
        } else {
            console.warn('Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()');
        }
    }
}

/* global WebAssembly: false */
/* eslint-disable new-cap, flowtype/require-valid-file-annotation */
// Emscripten-based JavaScript wrapper for Google Draco WASM decoder, manually optimized for much smaller size
function DracoDecoderModule(wasmPromise) {
    let HEAPU8, wasmMemory = null;
    function updateMemoryViews() {
        HEAPU8 = new Uint8Array(wasmMemory.buffer);
    }
    function abort() {
        throw new Error('Unexpected Draco error.');
    }
    function memcpyBig(dest, src, num) {
        return HEAPU8.copyWithin(dest, src, src + num);
    }
    function resizeHeap(requestedSize) {
        const oldSize = HEAPU8.length;
        const newSize = Math.max(requestedSize >>> 0, Math.ceil(oldSize * 1.2));
        const pages = Math.ceil((newSize - oldSize) / 65536);
        try {
            wasmMemory.grow(pages);
            updateMemoryViews();
            return true;
        } catch (e) {
            return false;
        }
    }
    const wasmImports = {
        a: {
            a: abort,
            d: memcpyBig,
            c: resizeHeap,
            b: abort
        }
    };
    const instantiateWasm = WebAssembly.instantiateStreaming ? WebAssembly.instantiateStreaming(wasmPromise, wasmImports) : wasmPromise.then(wasm => wasm.arrayBuffer()).then(buffer => WebAssembly.instantiate(buffer, wasmImports));
    return instantiateWasm.then(output => {
        // minified exports values might change when recompiling Draco WASM, to be manually updated on version ugprade
        const {
            Rb: _free,
            Qb: _malloc,
            P: _Mesh,
            T: _MeshDestroy,
            X: _StatusOK,
            Ja: _Decoder,
            La: _DecoderDecodeArrayToMesh,
            Qa: _DecoderGetAttributeByUniqueId,
            Va: _DecoderGetTrianglesUInt16Array,
            Wa: _DecoderGetTrianglesUInt32Array,
            eb: _DecoderGetAttributeDataArrayForAllPoints,
            jb: _DecoderDestroy,
            f: initRuntime,
            e: memory,
            yb: getINT8,
            zb: getUINT8,
            Ab: getINT16,
            Bb: getUINT16,
            Db: getUINT32,
            Gb: getFLOAT32
        } = output.instance.exports;
        wasmMemory = memory;
        const ensureCache = ((() => {
            let buffer = 0;
            let size = 0;
            let needed = 0;
            let temp = 0;
            return array => {
                if (needed) {
                    _free(temp);
                    _free(buffer);
                    size += needed;
                    needed = buffer = 0;
                }
                if (!buffer) {
                    size += 128;
                    buffer = _malloc(size);
                }
                const len = array.length + 7 & -8;
                let offset = buffer;
                if (len >= size) {
                    needed = len;
                    offset = temp = _malloc(len);
                }
                for (let i = 0; i < array.length; i++) {
                    HEAPU8[offset + i] = array[i];
                }
                return offset;
            };
        })());
        class Mesh {
            constructor() {
                this.ptr = _Mesh();
            }
            destroy() {
                _MeshDestroy(this.ptr);
            }
        }
        class Decoder {
            constructor() {
                this.ptr = _Decoder();
            }
            destroy() {
                _DecoderDestroy(this.ptr);
            }
            DecodeArrayToMesh(data, dataSize, outMesh) {
                const offset = ensureCache(data);
                const status = _DecoderDecodeArrayToMesh(this.ptr, offset, dataSize, outMesh.ptr);
                return !!_StatusOK(status);
            }
            GetAttributeByUniqueId(pc, id) {
                return { ptr: _DecoderGetAttributeByUniqueId(this.ptr, pc.ptr, id) };
            }
            GetTrianglesUInt16Array(m, outSize, outValues) {
                _DecoderGetTrianglesUInt16Array(this.ptr, m.ptr, outSize, outValues);
            }
            GetTrianglesUInt32Array(m, outSize, outValues) {
                _DecoderGetTrianglesUInt32Array(this.ptr, m.ptr, outSize, outValues);
            }
            GetAttributeDataArrayForAllPoints(pc, pa, dataType, outSize, outValues) {
                _DecoderGetAttributeDataArrayForAllPoints(this.ptr, pc.ptr, pa.ptr, dataType, outSize, outValues);
            }
        }
        updateMemoryViews();
        initRuntime();
        return {
            memory,
            _free,
            _malloc,
            Mesh,
            Decoder,
            DT_INT8: getINT8(),
            DT_UINT8: getUINT8(),
            DT_INT16: getINT16(),
            DT_UINT16: getUINT16(),
            DT_UINT32: getUINT32(),
            DT_FLOAT32: getFLOAT32()
        };
    });
}

//      
/* global self: false */
/* eslint-disable new-cap */
let dispatcher = null;
let dracoLoading;
let dracoUrl;
let draco;
function getDracoUrl() {
    if (isWorker() && self.worker && self.worker.dracoUrl) {
        return self.worker.dracoUrl;
    }
    return dracoUrl ? dracoUrl : config.DRACO_URL;
}
function setDracoUrl(url) {
    dracoUrl = exported$1.resolveURL(url);
    if (!dispatcher) {
        dispatcher = new Dispatcher(getGlobalWorkerPool(), new Evented());
    }
    // Sets the Draco URL in all workers.
    dispatcher.broadcast('setDracoUrl', dracoUrl);
}
function waitForDraco() {
    if (draco)
        return;
    if (dracoLoading)
        return dracoLoading;
    dracoLoading = DracoDecoderModule(fetch(getDracoUrl()));
    return dracoLoading.then(module => {
        draco = module;
        dracoLoading = undefined;
    });
}
const GLTF_BYTE = 5120;
const GLTF_UBYTE = 5121;
const GLTF_SHORT = 5122;
const GLTF_USHORT = 5123;
const GLTF_UINT = 5125;
const GLTF_FLOAT = 5126;
const GLTF_TO_ARRAY_TYPE = {
    [GLTF_BYTE]: Int8Array,
    [GLTF_UBYTE]: Uint8Array,
    [GLTF_SHORT]: Int16Array,
    [GLTF_USHORT]: Uint16Array,
    [GLTF_UINT]: Uint32Array,
    [GLTF_FLOAT]: Float32Array
};
const GLTF_TO_DRACO_TYPE = {
    [GLTF_BYTE]: 'DT_INT8',
    [GLTF_UBYTE]: 'DT_UINT8',
    [GLTF_SHORT]: 'DT_INT16',
    [GLTF_USHORT]: 'DT_UINT16',
    [GLTF_UINT]: 'DT_UINT32',
    [GLTF_FLOAT]: 'DT_FLOAT32'
};
const GLTF_COMPONENTS = {
    SCALAR: 1,
    VEC2: 2,
    VEC3: 3,
    VEC4: 4,
    MAT2: 4,
    MAT3: 9,
    MAT4: 16
};
function setAccessorBuffer(buffer, accessor, gltf) {
    const bufferViewIndex = gltf.json.bufferViews.length;
    const bufferIndex = gltf.buffers.length;
    accessor.bufferView = bufferViewIndex;
    gltf.json.bufferViews[bufferViewIndex] = {
        buffer: bufferIndex,
        byteLength: buffer.byteLength
    };
    gltf.buffers[bufferIndex] = buffer;
}
const DRACO_EXT = 'KHR_draco_mesh_compression';
function loadDracoMesh(primitive, gltf) {
    const config = primitive.extensions && primitive.extensions[DRACO_EXT];
    if (!config)
        return;
    const decoder = new draco.Decoder();
    const bytes = getGLTFBytes(gltf, config.bufferView);
    const mesh = new draco.Mesh();
    const ok = decoder.DecodeArrayToMesh(bytes, bytes.byteLength, mesh);
    if (!ok)
        throw new Error('Failed to decode Draco mesh');
    const indexAccessor = gltf.json.accessors[primitive.indices];
    const IndexArrayType = GLTF_TO_ARRAY_TYPE[indexAccessor.componentType];
    const indicesSize = indexAccessor.count * IndexArrayType.BYTES_PER_ELEMENT;
    const ptr = draco._malloc(indicesSize);
    if (IndexArrayType === Uint16Array) {
        decoder.GetTrianglesUInt16Array(mesh, indicesSize, ptr);
    } else {
        decoder.GetTrianglesUInt32Array(mesh, indicesSize, ptr);
    }
    const indicesBuffer = draco.memory.buffer.slice(ptr, ptr + indicesSize);
    setAccessorBuffer(indicesBuffer, indexAccessor, gltf);
    draco._free(ptr);
    for (const attributeId of Object.keys(config.attributes)) {
        const attribute = decoder.GetAttributeByUniqueId(mesh, config.attributes[attributeId]);
        const accessor = gltf.json.accessors[primitive.attributes[attributeId]];
        const ArrayType = GLTF_TO_ARRAY_TYPE[accessor.componentType];
        const dracoTypeName = GLTF_TO_DRACO_TYPE[accessor.componentType];
        const numComponents = GLTF_COMPONENTS[accessor.type];
        const numValues = accessor.count * numComponents;
        const dataSize = numValues * ArrayType.BYTES_PER_ELEMENT;
        const ptr = draco._malloc(dataSize);
        decoder.GetAttributeDataArrayForAllPoints(mesh, attribute, draco[dracoTypeName], dataSize, ptr);
        const buffer = draco.memory.buffer.slice(ptr, ptr + dataSize);
        setAccessorBuffer(buffer, accessor, gltf);
        draco._free(ptr);
    }
    decoder.destroy();
    mesh.destroy();
    delete primitive.extensions[DRACO_EXT];
}
const MAGIC_GLTF = 1179937895;
const textDecoder = new TextDecoder('utf8');
function resolveUrl(url, baseUrl) {
    return new URL(url, baseUrl).href;
}
function loadBuffer(buffer, gltf, index, baseUrl) {
    return fetch(resolveUrl(buffer.uri, baseUrl)).then(response => response.arrayBuffer()).then(arrayBuffer => {
        gltf.buffers[index] = arrayBuffer;
    });
}
function getGLTFBytes(gltf, bufferViewIndex) {
    const bufferView = gltf.json.bufferViews[bufferViewIndex];
    const buffer = gltf.buffers[bufferView.buffer];
    return new Uint8Array(buffer, bufferView.byteOffset || 0, bufferView.byteLength);
}
function loadImage(img, gltf, index, baseUrl) {
    if (img.uri) {
        const uri = resolveUrl(img.uri, baseUrl);
        return fetch(uri).then(response => response.blob()).then(blob => window$1.createImageBitmap(blob)).then(imageBitmap => {
            gltf.images[index] = imageBitmap;
        });
    } else if (img.bufferView !== undefined) {
        const bytes = getGLTFBytes(gltf, img.bufferView);
        const blob = new window$1.Blob([bytes], { type: img.mimeType });
        return window$1.createImageBitmap(blob).then(imageBitmap => {
            gltf.images[index] = imageBitmap;
        });
    }
}
function decodeGLTF(arrayBuffer, byteOffset = 0, baseUrl) {
    const gltf = {
        json: null,
        images: [],
        buffers: []
    };
    if (new Uint32Array(arrayBuffer, byteOffset, 1)[0] === MAGIC_GLTF) {
        const view = new Uint32Array(arrayBuffer, byteOffset);
        let pos = 2;
        const glbLen = (view[pos++] >> 2) - 3;
        const jsonLen = view[pos++] >> 2;
        view[pos++];
        gltf.json = JSON.parse(textDecoder.decode(view.subarray(pos, pos + jsonLen)));
        pos += jsonLen;
        if (pos < glbLen) {
            const byteLength = view[pos++];
            view[pos++];
            const start = byteOffset + (pos << 2);
            gltf.buffers[0] = arrayBuffer.slice(start, start + byteLength);
        }
    } else {
        gltf.json = JSON.parse(textDecoder.decode(new Uint8Array(arrayBuffer, byteOffset)));
    }
    const {buffers, images, meshes, extensionsUsed} = gltf.json;
    let bufferLoadsPromise = Promise.resolve();
    if (buffers) {
        const bufferLoads = [];
        for (let i = 0; i < buffers.length; i++) {
            const buffer = buffers[i];
            if (buffer.uri) {
                bufferLoads.push(loadBuffer(buffer, gltf, i, baseUrl));
            } else if (!gltf.buffers[i]) {
                gltf.buffers[i] = null;
            }
        }
        bufferLoadsPromise = Promise.all(bufferLoads);
    }
    return bufferLoadsPromise.then(() => {
        const assetLoads = [];
        const dracoUsed = extensionsUsed && extensionsUsed.includes(DRACO_EXT);
        if (dracoUsed) {
            assetLoads.push(waitForDraco());
        }
        if (images) {
            for (let i = 0; i < images.length; i++) {
                assetLoads.push(loadImage(images[i], gltf, i, baseUrl));
            }
        }
        const assetLoadsPromise = assetLoads.length ? Promise.all(assetLoads) : Promise.resolve();
        return assetLoadsPromise.then(() => {
            if (dracoUsed && meshes) {
                for (const {primitives} of meshes) {
                    for (const primitive of primitives) {
                        loadDracoMesh(primitive, gltf);
                    }
                }
            }
            return gltf;
        });
    });
}
function loadGLTF(url) {
    return fetch(url).then(response => response.arrayBuffer()).then(buffer => decodeGLTF(buffer, 0, url));
}
function load3DTile(data) {
    const magic = new Uint32Array(data, 0, 1)[0];
    let gltfOffset = 0;
    if (magic !== MAGIC_GLTF) {
        const header = new Uint32Array(data, 0, 7);
        const [, , byteLen, featureTableJsonLen, featureTableBinLen, batchTableJsonLen    /*, batchTableBinLen*/] = header;
        gltfOffset = header.byteLength + featureTableJsonLen + featureTableBinLen + batchTableJsonLen + featureTableBinLen;
        if (byteLen !== data.byteLength || gltfOffset >= data.byteLength) {
            warnOnce('Invalid b3dm header information.');
        }
    }
    return decodeGLTF(data, gltfOffset);
}

//      
/**
 * TriangleGridIndex is a specialized GridIndex data structure optimized
 * for querying potentially intersecting triangles in a 2d plane. Once built,
 * the data structure is immutable.
 *
 * @private
 */
class TriangleGridIndex {
    constructor(vertices, indices, cellCount) {
        this.triangleCount = indices.length / 3;
        this.min = new Point$2(0, 0);
        this.max = new Point$2(0, 0);
        this.xScale = 0;
        this.yScale = 0;
        this.cellsX = 0;
        this.cellsY = 0;
        this.cells = [];
        this.payload = [];
        if (this.triangleCount === 0 || vertices.length === 0 || cellCount === 0) {
            return;
        }
        // Compute cell size from the input
        const xCoords = vertices.map(v => v.x);
        const yCoords = vertices.map(v => v.y);
        this.min = new Point$2(Math.min(...xCoords), Math.min(...yCoords));
        this.max = new Point$2(Math.max(...xCoords), Math.max(...yCoords));
        const size = this.max.sub(this.min);
        size.x = Math.max(size.x, 1);
        size.y = Math.max(size.y, 1);
        const maxExt = Math.max(size.x, size.y);
        const cellSize = maxExt / cellCount;
        this.cellsX = Math.max(1, Math.ceil(size.x / cellSize));
        this.cellsY = Math.max(1, Math.ceil(size.y / cellSize));
        this.xScale = 1 / cellSize;
        this.yScale = 1 / cellSize;
        const associatedTriangles = [];
        // For each triangle find all intersecting cells
        for (let t = 0; t < this.triangleCount; t++) {
            const v0 = vertices[indices[t * 3 + 0]].sub(this.min);
            const v1 = vertices[indices[t * 3 + 1]].sub(this.min);
            const v2 = vertices[indices[t * 3 + 2]].sub(this.min);
            const minx = toCellIdx(Math.floor(Math.min(v0.x, v1.x, v2.x)), this.xScale, this.cellsX);
            const maxx = toCellIdx(Math.floor(Math.max(v0.x, v1.x, v2.x)), this.xScale, this.cellsX);
            const miny = toCellIdx(Math.floor(Math.min(v0.y, v1.y, v2.y)), this.yScale, this.cellsY);
            const maxy = toCellIdx(Math.floor(Math.max(v0.y, v1.y, v2.y)), this.yScale, this.cellsY);
            // Pre-allocate corner points of a cell
            const c00 = new Point$2(0, 0);
            const c10 = new Point$2(0, 0);
            const c01 = new Point$2(0, 0);
            const c11 = new Point$2(0, 0);
            for (let y = miny; y <= maxy; ++y) {
                c00.y = c10.y = y * cellSize;
                c01.y = c11.y = (y + 1) * cellSize;
                for (let x = minx; x <= maxx; ++x) {
                    c00.x = c01.x = x * cellSize;
                    c10.x = c11.x = (x + 1) * cellSize;
                    if (!triangleIntersectsTriangle(v0, v1, v2, c00, c10, c11) && !triangleIntersectsTriangle(v0, v1, v2, c00, c11, c01)) {
                        continue;
                    }
                    associatedTriangles.push({
                        cellIdx: y * this.cellsX + x,
                        triIdx: t
                    });
                }
            }
        }
        if (associatedTriangles.length === 0) {
            return;
        }
        // Store cell payload (a list of contained triangles) in adjacent memory cell by cell
        associatedTriangles.sort((a, b) => a.cellIdx - b.cellIdx || a.triIdx - b.triIdx);
        let idx = 0;
        while (idx < associatedTriangles.length) {
            const cellIdx = associatedTriangles[idx].cellIdx;
            const cell = {
                start: this.payload.length,
                len: 0
            };
            // Find all triangles belonging to the current cell
            while (idx < associatedTriangles.length && associatedTriangles[idx].cellIdx === cellIdx) {
                ++cell.len;
                this.payload.push(associatedTriangles[idx++].triIdx);
            }
            this.cells[cellIdx] = cell;
        }
    }
    query(bbMin, bbMax, out) {
        if (this.triangleCount === 0 || this.cells.length === 0) {
            return;
        }
        if (bbMin.x > this.max.x || this.min.x > bbMax.x) {
            return;
        } else if (bbMin.y > this.max.y || this.min.y > bbMax.y) {
            return;
        }
        // Use a bitset for lookups
        if (!this.lookup) {
            this.lookup = new Uint8Array(Math.ceil(this.triangleCount / 8));
        }
        for (let i = 0; i < this.lookup.length; i++) {
            this.lookup[i] = 0;
        }
        const mnx = toCellIdx(bbMin.x - this.min.x, this.xScale, this.cellsX);
        const mxx = toCellIdx(bbMax.x - this.min.x, this.xScale, this.cellsX);
        const mny = toCellIdx(bbMin.y - this.min.y, this.yScale, this.cellsY);
        const mxy = toCellIdx(bbMax.y - this.min.y, this.yScale, this.cellsY);
        for (let y = mny; y <= mxy; y++) {
            for (let x = mnx; x <= mxx; x++) {
                const cell = this.cells[y * this.cellsX + x];
                if (!cell) {
                    continue;
                }
                for (let i = 0; i < cell.len; i++) {
                    const triIdx = this.payload[cell.start + i];
                    // Check the lookup bitset if the triangle has been visited already
                    const byte = Math.floor(triIdx / 8);
                    const bit = 1 << triIdx % 8;
                    if (this.lookup[byte] & bit) {
                        continue;
                    }
                    this.lookup[byte] |= bit;
                    out.push(triIdx);
                    if (out.length === this.triangleCount) {
                        // All triangles visited already
                        return;
                    }
                }
            }
        }
    }
}
function toCellIdx(p, scale, cells) {
    return Math.max(0, Math.min(cells - 1, Math.floor(p * scale)));
}
register(TriangleGridIndex, 'TriangleGridIndex');

//      
function convertTextures(gltf, images) {
    const textures = [];
    const gl = window$1.WebGL2RenderingContext;
    if (gltf.json.textures) {
        for (const textureDesc of gltf.json.textures) {
            const sampler = {
                magFilter: gl.LINEAR,
                minFilter: gl.NEAREST,
                wrapS: gl.REPEAT,
                wrapT: gl.REPEAT
            };
            if (textureDesc.sampler !== undefined)
                Object.assign(sampler, gltf.json.samplers[textureDesc.sampler]);
            textures.push({
                image: images[textureDesc.source],
                sampler,
                uploaded: false
            });
        }
    }
    return textures;
}
function getBufferData(gltf, accessor) {
    const bufferView = gltf.json.bufferViews[accessor.bufferView];
    const buffer = gltf.buffers[bufferView.buffer];
    const offset = (accessor.byteOffset || 0) + (bufferView.byteOffset || 0);
    const ArrayType = GLTF_TO_ARRAY_TYPE[accessor.componentType];
    const bufferData = new ArrayType(buffer, offset, accessor.count * GLTF_COMPONENTS[accessor.type]);
    return bufferData;
}
function convertMaterial(materialDesc, textures) {
    const {emissiveFactor = [
            0,
            0,
            0
        ], alphaMode = 'OPAQUE', alphaCutoff = 0.5, normalTexture, occlusionTexture, emissiveTexture, doubleSided} = materialDesc;
    const {baseColorFactor = [
            1,
            1,
            1,
            1
        ], metallicFactor = 1, roughnessFactor = 1, baseColorTexture, metallicRoughnessTexture} = materialDesc.pbrMetallicRoughness || {};
    return {
        pbrMetallicRoughness: {
            baseColorFactor: new Color$1(...baseColorFactor),
            metallicFactor,
            roughnessFactor,
            baseColorTexture: baseColorTexture ? textures[baseColorTexture.index] : undefined,
            metallicRoughnessTexture: metallicRoughnessTexture ? textures[metallicRoughnessTexture.index] : undefined
        },
        doubleSided,
        emissiveFactor,
        alphaMode,
        alphaCutoff,
        normalTexture: normalTexture ? textures[normalTexture.index] : undefined,
        occlusionTexture: occlusionTexture ? textures[occlusionTexture.index] : undefined,
        emissionTexture: emissiveTexture ? textures[emissiveTexture.index] : undefined,
        defined: materialDesc.defined === undefined    // just to make the rendertests the same than native
    };
}
function computeCentroid(indexArray, vertexArray) {
    const out = [
        0,
        0,
        0
    ];
    const indexSize = indexArray.length;
    if (indexSize > 0) {
        for (let i = 0; i < indexSize; i++) {
            const index = indexArray[i] * 3;
            out[0] += vertexArray[index];
            out[1] += vertexArray[index + 1];
            out[2] += vertexArray[index + 2];
        }
        out[0] /= indexSize;
        out[1] /= indexSize;
        out[2] /= indexSize;
    }
    return out;
}
function convertPrimitive(primitive, gltf, textures) {
    const indicesIdx = primitive.indices;
    const attributeMap = primitive.attributes;
    const mesh = {};
    // eslint-disable-next-line no-warning-comments
    // TODO: Investigate a better way to pass arrays to StructArrays and avoid the double componentType indices
    mesh.indexArray = new StructArrayLayout3ui6();
    // eslint-disable-next-line no-warning-comments
    // TODO: There might be no need to copy element by element to mesh.indexArray.
    const indexAccessor = gltf.json.accessors[indicesIdx];
    const numTriangles = indexAccessor.count / 3;
    mesh.indexArray.reserve(numTriangles);
    const indexArrayBuffer = getBufferData(gltf, indexAccessor);
    for (let i = 0; i < numTriangles; i++) {
        mesh.indexArray.emplaceBack(indexArrayBuffer[i * 3], indexArrayBuffer[i * 3 + 1], indexArrayBuffer[i * 3 + 2]);
    }
    mesh.indexArray._trim();
    // vertices
    mesh.vertexArray = new StructArrayLayout3f12();
    const positionAccessor = gltf.json.accessors[attributeMap.POSITION];
    mesh.vertexArray.reserve(positionAccessor.count);
    const vertexArrayBuffer = getBufferData(gltf, positionAccessor);
    for (let i = 0; i < positionAccessor.count; i++) {
        mesh.vertexArray.emplaceBack(vertexArrayBuffer[i * 3], vertexArrayBuffer[i * 3 + 1], vertexArrayBuffer[i * 3 + 2]);
    }
    mesh.vertexArray._trim();
    // bounding box
    mesh.aabb = new Aabb(positionAccessor.min, positionAccessor.max);
    mesh.centroid = computeCentroid(indexArrayBuffer, vertexArrayBuffer);
    // colors
    if (attributeMap.COLOR_0 !== undefined) {
        const colorAccessor = gltf.json.accessors[attributeMap.COLOR_0];
        const numElements = GLTF_COMPONENTS[colorAccessor.type];
        // We only support colors in float and uint8 format for now
        if (colorAccessor.componentType === GLTF_FLOAT) {
            mesh.colorArray = numElements === 3 ? new StructArrayLayout3f12() : new StructArrayLayout4f16();
            mesh.colorArray.reserve(colorAccessor.count);
            const colorArrayBuffer = getBufferData(gltf, colorAccessor);
            if (numElements === 3) {
                // vec3f
                for (let i = 0; i < colorAccessor.count; i++) {
                    mesh.colorArray.emplaceBack(colorArrayBuffer[i * 3], colorArrayBuffer[i * 3 + 1], colorArrayBuffer[i * 3 + 2]);
                }
            } else {
                // vec4f
                for (let i = 0; i < colorAccessor.count; i++) {
                    mesh.colorArray.emplaceBack(colorArrayBuffer[i * 4], colorArrayBuffer[i * 4 + 1], colorArrayBuffer[i * 4 + 2], colorArrayBuffer[i * 4 + 3]);
                }
            }
            mesh.colorArray._trim();
        } else if (colorAccessor.componentType === GLTF_USHORT && numElements === 4) {
            mesh.colorArray = new StructArrayLayout4f16();
            mesh.colorArray.resize(colorAccessor.count);
            const colorArrayBuffer = getBufferData(gltf, colorAccessor);
            const norm = 1 / 65535;
            const float32Array = mesh.colorArray.float32;
            for (let i = 0; i < colorArrayBuffer.length * 4; ++i) {
                float32Array[i] = colorArrayBuffer[i] * norm;
            }
        } else {
            warnOnce(`glTF color buffer parsing for accessor ${ JSON.stringify(colorAccessor) } is not supported`);
        }
    }
    // normals
    if (attributeMap.NORMAL !== undefined) {
        mesh.normalArray = new StructArrayLayout3f12();
        const normalAccessor = gltf.json.accessors[attributeMap.NORMAL];
        mesh.normalArray.reserve(normalAccessor.count);
        const normalArrayBuffer = getBufferData(gltf, normalAccessor);
        for (let i = 0; i < normalAccessor.count; i++) {
            mesh.normalArray.emplaceBack(normalArrayBuffer[i * 3], normalArrayBuffer[i * 3 + 1], normalArrayBuffer[i * 3 + 2]);
        }
        mesh.normalArray._trim();
    }
    // texcoord
    if (attributeMap.TEXCOORD_0 !== undefined && textures.length > 0) {
        mesh.texcoordArray = new StructArrayLayout2f8();
        const texcoordAccessor = gltf.json.accessors[attributeMap.TEXCOORD_0];
        mesh.texcoordArray.reserve(texcoordAccessor.count);
        const texcoordArrayBuffer = getBufferData(gltf, texcoordAccessor);
        for (let i = 0; i < texcoordAccessor.count; i++) {
            mesh.texcoordArray.emplaceBack(texcoordArrayBuffer[i * 2], texcoordArrayBuffer[i * 2 + 1]);
        }
        mesh.texcoordArray._trim();
    }
    // Material
    const materialIdx = primitive.material;
    const materialDesc = materialIdx !== undefined ? gltf.json.materials[materialIdx] : { defined: false };
    mesh.material = convertMaterial(materialDesc, textures);
    if (attributeMap._FEATURE_RGBA4444 !== undefined) {
        const featureAccesor = gltf.json.accessors[attributeMap._FEATURE_RGBA4444];
        mesh.featureData = new Uint32Array(getBufferData(gltf, featureAccesor).buffer);
    }
    return mesh;
}
function convertMeshes(gltf, textures) {
    const meshes = [];
    for (const meshDesc of gltf.json.meshes) {
        const primitives = [];
        for (const primitive of meshDesc.primitives) {
            primitives.push(convertPrimitive(primitive, gltf, textures));
        }
        meshes.push(primitives);
    }
    return meshes;
}
function convertNode(nodeDesc, gltf, meshes) {
    const {matrix, rotation, translation, scale, mesh, extras, children} = nodeDesc;
    const node = {};
    node.matrix = matrix || mat4_1.fromRotationTranslationScale([], rotation || [
        0,
        0,
        0,
        1
    ], translation || [
        0,
        0,
        0
    ], scale || [
        1,
        1,
        1
    ]);
    if (mesh !== undefined) {
        node.meshes = meshes[mesh];
        const anchor = node.anchor = [
            0,
            0
        ];
        for (const mesh of node.meshes) {
            const {min, max} = mesh.aabb;
            anchor[0] += min[0] + max[0];
            anchor[1] += min[1] + max[1];
        }
        anchor[0] = Math.floor(anchor[0] / node.meshes.length / 2);
        anchor[1] = Math.floor(anchor[1] / node.meshes.length / 2);
    }
    if (extras) {
        if (extras.id) {
            node.id = extras.id;
        }
        if (extras.lights) {
            node.lights = decodeLights(extras.lights);
        }
    }
    if (children) {
        const converted = [];
        for (const childNodeIdx of children) {
            converted.push(convertNode(gltf.json.nodes[childNodeIdx], gltf, meshes));
        }
        node.children = converted;
    }
    return node;
}
function convertFootprint(mesh) {
    if (mesh.vertices.length === 0 || mesh.indices.length === 0) {
        return null;
    }
    const [min, max] = [
        mesh.vertices[0].clone(),
        mesh.vertices[0].clone()
    ];
    for (let i = 1; i < mesh.vertices.length; ++i) {
        const v = mesh.vertices[i];
        min.x = Math.min(min.x, v.x);
        min.y = Math.min(min.y, v.y);
        max.x = Math.max(max.x, v.x);
        max.y = Math.max(max.y, v.y);
    }
    // Use a fixed size triangle grid (8x8 cells) for acceleration intersection queries
    // with an exception that the cell size should never be larger than 256 tile units
    // (equals to 32x32 subdivision).
    const optimalCellCount = Math.ceil(Math.max(max.x - min.x, max.y - min.y) / 256);
    const cellCount = Math.max(8, optimalCellCount);
    const grid = new TriangleGridIndex(mesh.vertices, mesh.indices, cellCount);
    return {
        vertices: mesh.vertices,
        indices: mesh.indices,
        grid,
        min,
        max
    };
}
function parseLegacyFootprintMesh(gltfNode) {
    if (!gltfNode.extras || !gltfNode.extras.ground) {
        return null;
    }
    const groundContainer = gltfNode.extras.ground;
    if (!groundContainer || !Array.isArray(groundContainer) || groundContainer.length === 0) {
        return null;
    }
    const ground = groundContainer[0];
    if (!ground || !Array.isArray(ground) || ground.length === 0) {
        return null;
    }
    // Populate only the vertex list of the footprint mesh.
    const vertices = [];
    for (const point of ground) {
        if (!Array.isArray(point) || point.length !== 2) {
            continue;
        }
        const x = point[0];
        const y = point[1];
        if (typeof x !== 'number' || typeof y !== 'number') {
            continue;
        }
        vertices.push(new Point$2(x, y));
    }
    if (vertices.length < 3) {
        return null;
    }
    if (vertices.length > 1 && vertices[vertices.length - 1].equals(vertices[0])) {
        vertices.pop();
    }
    // Ensure that the vertex list is defined in CW order
    let cross = 0;
    for (let i = 0; i < vertices.length; i++) {
        const a = vertices[i];
        const b = vertices[(i + 1) % vertices.length];
        const c = vertices[(i + 2) % vertices.length];
        cross += (a.x - b.x) * (c.y - b.y) - (c.x - b.x) * (a.y - b.y);
    }
    if (cross > 0) {
        vertices.reverse();
    }
    // Triangulate the footprint and compute grid acceleration structure for
    // more performant intersection queries.
    const indices = earcut$1(vertices.flatMap(v => [
        v.x,
        v.y
    ]), []);
    if (indices.length === 0) {
        return null;
    }
    return {
        vertices,
        indices
    };
}
function parseNodeFootprintMesh(meshes) {
    const vertices = [];
    const indices = [];
    let baseVertex = 0;
    for (const mesh of meshes) {
        baseVertex = vertices.length;
        const vArray = mesh.vertexArray.float32;
        const iArray = mesh.indexArray.uint16;
        for (let i = 0; i < mesh.vertexArray.length; i++) {
            vertices.push(new Point$2(vArray[i * 3 + 0], vArray[i * 3 + 1]));
        }
        for (let i = 0; i < mesh.indexArray.length * 3; i++) {
            indices.push(iArray[i] + baseVertex);
        }
    }
    if (indices.length % 3 !== 0) {
        return null;
    }
    for (let i = 0; i < indices.length; i += 3) {
        const a = vertices[indices[i + 0]];
        const b = vertices[indices[i + 1]];
        const c = vertices[indices[i + 2]];
        if ((a.x - b.x) * (c.y - b.y) - (c.x - b.x) * (a.y - b.y) > 0) {
            // $FlowIssue[unsupported-syntax]
            [indices[i + 1], indices[i + 2]] = [
                indices[i + 2],
                indices[i + 1]
            ];
        }
    }
    return {
        vertices,
        indices
    };
}
function convertFootprints(convertedNodes, sceneNodes, modelNodes) {
    // Two different footprint formats are supported:
    //  1) Legacy format where footprints are defined as a linestring json
    //     inside extras-section of the node.
    //  2) Version "1" where footprints are included as regular gltf meshes and
    //     connected to correct models via matching ids.
    // Find footprint-only nodes from the list.
    const nodeFootprintLookup = {};
    const footprintNodeIndices = new Set();
    for (let i = 0; i < convertedNodes.length; i++) {
        const gltfNode = modelNodes[sceneNodes[i]];
        if (!gltfNode.extras) {
            continue;
        }
        const fpVersion = gltfNode.extras['mapbox:footprint:version'];
        const fpId = gltfNode.extras['mapbox:footprint:id'];
        if (fpVersion || fpId) {
            footprintNodeIndices.add(i);
        }
        if (fpVersion !== '1.0.0' || !fpId) {
            continue;
        }
        nodeFootprintLookup[fpId] = i;
    }
    // Go through nodes and see if either of the supported footprint formats are defined
    for (let i = 0; i < convertedNodes.length; i++) {
        if (footprintNodeIndices.has(i)) {
            continue;
        }
        const node = convertedNodes[i];
        const gltfNode = modelNodes[sceneNodes[i]];
        if (!gltfNode.extras) {
            continue;
        }
        // Prefer footprint nodes over the legacy format
        let fpMesh = null;
        if (node.id in nodeFootprintLookup) {
            fpMesh = parseNodeFootprintMesh(convertedNodes[nodeFootprintLookup[node.id]].meshes);
        }
        if (!fpMesh) {
            fpMesh = parseLegacyFootprintMesh(gltfNode);
        }
        if (fpMesh) {
            node.footprint = convertFootprint(fpMesh);
        }
    }
    // Remove footprint nodes as they serve no other purpose
    if (footprintNodeIndices.size > 0) {
        const nodesToRemove = Array.from(footprintNodeIndices.values()).sort((a, b) => a - b);
        for (let i = nodesToRemove.length - 1; i >= 0; i--) {
            convertedNodes.splice(nodesToRemove[i], 1);
        }
    }
}
function convertModel(gltf) {
    const textures = convertTextures(gltf, gltf.images);
    const meshes = convertMeshes(gltf, textures);
    // select the correct node hierarchy
    const {scenes, scene, nodes} = gltf.json;
    const gltfNodes = scenes ? scenes[scene || 0].nodes : nodes;
    const resultNodes = [];
    for (const nodeIdx of gltfNodes) {
        resultNodes.push(convertNode(nodes[nodeIdx], gltf, meshes));
    }
    convertFootprints(resultNodes, gltfNodes, gltf.json.nodes);
    return resultNodes;
}
function process3DTile(gltf, zScale) {
    const nodes = convertModel(gltf);
    for (const node of nodes) {
        for (const mesh of node.meshes) {
            parseHeightmap(mesh);
        }
        if (node.lights) {
            node.lightMeshIndex = node.meshes.length;
            node.meshes.push(createLightsMesh(node.lights, zScale));
        }
    }
    return nodes;
}
function parseHeightmap(mesh) {
    // This is a temporary, best effort approach, implementation that's to be removed, for Mapbox landmarks,
    // by a implementation in tiler. It would eventually still be used for 3d party models.
    mesh.heightmap = new Float32Array(HEIGHTMAP_DIM * HEIGHTMAP_DIM);
    mesh.heightmap.fill(-1);
    const vertices = mesh.vertexArray.float32;
    // implementation assumes tile coordinates for x and y and -1 and later +2
    // are to prevent going out of range
    const xMin = mesh.aabb.min[0] - 1;
    const yMin = mesh.aabb.min[1] - 1;
    const xMax = mesh.aabb.max[0];
    const yMax = mesh.aabb.max[1];
    const xRange = xMax - xMin + 2;
    const yRange = yMax - yMin + 2;
    const xCellInv = HEIGHTMAP_DIM / xRange;
    const yCellInv = HEIGHTMAP_DIM / yRange;
    for (let i = 0; i < vertices.length; i += 3) {
        const px = vertices[i + 0];
        const py = vertices[i + 1];
        const pz = vertices[i + 2];
        const x = (px - xMin) * xCellInv | 0;
        const y = (py - yMin) * yCellInv | 0;
        if (pz > mesh.heightmap[y * HEIGHTMAP_DIM + x]) {
            mesh.heightmap[y * HEIGHTMAP_DIM + x] = pz;
        }
    }
}
function createLightsMesh(lights, zScale) {
    const mesh = {};
    mesh.indexArray = new StructArrayLayout3ui6();
    mesh.indexArray.reserve(4 * lights.length);
    mesh.vertexArray = new StructArrayLayout3f12();
    mesh.vertexArray.reserve(10 * lights.length);
    mesh.colorArray = new StructArrayLayout4f16();
    mesh.vertexArray.reserve(10 * lights.length);
    let currentVertex = 0;
    // Model layer color4 attribute is used for light offset: first three components are light's offset in tile space (z
    // also in tile space) and 4th parameter is a decimal number that carries 2 parts: the distance to full light
    // falloff is in the integer part, and the decimal part represents the ratio of distance where the falloff starts (saturated
    // until it reaches that part).
    for (const light of lights) {
        // fallOff - light range from the door.
        const fallOff = Math.min(10, Math.max(4, 1.3 * light.height)) * zScale;
        const tangent = [
            -light.normal[1],
            light.normal[0],
            0
        ];
        // 0---3  (at light.height above light.points)
        // |   |
        // 1-p-2  (p for light.position at bottom edge)
        // horizontalSpread is tangent of the angle between light geometry and light normal.
        // Cap it for doors with large inset (depth) to prevent intersecting door posts.
        const horizontalSpread = Math.min(0.29, 0.1 * light.width / light.depth);
        // A simple geometry, that starts at door, starts towards the centre of door to prevent intersecting
        // door posts. Later, additional vertices at depth distance from door could be reconsidered.
        // 0.01f to prevent intersection with door post.
        const width = light.width - 2 * light.depth * zScale * (horizontalSpread + 0.01);
        const v1 = vec3_1.scaleAndAdd([], light.pos, tangent, width / 2);
        const v2 = vec3_1.scaleAndAdd([], light.pos, tangent, -width / 2);
        const v0 = [
            v1[0],
            v1[1],
            v1[2] + light.height
        ];
        const v3 = [
            v2[0],
            v2[1],
            v2[2] + light.height
        ];
        const v1extrusion = vec3_1.scaleAndAdd([], light.normal, tangent, horizontalSpread);
        vec3_1.scale(v1extrusion, v1extrusion, fallOff);
        const v2extrusion = vec3_1.scaleAndAdd([], light.normal, tangent, -horizontalSpread);
        vec3_1.scale(v2extrusion, v2extrusion, fallOff);
        vec3_1.add(v1extrusion, v1, v1extrusion);
        vec3_1.add(v2extrusion, v2, v2extrusion);
        v1[2] += 0.1;
        v2[2] += 0.1;
        mesh.vertexArray.emplaceBack(v1extrusion[0], v1extrusion[1], v1extrusion[2]);
        mesh.vertexArray.emplaceBack(v2extrusion[0], v2extrusion[1], v2extrusion[2]);
        mesh.vertexArray.emplaceBack(v1[0], v1[1], v1[2]);
        mesh.vertexArray.emplaceBack(v2[0], v2[1], v2[2]);
        // side: top
        mesh.vertexArray.emplaceBack(v0[0], v0[1], v0[2]);
        mesh.vertexArray.emplaceBack(v3[0], v3[1], v3[2]);
        // side
        mesh.vertexArray.emplaceBack(v1[0], v1[1], v1[2]);
        mesh.vertexArray.emplaceBack(v2[0], v2[1], v2[2]);
        mesh.vertexArray.emplaceBack(v1extrusion[0], v1extrusion[1], v1extrusion[2]);
        mesh.vertexArray.emplaceBack(v2extrusion[0], v2extrusion[1], v2extrusion[2]);
        // Light doesnt include light coordinates - instead it incldues offet to light area segment. Distances are
        // normalized by dividing by fallOff. Normalized lighting coordinate system is used where center of
        // coord system is on half of door and +Y is direction of extrusion.
        // z includes half width - this is used to calculate distance to segment.
        // 2 and 3 are bottom of the door, fully lit.
        const halfWidth = width / fallOff / 2;
        // right ground extruded looking out from door
        // x Coordinate is used to model angle (for spot)
        mesh.colorArray.emplaceBack(-halfWidth - horizontalSpread, -1, halfWidth, 0.8);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -1, halfWidth, 0.8);
        // keep shine at bottom of door even for reduced emissive strength
        mesh.colorArray.emplaceBack(-halfWidth, 0, halfWidth, 1.3);
        mesh.colorArray.emplaceBack(halfWidth, 0, halfWidth, 1.3);
        // for all vertices on the side, push the light origin behind the door top
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -0.8, halfWidth, 0.7);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -0.8, halfWidth, 0.7);
        // side at door, ground
        mesh.colorArray.emplaceBack(0, 0, halfWidth, 1.3);
        mesh.colorArray.emplaceBack(0, 0, halfWidth, 1.3);
        // extruded side
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -1.2, halfWidth, 0.8);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -1.2, halfWidth, 0.8);
        // Finally, the triangle indices
        mesh.indexArray.emplaceBack(6 + currentVertex, 4 + currentVertex, 8 + currentVertex);
        mesh.indexArray.emplaceBack(7 + currentVertex, 9 + currentVertex, 5 + currentVertex);
        mesh.indexArray.emplaceBack(0 + currentVertex, 1 + currentVertex, 2 + currentVertex);
        mesh.indexArray.emplaceBack(1 + currentVertex, 3 + currentVertex, 2 + currentVertex);
        currentVertex += 10;
    }
    //mesh.featureArray = new FeatureVertexArray();
    //mesh.featureArray.reserve(10 * lights.length);
    //for (let i = 0; i < 10 * lights.length; i++) {
    //    mesh.featureArray.emplaceBack(0xffff, 0xffff, 0xffff, 0xffff, 0, 0, 0);
    //}
    const material = {};
    material.defined = true;
    material.emissiveFactor = [
        0,
        0,
        0
    ];
    const pbrMetallicRoughness = {};
    pbrMetallicRoughness.baseColorFactor = Color$1.white;
    // $FlowIgnore[prop-missing] don't need all the properties
    material.pbrMetallicRoughness = pbrMetallicRoughness;
    mesh.material = material;
    mesh.aabb = new Aabb([
        Infinity,
        Infinity,
        Infinity
    ], [
        -Infinity,
        -Infinity,
        -Infinity
    ]);
    return mesh;
}
function decodeLights(base64) {
    if (!base64.length)
        return [];
    const decoded = base64DecToArr(base64);
    const lights = [];
    const lightCount = decoded.length / 24;
    // 24 bytes (4 uint16 & 4 floats) per light
    // Each door light is defined by two endpoiunts in tile coordinates, left and bottom right
    // (where normal is implied from those two), depth and height.
    // https://github.com/mapbox/mapbox-3dtile-tools/pull/100
    const lightData = new Uint16Array(decoded.buffer);
    const lightDataFloat = new Float32Array(decoded.buffer);
    const stride = 6;
    for (let i = 0; i < lightCount; i++) {
        const height = lightData[i * 2 * stride] / 30;
        const elevation = lightData[i * 2 * stride + 1] / 30;
        const depth = lightData[i * 2 * stride + 10] / 100;
        const x0 = lightDataFloat[i * stride + 1];
        const y0 = lightDataFloat[i * stride + 2];
        const x1 = lightDataFloat[i * stride + 3];
        const y1 = lightDataFloat[i * stride + 4];
        const dx = x1 - x0;
        const dy = y1 - y0;
        const width = Math.hypot(dx, dy);
        const normal = [
            dy / width,
            -dx / width,
            0
        ];
        const pos = [
            x0 + dx * 0.5,
            y0 + dy * 0.5,
            elevation
        ];
        const points = [
            x0,
            y0,
            x1,
            y1
        ];
        lights.push({
            pos,
            normal,
            width,
            height,
            depth,
            points
        });
    }
    return lights;
}

//      
/**
 * A source containing single models.
 */
// Important Note: ModelSource is legacy and should not be offered in the API, as the only valid official sources to add models
// are batched-models and via GeoJson/vector sources. We keep this one (for now) just for ease development and get the render-tests
// passing.
class ModelSource extends Evented {
    /**
     * @private
     */
    // eslint-disable-next-line no-unused-vars
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.id = id;
        this.type = 'model';
        this.models = [];
        this._loaded = false;
        this._options = options;
    }
    load() {
        const modelPromises = [];
        /* $FlowIgnore[prop-missing] we don't need the full spec of model_source as it's only used for testing */
        for (const modelId in this._options.models) {
            const modelSpec = this._options.models[modelId];
            const modelPromise = loadGLTF(this.map._requestManager.transformRequest(modelSpec.uri, ResourceType.Model).url).then(gltf => {
                if (!gltf)
                    return;
                const nodes = convertModel(gltf);
                const model = new Model(modelId, modelSpec.position, modelSpec.orientation, nodes);
                model.computeBoundsAndApplyParent();
                this.models.push(model);
            }).catch(err => {
                this.fire(new ErrorEvent(new Error(`Could not load model ${ modelId } from ${ modelSpec.uri }: ${ err.message }`)));
            });
            modelPromises.push(modelPromise);
        }
        return Promise.allSettled(modelPromises).then(() => {
            this._loaded = true;
            this.fire(new Event('data', {
                dataType: 'source',
                sourceDataType: 'metadata'
            }));
        }).catch(err => {
            this.fire(new ErrorEvent(new Error(`Could not load models: ${ err.message }`)));
        });
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.load();
    }
    hasTransition() {
        return false;
    }
    loaded() {
        return this._loaded;
    }
    getModels() {
        return this.models;
    }
    // eslint-disable-next-line no-unused-vars
    loadTile(tile, callback) {
    }
    serialize() {
        return { type: 'model' };
    }
}

//      
class Tiled3DModelSource extends Evented {
    /**
     * @private
     */
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.type = 'batched-model';
        this.id = id;
        this.tileSize = 512;
        this._options = options;
        this.tiles = this._options.tiles;
        this.maxzoom = options.maxzoom || 19;
        this.minzoom = options.minzoom || 0;
        this.roundZoom = true;
        this.usedInConflation = true;
        this.dispatcher = dispatcher;
        this.reparseOverscaled = false;
        this.scheme = 'xyz';
        this._loaded = false;
        this.setEventedParent(eventedParent);
    }
    // $FlowFixMe[method-unbinding]
    onAdd(map) {
        this.map = map;
        this.load();
    }
    load(callback) {
        this._loaded = false;
        this.fire(new Event('dataloading', { dataType: 'source' }));
        const language = Array.isArray(this.map._language) ? this.map._language.join() : this.map._language;
        const worldview = this.map._worldview;
        this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, language, worldview, (err, tileJSON) => {
            this._tileJSONRequest = null;
            this._loaded = true;
            if (err) {
                if (language)
                    console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${ language }`);
                if (worldview && worldview.length !== 2)
                    console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${ worldview }`);
                this.fire(new ErrorEvent(err));
            } else if (tileJSON) {
                extend$1(this, tileJSON);
                if (tileJSON.bounds)
                    this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
                postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);
                // `content` is included here to prevent a race condition where `Style#_updateSources` is called
                // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives
                // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088
                this.fire(new Event('data', {
                    dataType: 'source',
                    sourceDataType: 'metadata'
                }));
                this.fire(new Event('data', {
                    dataType: 'source',
                    sourceDataType: 'content'
                }));
            }
            if (callback)
                callback(err);
        });
    }
    hasTransition() {
        return false;
    }
    // $FlowFixMe[method-unbinding]
    hasTile(tileID) {
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    loaded() {
        return this._loaded;
    }
    loadTile(tile, callback) {
        const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme));
        const request = this.map._requestManager.transformRequest(url, ResourceType.Tile);
        const params = {
            request,
            data: undefined,
            uid: tile.uid,
            tileID: tile.tileID,
            tileZoom: tile.tileZoom,
            zoom: tile.tileID.overscaledZ,
            tileSize: this.tileSize * tile.tileID.overscaleFactor(),
            type: this.type,
            source: this.id,
            scope: this.scope,
            showCollisionBoxes: this.map.showCollisionBoxes,
            isSymbolTile: tile.isSymbolTile,
            brightness: this.map.style ? this.map.style.getBrightness() || 0 : 0
        };
        if (!tile.actor || tile.state === 'expired') {
            tile.actor = this.dispatcher.getActor();
            tile.request = tile.actor.send('loadTile', params, done.bind(this), undefined, true);
        } else if (tile.state === 'loading') {
            // schedule tile reloading after it has been loaded
            tile.reloadCallback = callback;
        } else {
            // If the tile has already been parsed we may just need to reevaluate
            if (tile.buckets) {
                const buckets = Object.values(tile.buckets);
                for (const bucket of buckets) {
                    // $FlowIgnore[incompatible-use] All buckets are Tiled3DModelBuckets
                    bucket.dirty = true;
                }
                tile.state = 'loaded';
                return;
            }
            tile.request = tile.actor.send('reloadTile', params, done.bind(this));
        }
        // $FlowFixMe[missing-this-annot]
        function done(err, data) {
            if (tile.aborted)
                return callback(null);
            // $FlowFixMe[prop-missing] - generic Error type doesn't have status
            if (err && err.status !== 404) {
                return callback(err);
            }
            if (data) {
                if (data.resourceTiming)
                    tile.resourceTiming = data.resourceTiming;
                if (this.map._refreshExpiredTiles)
                    tile.setExpiryData(data);
                tile.buckets = {
                    ...tile.buckets,
                    ...data.buckets
                };
            }
            tile.state = 'loaded';
            callback(null);
        }
    }
    serialize() {
        return extend$1({}, this._options);
    }
}

//      
const sourceTypes = {
    vector: VectorTileSource,
    raster: RasterTileSource,
    'raster-dem': RasterDEMTileSource,
    geojson: GeoJSONSource,
    video: VideoSource,
    image: ImageSource,
    model: ModelSource,
    'batched-model': Tiled3DModelSource,
    canvas: CanvasSource,
    custom: CustomSource
};
/*
 * Creates a tiled data source instance given an options object.
 *
 * @param id
 * @param {Object} source A source definition object compliant with
 * [`mapbox-gl-style-spec`](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or, for a third-party source type,
  * with that type's requirements.
 * @param {Dispatcher} dispatcher
 * @returns {Source}
 */
const create = function (id, specification, dispatcher, eventedParent) {
    // $FlowFixMe[prop-missing]
    const source = new sourceTypes[specification.type](id, specification, dispatcher, eventedParent);
    if (source.id !== id) {
        throw new Error(`Expected Source id to be ${ id } instead of ${ source.id }`);
    }
    bindAll([
        'load',
        'abort',
        'unload',
        'serialize',
        'prepare'
    ], source);
    return source;
};
const getType = function (name) {
    return sourceTypes[name];
};
const setType = function (name, type) {
    sourceTypes[name] = type;
};

/*
 * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates.
 */
function getPixelPosMatrix(transform, tileID) {
    const t = mat4_1.identity([]);
    mat4_1.scale(t, t, [
        transform.width * 0.5,
        -transform.height * 0.5,
        1
    ]);
    mat4_1.translate(t, t, [
        1,
        -1,
        0
    ]);
    mat4_1.multiply(t, t, transform.calculateProjMatrix(tileID.toUnwrapped()));
    return Float32Array.from(t);
}
function queryRenderedFeatures(sourceCache, styleLayers, serializedLayers, queryGeometry, params, transform, use3DQuery, visualizeQueryGeometry = false) {
    const tileResults = sourceCache.tilesIn(queryGeometry, use3DQuery, visualizeQueryGeometry);
    tileResults.sort(sortTilesIn);
    const renderedFeatureLayers = [];
    for (const tileResult of tileResults) {
        renderedFeatureLayers.push({
            wrappedTileID: tileResult.tile.tileID.wrapped().key,
            queryResults: tileResult.tile.queryRenderedFeatures(styleLayers, serializedLayers, sourceCache._state, tileResult, params, transform, getPixelPosMatrix(sourceCache.transform, tileResult.tile.tileID), visualizeQueryGeometry)
        });
    }
    const result = mergeRenderedFeatureLayers(renderedFeatureLayers);
    // Merge state from SourceCache into the results
    for (const layerID in result) {
        result[layerID].forEach(featureWrapper => {
            const feature = featureWrapper.feature;
            const layer = feature.layer;
            if (!layer || layer.type === 'background' || layer.type === 'sky' || layer.type === 'slot')
                return;
            feature.source = layer.source;
            if (layer['source-layer']) {
                feature.sourceLayer = layer['source-layer'];
            }
            feature.state = feature.id !== undefined ? sourceCache.getFeatureState(layer['source-layer'], feature.id) : {};
        });
    }
    return result;
}
function queryRenderedSymbols(styleLayers, serializedLayers, getLayerSourceCache, queryGeometry, params, collisionIndex, retainedQueryData) {
    const result = {};
    const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);
    const bucketQueryData = [];
    for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) {
        bucketQueryData.push(retainedQueryData[bucketInstanceId]);
    }
    bucketQueryData.sort(sortTilesIn);
    for (const queryData of bucketQueryData) {
        const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], serializedLayers, queryData.bucketIndex, queryData.sourceLayerIndex, params.filter, params.layers, params.availableImages, styleLayers);
        for (const layerID in bucketSymbols) {
            const resultFeatures = result[layerID] = result[layerID] || [];
            const layerSymbols = bucketSymbols[layerID];
            layerSymbols.sort((a, b) => {
                // Match topDownFeatureComparator from FeatureIndex, but using
                // most recent sorting of features from bucket.sortFeatures
                const featureSortOrder = queryData.featureSortOrder;
                if (featureSortOrder) {
                    // queryRenderedSymbols documentation says we'll return features in
                    // "top-to-bottom" rendering order (aka last-to-first).
                    // Actually there can be multiple symbol instances per feature, so
                    // we sort each feature based on the first matching symbol instance.
                    const sortedA = featureSortOrder.indexOf(a.featureIndex);
                    const sortedB = featureSortOrder.indexOf(b.featureIndex);
                    return sortedB - sortedA;
                } else {
                    // Bucket hasn't been re-sorted based on angle, so use the
                    // reverse of the order the features appeared in the data.
                    return b.featureIndex - a.featureIndex;
                }
            });
            for (const symbolFeature of layerSymbols) {
                resultFeatures.push(symbolFeature);
            }
        }
    }
    // Merge state from SourceCache into the results
    for (const layerName in result) {
        result[layerName].forEach(featureWrapper => {
            const feature = featureWrapper.feature;
            const layer = styleLayers[layerName];
            const sourceCache = getLayerSourceCache(layer);
            if (!sourceCache)
                return;
            const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);
            feature.source = feature.layer.source;
            if (feature.layer['source-layer']) {
                feature.sourceLayer = feature.layer['source-layer'];
            }
            feature.state = state;
        });
    }
    return result;
}
function querySourceFeatures(sourceCache, params) {
    const tiles = sourceCache.getRenderableIds().map(id => {
        return sourceCache.getTileByID(id);
    });
    const result = [];
    const dataTiles = {};
    for (let i = 0; i < tiles.length; i++) {
        const tile = tiles[i];
        const dataID = tile.tileID.canonical.key;
        if (!dataTiles[dataID]) {
            dataTiles[dataID] = true;
            tile.querySourceFeatures(result, params);
        }
    }
    return result;
}
function sortTilesIn(a, b) {
    const idA = a.tileID;
    const idB = b.tileID;
    return idA.overscaledZ - idB.overscaledZ || idA.canonical.y - idB.canonical.y || idA.wrap - idB.wrap || idA.canonical.x - idB.canonical.x;
}
function mergeRenderedFeatureLayers(tiles) {
    // Merge results from all tiles, but if two tiles share the same
    // wrapped ID, don't duplicate features between the two tiles
    const result = {};
    const wrappedIDLayerMap = {};
    for (const tile of tiles) {
        const queryResults = tile.queryResults;
        const wrappedID = tile.wrappedTileID;
        const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {};
        for (const layerID in queryResults) {
            const tileFeatures = queryResults[layerID];
            const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {};
            const resultFeatures = result[layerID] = result[layerID] || [];
            for (const tileFeature of tileFeatures) {
                if (!wrappedIDFeatures[tileFeature.featureIndex]) {
                    wrappedIDFeatures[tileFeature.featureIndex] = true;
                    resultFeatures.push(tileFeature);
                }
            }
        }
    }
    return result;
}

//      
class BuildingIndex {
    constructor(style) {
        this.style = style;
    }
    processLayersChanged() {
        this.layers = [];
        for (const layerId in this.style._mergedLayers) {
            const layer = this.style._mergedLayers[layerId];
            if (layer.type === 'fill-extrusion') {
                this.layers.push(layer);
            } else if (layer.type === 'model') {
                const source = this.style.getLayerSource(layer);
                if (source && source.type === 'batched-model') {
                    this.layers.push(layer);
                }
            }
        }
    }
    updateZOffset(symbolBucket, tileID) {
        // prepare lookup from bucket to overlapping buckets of all building layers.
        this.currentBuildingBuckets = [];
        for (let i = 0; i < this.layers.length; ++i) {
            const layer = this.layers[i];
            const sourceCache = this.style.getLayerSourceCache(layer);
            let verticalScale = 1;
            if (layer.type === 'fill-extrusion') {
                // See https://mapbox.atlassian.net/browse/MAPS3D-1159 for more details on why we should take opacity into account.
                const opacity = layer.paint.get('fill-extrusion-opacity');
                verticalScale = opacity > 0 ? layer.paint.get('fill-extrusion-vertical-scale') : 0;
            }
            let tile = sourceCache ? sourceCache.getTile(tileID) : null;
            if (!tile && sourceCache && tileID.canonical.z > sourceCache.getSource().minzoom) {
                let id = tileID.scaledTo(Math.min(sourceCache.getSource().maxzoom, tileID.overscaledZ - 1));
                while (id.overscaledZ >= sourceCache.getSource().minzoom) {
                    tile = sourceCache.getTile(id);
                    if (tile || id.overscaledZ === 0)
                        break;
                    id = id.scaledTo(id.overscaledZ - 1);
                }
            }
            this.currentBuildingBuckets.push({
                bucket: tile ? tile.getBucket(layer) : null,
                tileID: tile ? tile.tileID : tileID,
                verticalScale
            });
        }
        symbolBucket.hasAnyZOffset = false;
        let dataChanged = false;
        for (let s = 0; s < symbolBucket.symbolInstances.length; s++) {
            const symbolInstance = symbolBucket.symbolInstances.get(s);
            const currentZOffset = symbolInstance.zOffset;
            const newZOffset = this._getHeightAtTileOffset(tileID, symbolInstance.tileAnchorX, symbolInstance.tileAnchorY);
            symbolInstance.zOffset = newZOffset !== -1 ? newZOffset : currentZOffset;
            if (!dataChanged && currentZOffset !== symbolInstance.zOffset) {
                dataChanged = true;
            }
            if (!symbolBucket.hasAnyZOffset && symbolInstance.zOffset !== 0) {
                symbolBucket.hasAnyZOffset = true;
            }
        }
        if (dataChanged) {
            symbolBucket.zOffsetBuffersNeedUpload = true;
            symbolBucket.zOffsetSortDirty = true;
        }
    }
    _mapCoordToOverlappingTile(tid, x, y, targetTileID) {
        let tileX = x;
        let tileY = y;
        const tileID = targetTileID;
        if (tid.canonical.z !== tileID.canonical.z) {
            const id = tileID.canonical;
            const zDiff = 1 / (1 << tid.canonical.z - id.z);
            tileX = (x + tid.canonical.x * EXTENT) * zDiff - id.x * EXTENT | 0;
            tileY = (y + tid.canonical.y * EXTENT) * zDiff - id.y * EXTENT | 0;
        }
        return {
            tileX,
            tileY
        };
    }
    _getHeightAtTileOffset(tid, x, y) {
        let availableHeight;
        // use FE data when landmark height is not available. Instead of asuming order, process
        // fill extrusions before landmarks
        for (let i = 0; i < this.layers.length; ++i) {
            const layer = this.layers[i];
            if (layer.type !== 'fill-extrusion')
                continue;
            const {bucket, tileID, verticalScale} = this.currentBuildingBuckets[i];
            if (!bucket)
                continue;
            const {tileX, tileY} = this._mapCoordToOverlappingTile(tid, x, y, tileID);
            const b = bucket;
            const heightData = b.getHeightAtTileCoord(tileX, tileY);
            if (!heightData || heightData.height === undefined)
                continue;
            if (heightData.hidden) {
                availableHeight = heightData.height;
                continue;
            }
            return heightData.height * verticalScale;
        }
        for (let i = 0; i < this.layers.length; ++i) {
            const layer = this.layers[i];
            if (layer.type !== 'model')
                continue;
            const {bucket, tileID} = this.currentBuildingBuckets[i];
            if (!bucket)
                continue;
            const {tileX, tileY} = this._mapCoordToOverlappingTile(tid, x, y, tileID);
            const b = bucket;
            const heightData = b.getHeightAtTileCoord(tileX, tileY);
            if (!heightData || heightData.hidden)
                continue;
            if (heightData.height === undefined && availableHeight !== undefined)
                return Math.min(heightData.maxHeight, availableHeight) * heightData.verticalScale;
            return (heightData.height || 0) * heightData.verticalScale;
        }
        // We couldn't find a bucket
        return -1;
    }
}

//      
var refProperties = [
    'type',
    'source',
    'source-layer',
    'minzoom',
    'maxzoom',
    'filter',
    'layout'
];

//      
function deref(layer, parent) {
    const result = {};
    for (const k in layer) {
        if (k !== 'ref') {
            result[k] = layer[k];
        }
    }
    refProperties.forEach(k => {
        if (k in parent) {
            result[k] = parent[k];
        }
    });
    return result;
}
/**
 * Given an array of layers, some of which may contain `ref` properties
 * whose value is the `id` of another property, return a new array where
 * such layers have been augmented with the 'type', 'source', etc. properties
 * from the parent layer, and the `ref` property has been removed.
 *
 * The input is not modified. The output may contain references to portions
 * of the input.
 *
 * @private
 * @param {Array<Layer>} layers
 * @returns {Array<Layer>}
 */
function derefLayers(layers) {
    layers = layers.slice();
    const map = Object.create(null);
    for (let i = 0; i < layers.length; i++) {
        map[layers[i].id] = layers[i];
    }
    for (let i = 0; i < layers.length; i++) {
        if ('ref' in layers[i]) {
            layers[i] = deref(layers[i], map[layers[i].ref]);
        }
    }
    return layers;
}

//      
function emptyStyle() {
    return {
        version: 8,
        layers: [],
        sources: {}
    };
}

//      
const operations = {
    /*
     * { command: 'setStyle', args: [stylesheet] }
     */
    setStyle: 'setStyle',
    /*
     * { command: 'addLayer', args: [layer, 'beforeLayerId'] }
     */
    addLayer: 'addLayer',
    /*
     * { command: 'removeLayer', args: ['layerId'] }
     */
    removeLayer: 'removeLayer',
    /*
     * { command: 'setPaintProperty', args: ['layerId', 'prop', value] }
     */
    setPaintProperty: 'setPaintProperty',
    /*
     * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }
     */
    setLayoutProperty: 'setLayoutProperty',
    /*
     * { command: 'setSlot', args: ['layerId', slot] }
     */
    setSlot: 'setSlot',
    /*
     * { command: 'setFilter', args: ['layerId', filter] }
     */
    setFilter: 'setFilter',
    /*
     * { command: 'addSource', args: ['sourceId', source] }
     */
    addSource: 'addSource',
    /*
     * { command: 'removeSource', args: ['sourceId'] }
     */
    removeSource: 'removeSource',
    /*
     * { command: 'setGeoJSONSourceData', args: ['sourceId', data] }
     */
    setGeoJSONSourceData: 'setGeoJSONSourceData',
    /*
     * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }
     */
    setLayerZoomRange: 'setLayerZoomRange',
    /*
     * { command: 'setLayerProperty', args: ['layerId', 'prop', value] }
     */
    setLayerProperty: 'setLayerProperty',
    /*
     * { command: 'setCenter', args: [[lon, lat]] }
     */
    setCenter: 'setCenter',
    /*
     * { command: 'setZoom', args: [zoom] }
     */
    setZoom: 'setZoom',
    /*
     * { command: 'setBearing', args: [bearing] }
     */
    setBearing: 'setBearing',
    /*
     * { command: 'setPitch', args: [pitch] }
     */
    setPitch: 'setPitch',
    /*
     * { command: 'setSprite', args: ['spriteUrl'] }
     */
    setSprite: 'setSprite',
    /*
     * { command: 'setGlyphs', args: ['glyphsUrl'] }
     */
    setGlyphs: 'setGlyphs',
    /*
     * { command: 'setTransition', args: [transition] }
     */
    setTransition: 'setTransition',
    /*
     * { command: 'setLighting', args: [lightProperties] }
     */
    setLight: 'setLight',
    /*
     * { command: 'setTerrain', args: [terrainProperties] }
     */
    setTerrain: 'setTerrain',
    /*
     *  { command: 'setFog', args: [fogProperties] }
     */
    setFog: 'setFog',
    /*
     *  { command: 'setCamera', args: [cameraProperties] }
     */
    setCamera: 'setCamera',
    /*
     *  { command: 'setLights', args: [{light-3d},...] }
     */
    setLights: 'setLights',
    /*
     *  { command: 'setProjection', args: [projectionProperties] }
     */
    setProjection: 'setProjection',
    /*
     *  { command: 'addImport', args: [import] }
     */
    addImport: 'addImport',
    /*
     *  { command: 'removeImport', args: [importId] }
     */
    removeImport: 'removeImport',
    /*
     *  { command: 'setImportUrl', args: [importId, styleUrl] }
     */
    setImportUrl: 'setImportUrl',
    /*
     *  { command: 'setImportData', args: [importId, stylesheet] }
     */
    setImportData: 'setImportData',
    /*
     *  { command: 'setImportConfig', args: [importId, config] }
     */
    setImportConfig: 'setImportConfig'
};
function addSource(sourceId, after, commands) {
    commands.push({
        command: operations.addSource,
        args: [
            sourceId,
            after[sourceId]
        ]
    });
}
function removeSource(sourceId, commands, sourcesRemoved) {
    commands.push({
        command: operations.removeSource,
        args: [sourceId]
    });
    sourcesRemoved[sourceId] = true;
}
function updateSource(sourceId, after, commands, sourcesRemoved) {
    removeSource(sourceId, commands, sourcesRemoved);
    addSource(sourceId, after, commands);
}
function canUpdateGeoJSON(before, after, sourceId) {
    let prop;
    for (prop in before[sourceId]) {
        if (!before[sourceId].hasOwnProperty(prop))
            continue;
        if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) {
            return false;
        }
    }
    for (prop in after[sourceId]) {
        if (!after[sourceId].hasOwnProperty(prop))
            continue;
        if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) {
            return false;
        }
    }
    return true;
}
function diffSources(before, after, commands, sourcesRemoved) {
    before = before || {};
    after = after || {};
    let sourceId;
    // look for sources to remove
    for (sourceId in before) {
        if (!before.hasOwnProperty(sourceId))
            continue;
        if (!after.hasOwnProperty(sourceId)) {
            removeSource(sourceId, commands, sourcesRemoved);
        }
    }
    // look for sources to add/update
    for (sourceId in after) {
        if (!after.hasOwnProperty(sourceId))
            continue;
        const source = after[sourceId];
        if (!before.hasOwnProperty(sourceId)) {
            addSource(sourceId, after, commands);
        } else if (!deepEqual(before[sourceId], source)) {
            if (before[sourceId].type === 'geojson' && source.type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {
                commands.push({
                    command: operations.setGeoJSONSourceData,
                    args: [
                        sourceId,
                        source.data
                    ]
                });
            } else {
                // no update command, must remove then add
                updateSource(sourceId, after, commands, sourcesRemoved);
            }
        }
    }
}
function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {
    before = before || {};
    after = after || {};
    let prop;
    for (prop in before) {
        if (!before.hasOwnProperty(prop))
            continue;
        if (!deepEqual(before[prop], after[prop])) {
            commands.push({
                command,
                args: [
                    layerId,
                    prop,
                    after[prop],
                    klass
                ]
            });
        }
    }
    for (prop in after) {
        if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop))
            continue;
        if (!deepEqual(before[prop], after[prop])) {
            commands.push({
                command,
                args: [
                    layerId,
                    prop,
                    after[prop],
                    klass
                ]
            });
        }
    }
}
function pluckId(item) {
    return item.id;
}
function indexById(group, item) {
    group[item.id] = item;
    return group;
}
function diffLayers(before, after, commands) {
    before = before || [];
    after = after || [];
    // order of layers by id
    const beforeOrder = before.map(pluckId);
    const afterOrder = after.map(pluckId);
    // index of layer by id
    const beforeIndex = before.reduce(indexById, {});
    const afterIndex = after.reduce(indexById, {});
    // track order of layers as if they have been mutated
    const tracker = beforeOrder.slice();
    // layers that have been added do not need to be diffed
    const clean = Object.create(null);
    let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;
    // remove layers
    for (i = 0, d = 0; i < beforeOrder.length; i++) {
        layerId = beforeOrder[i];
        if (!afterIndex.hasOwnProperty(layerId)) {
            commands.push({
                command: operations.removeLayer,
                args: [layerId]
            });
            tracker.splice(tracker.indexOf(layerId, d), 1);
        } else {
            // limit where in tracker we need to look for a match
            d++;
        }
    }
    // add/reorder layers
    for (i = 0, d = 0; i < afterOrder.length; i++) {
        // work backwards as insert is before an existing layer
        layerId = afterOrder[afterOrder.length - 1 - i];
        if (tracker[tracker.length - 1 - i] === layerId)
            continue;
        if (beforeIndex.hasOwnProperty(layerId)) {
            // remove the layer before we insert at the correct position
            commands.push({
                command: operations.removeLayer,
                args: [layerId]
            });
            tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);
        } else {
            // limit where in tracker we need to look for a match
            d++;
        }
        // add layer at correct position
        insertBeforeLayerId = tracker[tracker.length - i];
        commands.push({
            command: operations.addLayer,
            args: [
                afterIndex[layerId],
                insertBeforeLayerId
            ]
        });
        tracker.splice(tracker.length - i, 0, layerId);
        clean[layerId] = true;
    }
    // update layers
    for (i = 0; i < afterOrder.length; i++) {
        layerId = afterOrder[i];
        beforeLayer = beforeIndex[layerId];
        afterLayer = afterIndex[layerId];
        // no need to update if previously added (new or moved)
        if (clean[layerId] || deepEqual(beforeLayer, afterLayer))
            continue;
        // If source, source-layer, or type have changes, then remove the layer
        // and add it back 'from scratch'.
        // $FlowFixMe[prop-missing] - there is no `source-layer` in background and sky layers
        if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) {
            commands.push({
                command: operations.removeLayer,
                args: [layerId]
            });
            // we add the layer back at the same position it was already in, so
            // there's no need to update the `tracker`
            insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];
            commands.push({
                command: operations.addLayer,
                args: [
                    afterLayer,
                    insertBeforeLayerId
                ]
            });
            continue;
        }
        // layout, paint, filter, minzoom, maxzoom
        diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);
        diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);
        if (!deepEqual(beforeLayer.slot, afterLayer.slot)) {
            commands.push({
                command: operations.setSlot,
                args: [
                    layerId,
                    afterLayer.slot
                ]
            });
        }
        if (!deepEqual(beforeLayer.filter, afterLayer.filter)) {
            commands.push({
                command: operations.setFilter,
                args: [
                    layerId,
                    afterLayer.filter
                ]
            });
        }
        if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {
            commands.push({
                command: operations.setLayerZoomRange,
                args: [
                    layerId,
                    afterLayer.minzoom,
                    afterLayer.maxzoom
                ]
            });
        }
        // handle all other layer props, including paint.*
        for (prop in beforeLayer) {
            if (!beforeLayer.hasOwnProperty(prop))
                continue;
            if (prop === 'layout' || prop === 'paint' || prop === 'filter' || prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom' || prop === 'slot')
                continue;
            if (prop.indexOf('paint.') === 0) {
                diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
            } else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) {
                commands.push({
                    command: operations.setLayerProperty,
                    args: [
                        layerId,
                        prop,
                        afterLayer[prop]
                    ]
                });
            }
        }
        for (prop in afterLayer) {
            if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop))
                continue;
            if (prop === 'layout' || prop === 'paint' || prop === 'filter' || prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom' || prop === 'slot')
                continue;
            if (prop.indexOf('paint.') === 0) {
                diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
            } else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) {
                commands.push({
                    command: operations.setLayerProperty,
                    args: [
                        layerId,
                        prop,
                        afterLayer[prop]
                    ]
                });
            }
        }
    }
}
function diffImports(before = [], after = [], commands) {
    before = before || [];
    after = after || [];
    // order imports by id
    const beforeOrder = before.map(pluckId);
    const afterOrder = after.map(pluckId);
    // index imports by id
    const beforeIndex = before.reduce(indexById, {});
    const afterIndex = after.reduce(indexById, {});
    // track order of imports as if they have been mutated
    const tracker = beforeOrder.slice();
    let i, d, importId, insertBefore;
    // remove imports
    for (i = 0, d = 0; i < beforeOrder.length; i++) {
        importId = beforeOrder[i];
        if (!afterIndex.hasOwnProperty(importId)) {
            commands.push({
                command: operations.removeImport,
                args: [importId]
            });
            tracker.splice(tracker.indexOf(importId, d), 1);
        } else {
            // limit where in tracker we need to look for a match
            d++;
        }
    }
    // add/reorder imports
    for (i = 0, d = 0; i < afterOrder.length; i++) {
        // work backwards as insert is before an existing import
        importId = afterOrder[afterOrder.length - 1 - i];
        if (tracker[tracker.length - 1 - i] === importId)
            continue;
        if (beforeIndex.hasOwnProperty(importId)) {
            // remove the import before we insert at the correct position
            commands.push({
                command: operations.removeImport,
                args: [importId]
            });
            tracker.splice(tracker.lastIndexOf(importId, tracker.length - d), 1);
        } else {
            // limit where in tracker we need to look for a match
            d++;
        }
        // add import at correct position
        insertBefore = tracker[tracker.length - i];
        commands.push({
            command: operations.addImport,
            args: [
                afterIndex[importId],
                insertBefore
            ]
        });
        tracker.splice(tracker.length - i, 0, importId);
    }
    // update imports
    for (const afterImport of after) {
        const beforeImport = beforeIndex[afterImport.id];
        if (!beforeImport || deepEqual(beforeImport, afterImport))
            continue;
        if (!deepEqual(beforeImport.config, afterImport.config)) {
            commands.push({
                command: operations.setImportConfig,
                args: [
                    afterImport.id,
                    afterImport.config
                ]
            });
        }
        if (!deepEqual(beforeImport.url, afterImport.url)) {
            commands.push({
                command: operations.setImportUrl,
                args: [
                    afterImport.id,
                    afterImport.url
                ]
            });
        }
        const beforeData = beforeImport && beforeImport.data;
        const afterData = afterImport.data;
        if (!deepEqual(beforeData, afterData)) {
            commands.push({
                command: operations.setImportData,
                args: [
                    afterImport.id,
                    afterData
                ]
            });
        }
    }
}
/**
 * Diff two stylesheet
 *
 * Creates semanticly aware diffs that can easily be applied at runtime.
 * Operations produced by the diff closely resemble the mapbox-gl-js API. Any
 * error creating the diff will fall back to the 'setStyle' operation.
 *
 * Example diff:
 * [
 *     { command: 'setConstant', args: ['@water', '#0000FF'] },
 *     { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }
 * ]
 *
 * @private
 * @param {*} [before] stylesheet to compare from
 * @param {*} after stylesheet to compare to
 * @returns Array list of changes
 */
function diffStyles(before, after) {
    if (!before)
        return [{
                command: operations.setStyle,
                args: [after]
            }];
    let commands = [];
    try {
        // Handle changes to top-level properties
        if (!deepEqual(before.version, after.version)) {
            return [{
                    command: operations.setStyle,
                    args: [after]
                }];
        }
        if (!deepEqual(before.center, after.center)) {
            commands.push({
                command: operations.setCenter,
                args: [after.center]
            });
        }
        if (!deepEqual(before.zoom, after.zoom)) {
            commands.push({
                command: operations.setZoom,
                args: [after.zoom]
            });
        }
        if (!deepEqual(before.bearing, after.bearing)) {
            commands.push({
                command: operations.setBearing,
                args: [after.bearing]
            });
        }
        if (!deepEqual(before.pitch, after.pitch)) {
            commands.push({
                command: operations.setPitch,
                args: [after.pitch]
            });
        }
        if (!deepEqual(before.sprite, after.sprite)) {
            commands.push({
                command: operations.setSprite,
                args: [after.sprite]
            });
        }
        if (!deepEqual(before.glyphs, after.glyphs)) {
            commands.push({
                command: operations.setGlyphs,
                args: [after.glyphs]
            });
        }
        if (!deepEqual(before.transition, after.transition)) {
            commands.push({
                command: operations.setTransition,
                args: [after.transition]
            });
        }
        if (!deepEqual(before.light, after.light)) {
            commands.push({
                command: operations.setLight,
                args: [after.light]
            });
        }
        if (!deepEqual(before.fog, after.fog)) {
            commands.push({
                command: operations.setFog,
                args: [after.fog]
            });
        }
        if (!deepEqual(before.projection, after.projection)) {
            commands.push({
                command: operations.setProjection,
                args: [after.projection]
            });
        }
        if (!deepEqual(before.lights, after.lights)) {
            commands.push({
                command: operations.setLights,
                args: [after.lights]
            });
        }
        if (!deepEqual(before.camera, after.camera)) {
            commands.push({
                command: operations.setCamera,
                args: [after.camera]
            });
        }
        // Handle changes to `sources`
        // If a source is to be removed, we also--before the removeSource
        // command--need to remove all the style layers that depend on it.
        const sourcesRemoved = {};
        // First collect the {add,remove}Source commands
        const removeOrAddSourceCommands = [];
        diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);
        // Push a removeLayer command for each style layer that depends on a
        // source that's being removed.
        // Also, exclude any such layers them from the input to `diffLayers`
        // below, so that diffLayers produces the appropriate `addLayers`
        // command
        const beforeLayers = [];
        if (before.layers) {
            before.layers.forEach(layer => {
                if (layer.source && sourcesRemoved[layer.source]) {
                    commands.push({
                        command: operations.removeLayer,
                        args: [layer.id]
                    });
                } else {
                    beforeLayers.push(layer);
                }
            });
        }
        // Remove the terrain if the source for that terrain is being removed
        let beforeTerrain = before.terrain;
        if (beforeTerrain) {
            if (sourcesRemoved[beforeTerrain.source]) {
                commands.push({
                    command: operations.setTerrain,
                    args: [undefined]
                });
                beforeTerrain = undefined;
            }
        }
        commands = commands.concat(removeOrAddSourceCommands);
        // Even though terrain is a top-level property
        // Its like a layer in the sense that it depends on a source being present.
        if (!deepEqual(beforeTerrain, after.terrain)) {
            commands.push({
                command: operations.setTerrain,
                args: [after.terrain]
            });
        }
        // Handle changes to `layers`
        diffLayers(beforeLayers, after.layers, commands);
        // Handle changes to `imports`
        diffImports(before.imports, after.imports, commands);
    } catch (e) {
        // fall back to setStyle
        console.warn('Unable to compute style diff:', e);
        commands = [{
                command: operations.setStyle,
                args: [after]
            }];
    }
    return commands;
}

//      
class PathInterpolator {
    constructor(points_, padding_) {
        this.reset(points_, padding_);
    }
    reset(points_, padding_) {
        this.points = points_ || [];
        // Compute cumulative distance from first point to every other point in the segment.
        // Last entry in the array is total length of the path
        this._distances = [0];
        for (let i = 1; i < this.points.length; i++) {
            this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]);
        }
        this.length = this._distances[this._distances.length - 1];
        this.padding = Math.min(padding_ || 0, this.length * 0.5);
        this.paddedLength = this.length - this.padding * 2;
    }
    lerp(t) {
        if (this.points.length === 1) {
            return this.points[0];
        }
        t = clamp(t, 0, 1);
        // Find the correct segment [p0, p1] where p0 <= x < p1
        let currentIndex = 1;
        let distOfCurrentIdx = this._distances[currentIndex];
        const distToTarget = t * this.paddedLength + this.padding;
        while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) {
            distOfCurrentIdx = this._distances[++currentIndex];
        }
        // Interpolate between the two points of the segment
        const idxOfPrevPoint = currentIndex - 1;
        const distOfPrevIdx = this._distances[idxOfPrevPoint];
        const segmentLength = distOfCurrentIdx - distOfPrevIdx;
        const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0;
        return this.points[idxOfPrevPoint].mult(1 - segmentT).add(this.points[currentIndex].mult(segmentT));
    }
}

//      
/**
 * GridIndex is a data structure for testing the intersection of
 * circles and rectangles in a 2d plane.
 * It is optimized for rapid insertion and querying.
 * GridIndex splits the plane into a set of "cells" and keeps track
 * of which geometries intersect with each cell. At query time,
 * full geometry comparisons are only done for items that share
 * at least one cell. As long as the geometries are relatively
 * uniformly distributed across the plane, this greatly reduces
 * the number of comparisons necessary.
 *
 * @private
 */
class GridIndex {
    constructor(width, height, cellSize) {
        const boxCells = this.boxCells = [];
        const circleCells = this.circleCells = [];
        // More cells -> fewer geometries to check per cell, but items tend
        // to be split across more cells.
        // Sweet spot allows most small items to fit in one cell
        this.xCellCount = Math.ceil(width / cellSize);
        this.yCellCount = Math.ceil(height / cellSize);
        for (let i = 0; i < this.xCellCount * this.yCellCount; i++) {
            boxCells.push([]);
            circleCells.push([]);
        }
        this.circleKeys = [];
        this.boxKeys = [];
        this.bboxes = [];
        this.circles = [];
        this.width = width;
        this.height = height;
        this.xScale = this.xCellCount / width;
        this.yScale = this.yCellCount / height;
        this.boxUid = 0;
        this.circleUid = 0;
    }
    keysLength() {
        return this.boxKeys.length + this.circleKeys.length;
    }
    insert(key, x1, y1, x2, y2) {
        // $FlowFixMe[method-unbinding]
        this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);
        this.boxKeys.push(key);
        this.bboxes.push(x1);
        this.bboxes.push(y1);
        this.bboxes.push(x2);
        this.bboxes.push(y2);
    }
    insertCircle(key, x, y, radius) {
        // Insert circle into grid for all cells in the circumscribing square
        // It's more than necessary (by a factor of 4/PI), but fast to insert
        // $FlowFixMe[method-unbinding]
        this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);
        this.circleKeys.push(key);
        this.circles.push(x);
        this.circles.push(y);
        this.circles.push(radius);
    }
    _insertBoxCell(x1, y1, x2, y2, cellIndex, uid) {
        this.boxCells[cellIndex].push(uid);
    }
    _insertCircleCell(x1, y1, x2, y2, cellIndex, uid) {
        this.circleCells[cellIndex].push(uid);
    }
    _query(x1, y1, x2, y2, hitTest, predicate) {
        if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {
            return hitTest ? false : [];
        }
        const result = [];
        if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {
            if (hitTest) {
                return true;
            }
            for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) {
                result.push({
                    key: this.boxKeys[boxUid],
                    x1: this.bboxes[boxUid * 4],
                    y1: this.bboxes[boxUid * 4 + 1],
                    x2: this.bboxes[boxUid * 4 + 2],
                    y2: this.bboxes[boxUid * 4 + 3]
                });
            }
            for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {
                const x = this.circles[circleUid * 3];
                const y = this.circles[circleUid * 3 + 1];
                const radius = this.circles[circleUid * 3 + 2];
                result.push({
                    key: this.circleKeys[circleUid],
                    x1: x - radius,
                    y1: y - radius,
                    x2: x + radius,
                    y2: y + radius
                });
            }
            return predicate ? result.filter(predicate) : result;
        } else {
            const queryArgs = {
                hitTest,
                seenUids: {
                    box: {},
                    circle: {}
                }
            };
            // $FlowFixMe[method-unbinding]
            this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);
            return hitTest ? result.length > 0 : result;
        }
    }
    _queryCircle(x, y, radius, hitTest, predicate) {
        // Insert circle into grid for all cells in the circumscribing square
        // It's more than necessary (by a factor of 4/PI), but fast to insert
        const x1 = x - radius;
        const x2 = x + radius;
        const y1 = y - radius;
        const y2 = y + radius;
        if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {
            return hitTest ? false : [];
        }
        // Box query early exits if the bounding box is larger than the grid, but we don't do
        // the equivalent calculation for circle queries because early exit is less likely
        // and the calculation is more expensive
        const result = [];
        const queryArgs = {
            hitTest,
            circle: {
                x,
                y,
                radius
            },
            seenUids: {
                box: {},
                circle: {}
            }
        };
        // $FlowFixMe[method-unbinding]
        this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);
        return hitTest ? result.length > 0 : result;
    }
    query(x1, y1, x2, y2, predicate) {
        return this._query(x1, y1, x2, y2, false, predicate);
    }
    hitTest(x1, y1, x2, y2, predicate) {
        return this._query(x1, y1, x2, y2, true, predicate);
    }
    hitTestCircle(x, y, radius, predicate) {
        return this._queryCircle(x, y, radius, true, predicate);
    }
    _queryCell(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) {
        const seenUids = queryArgs.seenUids;
        const boxCell = this.boxCells[cellIndex];
        if (boxCell !== null) {
            const bboxes = this.bboxes;
            for (const boxUid of boxCell) {
                if (!seenUids.box[boxUid]) {
                    seenUids.box[boxUid] = true;
                    const offset = boxUid * 4;
                    if (x1 <= bboxes[offset + 2] && y1 <= bboxes[offset + 3] && x2 >= bboxes[offset + 0] && y2 >= bboxes[offset + 1] && (!predicate || predicate(this.boxKeys[boxUid]))) {
                        if (queryArgs.hitTest) {
                            result.push(true);
                            return true;
                        } else {
                            result.push({
                                key: this.boxKeys[boxUid],
                                x1: bboxes[offset],
                                y1: bboxes[offset + 1],
                                x2: bboxes[offset + 2],
                                y2: bboxes[offset + 3]
                            });
                        }
                    }
                }
            }
        }
        const circleCell = this.circleCells[cellIndex];
        if (circleCell !== null) {
            const circles = this.circles;
            for (const circleUid of circleCell) {
                if (!seenUids.circle[circleUid]) {
                    seenUids.circle[circleUid] = true;
                    const offset = circleUid * 3;
                    if (this._circleAndRectCollide(circles[offset], circles[offset + 1], circles[offset + 2], x1, y1, x2, y2) && (!predicate || predicate(this.circleKeys[circleUid]))) {
                        if (queryArgs.hitTest) {
                            result.push(true);
                            return true;
                        } else {
                            const x = circles[offset];
                            const y = circles[offset + 1];
                            const radius = circles[offset + 2];
                            result.push({
                                key: this.circleKeys[circleUid],
                                x1: x - radius,
                                y1: y - radius,
                                x2: x + radius,
                                y2: y + radius
                            });
                        }
                    }
                }
            }
        }
    }
    _queryCellCircle(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) {
        const circle = queryArgs.circle;
        const seenUids = queryArgs.seenUids;
        const boxCell = this.boxCells[cellIndex];
        if (boxCell !== null) {
            const bboxes = this.bboxes;
            for (const boxUid of boxCell) {
                if (!seenUids.box[boxUid]) {
                    seenUids.box[boxUid] = true;
                    const offset = boxUid * 4;
                    if (this._circleAndRectCollide(circle.x, circle.y, circle.radius, bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) && (!predicate || predicate(this.boxKeys[boxUid]))) {
                        result.push(true);
                        return true;
                    }
                }
            }
        }
        const circleCell = this.circleCells[cellIndex];
        if (circleCell !== null) {
            const circles = this.circles;
            for (const circleUid of circleCell) {
                if (!seenUids.circle[circleUid]) {
                    seenUids.circle[circleUid] = true;
                    const offset = circleUid * 3;
                    if (this._circlesCollide(circles[offset], circles[offset + 1], circles[offset + 2], circle.x, circle.y, circle.radius) && (!predicate || predicate(this.circleKeys[circleUid]))) {
                        result.push(true);
                        return true;
                    }
                }
            }
        }
    }
    _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, predicate) {
        const cx1 = this._convertToXCellCoord(x1);
        const cy1 = this._convertToYCellCoord(y1);
        const cx2 = this._convertToXCellCoord(x2);
        const cy2 = this._convertToYCellCoord(y2);
        for (let x = cx1; x <= cx2; x++) {
            for (let y = cy1; y <= cy2; y++) {
                const cellIndex = this.xCellCount * y + x;
                if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate))
                    return;
            }
        }
    }
    _convertToXCellCoord(x) {
        return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));
    }
    _convertToYCellCoord(y) {
        return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));
    }
    _circlesCollide(x1, y1, r1, x2, y2, r2) {
        const dx = x2 - x1;
        const dy = y2 - y1;
        const bothRadii = r1 + r2;
        return bothRadii * bothRadii > dx * dx + dy * dy;
    }
    _circleAndRectCollide(circleX, circleY, radius, x1, y1, x2, y2) {
        const halfRectWidth = (x2 - x1) / 2;
        const distX = Math.abs(circleX - (x1 + halfRectWidth));
        if (distX > halfRectWidth + radius) {
            return false;
        }
        const halfRectHeight = (y2 - y1) / 2;
        const distY = Math.abs(circleY - (y1 + halfRectHeight));
        if (distY > halfRectHeight + radius) {
            return false;
        }
        if (distX <= halfRectWidth || distY <= halfRectHeight) {
            return true;
        }
        const dx = distX - halfRectWidth;
        const dy = distY - halfRectHeight;
        return dx * dx + dy * dy <= radius * radius;
    }
}

//      
// When a symbol crosses the edge that causes it to be included in
// collision detection, it will cause changes in the symbols around
// it. This constant specifies how many pixels to pad the edge of
// the viewport for collision detection so that the bulk of the changes
// occur offscreen. Making this constant greater increases label
// stability, but it's expensive.
const viewportPadding = 100;
/**
 * A collision index used to prevent symbols from overlapping. It keep tracks of
 * where previous symbols have been placed and is used to check if a new
 * symbol overlaps with any previously added symbols.
 *
 * There are two steps to insertion: first placeCollisionBox/Circles checks if
 * there's room for a symbol, then insertCollisionBox/Circles actually puts the
 * symbol in the index. The two step process allows paired symbols to be inserted
 * together even if they overlap.
 *
 * @private
 */
class CollisionIndex {
    constructor(transform, fogState, grid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25), ignoredGrid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)) {
        this.transform = transform;
        this.grid = grid;
        this.ignoredGrid = ignoredGrid;
        this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance;
        this.screenRightBoundary = transform.width + viewportPadding;
        this.screenBottomBoundary = transform.height + viewportPadding;
        this.gridRightBoundary = transform.width + 2 * viewportPadding;
        this.gridBottomBoundary = transform.height + 2 * viewportPadding;
        this.fogState = fogState;
    }
    placeCollisionBox(bucket, scale, collisionBox, shift, allowOverlap, textPixelRatio, posMatrix, collisionGroupPredicate) {
        let anchorX = collisionBox.projectedAnchorX;
        let anchorY = collisionBox.projectedAnchorY;
        let anchorZ = collisionBox.projectedAnchorZ;
        // Apply elevation vector to the anchor point
        const elevation = collisionBox.elevation;
        const tileID = collisionBox.tileID;
        const projection = bucket.getProjection();
        if (elevation && tileID) {
            const [ux, uy, uz] = projection.upVector(tileID.canonical, collisionBox.tileAnchorX, collisionBox.tileAnchorY);
            const upScale = projection.upVectorScale(tileID.canonical, this.transform.center.lat, this.transform.worldSize).metersToTile;
            anchorX += ux * elevation * upScale;
            anchorY += uy * elevation * upScale;
            anchorZ += uz * elevation * upScale;
        }
        const checkOcclusion = projection.name === 'globe' || !!elevation || this.transform.pitch > 0;
        const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, anchorX, anchorY, anchorZ, collisionBox.tileID, checkOcclusion, projection);
        const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;
        const tlX = (collisionBox.x1 * scale + shift.x - collisionBox.padding) * tileToViewport + projectedPoint.point.x;
        const tlY = (collisionBox.y1 * scale + shift.y - collisionBox.padding) * tileToViewport + projectedPoint.point.y;
        const brX = (collisionBox.x2 * scale + shift.x + collisionBox.padding) * tileToViewport + projectedPoint.point.x;
        const brY = (collisionBox.y2 * scale + shift.y + collisionBox.padding) * tileToViewport + projectedPoint.point.y;
        // Clip at 10 times the distance of the map center or, said otherwise, when the label
        // would be drawn at 10% the size of the features around it without scaling. Refer:
        // https://github.com/mapbox/mapbox-gl-native/wiki/Text-Rendering#perspective-scaling
        // 0.55 === projection.getPerspectiveRatio(camera_to_center, camera_to_center * 10)
        const minPerspectiveRatio = 0.55;
        const isClipped = projectedPoint.perspectiveRatio <= minPerspectiveRatio || projectedPoint.occluded;
        if (!this.isInsideGrid(tlX, tlY, brX, brY) || !allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate) || isClipped) {
            return {
                box: [],
                offscreen: false,
                occluded: projectedPoint.occluded
            };
        }
        return {
            box: [
                tlX,
                tlY,
                brX,
                brY
            ],
            offscreen: this.isOffscreen(tlX, tlY, brX, brY),
            occluded: false
        };
    }
    placeCollisionCircles(bucket, allowOverlap, symbol, lineVertexArray, glyphOffsetArray, fontSize, posMatrix, labelPlaneMatrix, labelToScreenMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding, tileID) {
        const placedCollisionCircles = [];
        const elevation = this.transform.elevation;
        const projection = bucket.getProjection();
        const getElevation = elevation ? elevation.getAtTileOffsetFunc(tileID, this.transform.center.lat, this.transform.worldSize, projection) : null;
        const tileUnitAnchorPoint = new Point$2(symbol.tileAnchorX, symbol.tileAnchorY);
        let {
            x: anchorX,
            y: anchorY,
            z: anchorZ
        } = projection.projectTilePoint(tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, tileID.canonical);
        if (getElevation) {
            const [dx, dy, dz] = getElevation(tileUnitAnchorPoint);
            anchorX += dx;
            anchorY += dy;
            anchorZ += dz;
        }
        const isGlobe = projection.name === 'globe';
        const checkOcclusion = isGlobe || !!elevation || this.transform.pitch > 0;
        const screenAnchorPoint = this.projectAndGetPerspectiveRatio(posMatrix, anchorX, anchorY, anchorZ, tileID, checkOcclusion, projection);
        const {perspectiveRatio} = screenAnchorPoint;
        const labelPlaneFontScale = (pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio) / ONE_EM;
        const labelPlaneAnchorPoint = project(anchorX, anchorY, anchorZ, labelPlaneMatrix);
        const projectionCache = {};
        const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;
        const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;
        const firstAndLastGlyph = screenAnchorPoint.signedDistanceFromCamera > 0 ? placeFirstAndLastGlyph(labelPlaneFontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, /*flip*/
        false, labelPlaneAnchorPoint, tileUnitAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache, elevation && !pitchWithMap ? getElevation : null, // pitchWithMap: no need to sample elevation as it has no effect when projecting using scale/rotate to tile space labelPlaneMatrix.
        pitchWithMap && !!elevation, projection, tileID, pitchWithMap) : null;
        let collisionDetected = false;
        let inGrid = false;
        let entirelyOffscreen = true;
        if (firstAndLastGlyph && !screenAnchorPoint.occluded) {
            const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;
            const screenPlaneMin = new Point$2(-viewportPadding, -viewportPadding);
            const screenPlaneMax = new Point$2(this.screenRightBoundary, this.screenBottomBoundary);
            const interpolator = new PathInterpolator();
            // Construct a projected path from projected line vertices. Anchor points are ignored and removed
            const {first, last} = firstAndLastGlyph;
            const firstLen = first.path.length;
            let projectedPath = [];
            for (let i = firstLen - 1; i >= 1; i--) {
                projectedPath.push(first.path[i]);
            }
            for (let i = 1; i < last.path.length; i++) {
                projectedPath.push(last.path[i]);
            }
            // Tolerate a slightly longer distance than one diameter between two adjacent circles
            const circleDist = radius * 2.5;
            // The path might need to be converted into screen space if a pitched map is used as the label space
            if (labelToScreenMatrix) {
                projectedPath = projectedPath.map(([x, y, z], index) => {
                    if (getElevation && !isGlobe) {
                        z = getElevation(index < firstLen - 1 ? first.tilePath[firstLen - 1 - index] : last.tilePath[index - firstLen + 2])[2];
                    }
                    return project(x, y, z, labelToScreenMatrix);
                });
                // Do not try to place collision circles if even of the points is behind the camera.
                // This is a plausible scenario with big camera pitch angles
                if (projectedPath.some(point => point[3] <= 0)) {
                    projectedPath = [];
                }
            }
            let segments = [];
            if (projectedPath.length > 0) {
                // Quickly check if the path is fully inside or outside of the padded collision region.
                // For overlapping paths we'll only create collision circles for the visible segments
                let minx = Infinity;
                let maxx = -Infinity;
                let miny = Infinity;
                let maxy = -Infinity;
                for (const p of projectedPath) {
                    minx = Math.min(minx, p[0]);
                    miny = Math.min(miny, p[1]);
                    maxx = Math.max(maxx, p[0]);
                    maxy = Math.max(maxy, p[1]);
                }
                // Path visible
                if (maxx >= screenPlaneMin.x && minx <= screenPlaneMax.x && maxy >= screenPlaneMin.y && miny <= screenPlaneMax.y) {
                    segments = [projectedPath.map(p => new Point$2(p[0], p[1]))];
                    if (minx < screenPlaneMin.x || maxx > screenPlaneMax.x || miny < screenPlaneMin.y || maxy > screenPlaneMax.y) {
                        // Path partially visible, clip
                        segments = clipLine(segments, screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);
                    }
                }
            }
            for (const seg of segments) {
                interpolator.reset(seg, radius * 0.25);
                let numCircles = 0;
                if (interpolator.length <= 0.5 * radius) {
                    numCircles = 1;
                } else {
                    numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;
                }
                for (let i = 0; i < numCircles; i++) {
                    const t = i / Math.max(numCircles - 1, 1);
                    const circlePosition = interpolator.lerp(t);
                    // add viewport padding to the position and perform initial collision check
                    const centerX = circlePosition.x + viewportPadding;
                    const centerY = circlePosition.y + viewportPadding;
                    placedCollisionCircles.push(centerX, centerY, radius, 0);
                    const x1 = centerX - radius;
                    const y1 = centerY - radius;
                    const x2 = centerX + radius;
                    const y2 = centerY + radius;
                    entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);
                    inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);
                    if (!allowOverlap) {
                        if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) {
                            // Don't early exit if we're showing the debug circles because we still want to calculate
                            // which circles are in use
                            collisionDetected = true;
                            if (!showCollisionCircles) {
                                return {
                                    circles: [],
                                    offscreen: false,
                                    collisionDetected,
                                    occluded: false
                                };
                            }
                        }
                    }
                }
            }
        }
        return {
            circles: !showCollisionCircles && collisionDetected || !inGrid ? [] : placedCollisionCircles,
            offscreen: entirelyOffscreen,
            collisionDetected,
            occluded: screenAnchorPoint.occluded
        };
    }
    /**
     * Because the geometries in the CollisionIndex are an approximation of the shape of
     * symbols on the map, we use the CollisionIndex to look up the symbol part of
     * `queryRenderedFeatures`.
     *
     * @private
     */
    queryRenderedSymbols(viewportQueryGeometry) {
        if (viewportQueryGeometry.length === 0 || this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0) {
            return {};
        }
        const query = [];
        let minX = Infinity;
        let minY = Infinity;
        let maxX = -Infinity;
        let maxY = -Infinity;
        for (const point of viewportQueryGeometry) {
            const gridPoint = new Point$2(point.x + viewportPadding, point.y + viewportPadding);
            minX = Math.min(minX, gridPoint.x);
            minY = Math.min(minY, gridPoint.y);
            maxX = Math.max(maxX, gridPoint.x);
            maxY = Math.max(maxY, gridPoint.y);
            query.push(gridPoint);
        }
        const features = this.grid.query(minX, minY, maxX, maxY).concat(this.ignoredGrid.query(minX, minY, maxX, maxY));
        const seenFeatures = {};
        const result = {};
        for (const feature of features) {
            const featureKey = feature.key;
            // Skip already seen features.
            if (seenFeatures[featureKey.bucketInstanceId] === undefined) {
                seenFeatures[featureKey.bucketInstanceId] = {};
            }
            if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {
                continue;
            }
            // Check if query intersects with the feature box
            // "Collision Circles" for line labels are treated as boxes here
            // Since there's no actual collision taking place, the circle vs. square
            // distinction doesn't matter as much, and box geometry is easier
            // to work with.
            const bbox = [
                new Point$2(feature.x1, feature.y1),
                new Point$2(feature.x2, feature.y1),
                new Point$2(feature.x2, feature.y2),
                new Point$2(feature.x1, feature.y2)
            ];
            if (!polygonIntersectsPolygon(query, bbox)) {
                continue;
            }
            seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;
            if (result[featureKey.bucketInstanceId] === undefined) {
                result[featureKey.bucketInstanceId] = [];
            }
            result[featureKey.bucketInstanceId].push(featureKey.featureIndex);
        }
        return result;
    }
    insertCollisionBox(collisionBox, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) {
        const grid = ignorePlacement ? this.ignoredGrid : this.grid;
        const key = {
            bucketInstanceId,
            featureIndex,
            collisionGroupID
        };
        grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);
    }
    insertCollisionCircles(collisionCircles, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) {
        const grid = ignorePlacement ? this.ignoredGrid : this.grid;
        const key = {
            bucketInstanceId,
            featureIndex,
            collisionGroupID
        };
        for (let k = 0; k < collisionCircles.length; k += 4) {
            grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);
        }
    }
    projectAndGetPerspectiveRatio(posMatrix, x, y, z, tileID, checkOcclusion, bucketProjection) {
        const p = [
            x,
            y,
            z,
            1
        ];
        let behindFog = false;
        if (z || this.transform.pitch > 0) {
            vec4_1.transformMat4(p, p, posMatrix);
            // Do not perform symbol occlusion on globe due to fog fixed range
            const isGlobe = bucketProjection.name === 'globe';
            if (this.fogState && tileID && !isGlobe) {
                const fogOpacity = getFogOpacityAtTileCoord(this.fogState, x, y, z, tileID.toUnwrapped(), this.transform);
                behindFog = fogOpacity > FOG_SYMBOL_CLIPPING_THRESHOLD;
            }
        } else {
            xyTransformMat4(p, p, posMatrix);
        }
        const w = p[3];
        const a = new Point$2((p[0] / w + 1) / 2 * this.transform.width + viewportPadding, (-p[1] / w + 1) / 2 * this.transform.height + viewportPadding);
        return {
            point: a,
            // See perspective ratio comment in symbol_sdf.vertex
            // We're doing collision detection in viewport space so we need
            // to scale down boxes in the distance
            perspectiveRatio: Math.min(0.5 + 0.5 * (this.transform.getCameraToCenterDistance(bucketProjection) / w), 1.5),
            signedDistanceFromCamera: w,
            occluded: checkOcclusion && p[2] > w || behindFog    // Occluded by the far plane
        };
    }
    isOffscreen(x1, y1, x2, y2) {
        return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;
    }
    isInsideGrid(x1, y1, x2, y2) {
        return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;
    }
    /*
    * Returns a matrix for transforming collision shapes to viewport coordinate space.
    * Use this function to render e.g. collision circles on the screen.
    *   example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos
    */
    getViewportMatrix() {
        const m = mat4_1.identity([]);
        mat4_1.translate(m, m, [
            -viewportPadding,
            -viewportPadding,
            0
        ]);
        return m;
    }
}

//      
function reconstructTileMatrix(transform, projection, coord) {
    // Bucket being rendered is built for different map projection
    // than is currently being used. Reconstruct correct matrices.
    // This code path may happen during a Globe - Mercator transition
    const tileMatrix = projection.createTileMatrix(transform, transform.worldSize, coord.toUnwrapped());
    return mat4_1.multiply(new Float32Array(16), transform.projMatrix, tileMatrix);
}
function getCollisionDebugTileProjectionMatrix(coord, bucket, transform) {
    if (bucket.projection.name === transform.projection.name) {
        return coord.projMatrix;
    }
    const tr = transform.clone();
    tr.setProjection(bucket.projection);
    return reconstructTileMatrix(tr, bucket.getProjection(), coord);
}
function getSymbolTileProjectionMatrix(coord, bucketProjection, transform) {
    if (bucketProjection.name === transform.projection.name) {
        return coord.projMatrix;
    }
    return reconstructTileMatrix(transform, bucketProjection, coord);
}
function getSymbolPlacementTileProjectionMatrix(coord, bucketProjection, transform, runtimeProjection) {
    if (bucketProjection.name === runtimeProjection) {
        return transform.calculateProjMatrix(coord.toUnwrapped());
    }
    return reconstructTileMatrix(transform, bucketProjection, coord);
}

//      
// PlacedCollisionBox with all fields optional
class OpacityState {
    constructor(prevState, increment, placed, skipFade) {
        if (prevState) {
            this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment)));
        } else {
            this.opacity = skipFade && placed ? 1 : 0;
        }
        this.placed = placed;
    }
    isHidden() {
        return this.opacity === 0 && !this.placed;
    }
}
class JointOpacityState {
    constructor(prevState, increment, placedText, placedIcon, skipFade, clipped = false) {
        this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade);
        this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade);
        this.clipped = clipped;
    }
    isHidden() {
        return this.text.isHidden() && this.icon.isHidden();
    }
}
class JointPlacement {
    // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge
    // Because these symbols aren't onscreen yet, we can skip the "fade in" animation,
    // and if a subsequent viewport change brings them into view, they'll be fully
    // visible right away.
    constructor(text, icon, skipFade, clipped = false) {
        this.text = text;
        this.icon = icon;
        this.skipFade = skipFade;
        this.clipped = clipped;
    }
}
class CollisionCircleArray {
    // Stores collision circles and placement matrices of a bucket for debug rendering.
    constructor() {
        this.invProjMatrix = mat4_1.create();
        this.viewportMatrix = mat4_1.create();
        this.circles = [];
    }
}
class RetainedQueryData {
    constructor(bucketInstanceId, featureIndex, sourceLayerIndex, bucketIndex, tileID) {
        this.bucketInstanceId = bucketInstanceId;
        this.featureIndex = featureIndex;
        this.sourceLayerIndex = sourceLayerIndex;
        this.bucketIndex = bucketIndex;
        this.tileID = tileID;
    }
}
class CollisionGroups {
    constructor(crossSourceCollisions) {
        this.crossSourceCollisions = crossSourceCollisions;
        this.maxGroupID = 0;
        this.collisionGroups = {};
    }
    get(sourceID) {
        // The predicate/groupID mechanism allows for arbitrary grouping,
        // but the current interface defines one source == one group when
        // crossSourceCollisions == true.
        if (!this.crossSourceCollisions) {
            if (!this.collisionGroups[sourceID]) {
                const nextGroupID = ++this.maxGroupID;
                this.collisionGroups[sourceID] = {
                    ID: nextGroupID,
                    predicate: key => {
                        return key.collisionGroupID === nextGroupID;
                    }
                };
            }
            return this.collisionGroups[sourceID];
        } else {
            return {
                ID: 0,
                predicate: null
            };
        }
    }
}
function calculateVariableLayoutShift(anchor, width, height, textOffset, textScale) {
    const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);
    const shiftX = -(horizontalAlign - 0.5) * width;
    const shiftY = -(verticalAlign - 0.5) * height;
    const offset = evaluateVariableOffset(anchor, textOffset);
    return new Point$2(shiftX + offset[0] * textScale, shiftY + offset[1] * textScale);
}
function offsetShift(shiftX, shiftY, rotateWithMap, pitchWithMap, angle) {
    const shift = new Point$2(shiftX, shiftY);
    if (rotateWithMap) {
        shift._rotate(pitchWithMap ? angle : -angle);
    }
    return shift;
}
class Placement {
    constructor(transform, fadeDuration, crossSourceCollisions, prevPlacement, fogState, buildingIndex) {
        this.transform = transform.clone();
        this.projection = transform.projection.name;
        this.collisionIndex = new CollisionIndex(this.transform, fogState);
        this.buildingIndex = buildingIndex;
        this.placements = {};
        this.opacities = {};
        this.variableOffsets = {};
        this.stale = false;
        this.commitTime = 0;
        this.fadeDuration = fadeDuration;
        this.retainedQueryData = {};
        this.collisionGroups = new CollisionGroups(crossSourceCollisions);
        this.collisionCircleArrays = {};
        this.prevPlacement = prevPlacement;
        if (prevPlacement) {
            prevPlacement.prevPlacement = undefined;    // Only hold on to one placement back
        }
        this.placedOrientations = {};
    }
    getBucketParts(results, styleLayer, tile, sortAcrossTiles) {
        const symbolBucket = tile.getBucket(styleLayer);
        const bucketFeatureIndex = tile.latestFeatureIndex;
        if (!symbolBucket || !bucketFeatureIndex || styleLayer.fqid !== symbolBucket.layerIds[0])
            return;
        const layout = symbolBucket.layers[0].layout;
        const collisionBoxArray = tile.collisionBoxArray;
        const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);
        const textPixelRatio = tile.tileSize / EXTENT;
        const unwrappedTileID = tile.tileID.toUnwrapped();
        this.transform.setProjection(symbolBucket.projection);
        const posMatrix = getSymbolPlacementTileProjectionMatrix(tile.tileID, symbolBucket.getProjection(), this.transform, this.projection);
        const pitchWithMap = layout.get('text-pitch-alignment') === 'map';
        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';
        styleLayer.compileFilter();
        const dynamicFilter = styleLayer.dynamicFilter();
        const dynamicFilterNeedsFeature = styleLayer.dynamicFilterNeedsFeature();
        const pixelsToTiles = this.transform.calculatePixelsToTileUnitsMatrix(tile);
        const textLabelPlaneMatrix = getLabelPlaneMatrixForPlacement(posMatrix, tile.tileID.canonical, pitchWithMap, rotateWithMap, this.transform, symbolBucket.getProjection(), pixelsToTiles);
        let labelToScreenMatrix = null;
        if (pitchWithMap) {
            const glMatrix = getGlCoordMatrix(posMatrix, tile.tileID.canonical, pitchWithMap, rotateWithMap, this.transform, symbolBucket.getProjection(), pixelsToTiles);
            labelToScreenMatrix = mat4_1.multiply([], this.transform.labelPlaneMatrix, glMatrix);
        }
        let clippingData = null;
        if (!!dynamicFilter && tile.latestFeatureIndex) {
            clippingData = {
                unwrappedTileID,
                dynamicFilter,
                dynamicFilterNeedsFeature,
                featureIndex: tile.latestFeatureIndex
            };
        }
        // As long as this placement lives, we have to hold onto this bucket's
        // matching FeatureIndex/data for querying purposes
        this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID);
        const parameters = {
            bucket: symbolBucket,
            layout,
            posMatrix,
            textLabelPlaneMatrix,
            labelToScreenMatrix,
            clippingData,
            scale,
            textPixelRatio,
            holdingForFade: tile.holdingForFade(),
            collisionBoxArray,
            partiallyEvaluatedTextSize: evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom),
            partiallyEvaluatedIconSize: evaluateSizeForZoom(symbolBucket.iconSizeData, this.transform.zoom),
            collisionGroup: this.collisionGroups.get(symbolBucket.sourceID)
        };
        if (sortAcrossTiles) {
            for (const range of symbolBucket.sortKeyRanges) {
                const {sortKey, symbolInstanceStart, symbolInstanceEnd} = range;
                results.push({
                    sortKey,
                    symbolInstanceStart,
                    symbolInstanceEnd,
                    parameters
                });
            }
        } else {
            results.push({
                symbolInstanceStart: 0,
                symbolInstanceEnd: symbolBucket.symbolInstances.length,
                parameters
            });
        }
    }
    attemptAnchorPlacement(anchor, textBox, width, height, textScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, collisionGroup, textAllowOverlap, symbolInstance, boxIndex, bucket, orientation, iconBox, textSize, iconSize) {
        const {textOffset0, textOffset1, crossTileID} = symbolInstance;
        const textOffset = [
            textOffset0,
            textOffset1
        ];
        const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textScale);
        const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(bucket, textScale, textBox, offsetShift(shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle), textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
        if (iconBox) {
            const size = bucket.getSymbolInstanceIconSize(iconSize, this.transform.zoom, symbolInstance.placedIconSymbolIndex);
            const placedIconBoxes = this.collisionIndex.placeCollisionBox(bucket, size, iconBox, offsetShift(shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle), textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
            if (placedIconBoxes.box.length === 0)
                return;
        }
        if (placedGlyphBoxes.box.length > 0) {
            let prevAnchor;
            // If this label was placed in the previous placement, record the anchor position
            // to allow us to animate the transition
            if (this.prevPlacement && this.prevPlacement.variableOffsets[crossTileID] && this.prevPlacement.placements[crossTileID] && this.prevPlacement.placements[crossTileID].text) {
                prevAnchor = this.prevPlacement.variableOffsets[crossTileID].anchor;
            }
            this.variableOffsets[crossTileID] = {
                textOffset,
                width,
                height,
                anchor,
                textScale,
                prevAnchor
            };
            this.markUsedJustification(bucket, anchor, symbolInstance, orientation);
            if (bucket.allowVerticalPlacement) {
                this.markUsedOrientation(bucket, orientation, symbolInstance);
                this.placedOrientations[crossTileID] = orientation;
            }
            return {
                shift,
                placedGlyphBoxes
            };
        }
    }
    placeLayerBucketPart(bucketPart, seenCrossTileIDs, showCollisionBoxes, updateCollisionBoxIfNecessary) {
        const {bucket, layout, posMatrix, textLabelPlaneMatrix, labelToScreenMatrix, clippingData, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, partiallyEvaluatedIconSize, collisionGroup} = bucketPart.parameters;
        const textOptional = layout.get('text-optional');
        const iconOptional = layout.get('icon-optional');
        const textAllowOverlap = layout.get('text-allow-overlap');
        const iconAllowOverlap = layout.get('icon-allow-overlap');
        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';
        const pitchWithMap = layout.get('text-pitch-alignment') === 'map';
        const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y';
        const zOffset = layout.get('symbol-z-elevate');
        this.transform.setProjection(bucket.projection);
        // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities
        // If we know a symbol is always supposed to show, force it to be marked visible even if
        // it wasn't placed into the collision index (because some or all of it was outside the range
        // of the collision grid).
        // There is a subtle edge case here we're accepting:
        //  Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false
        //  A's icon is outside the grid, so doesn't get placed
        //  A's text would be inside grid, but doesn't get placed because of icon-optional: false
        //  We still show A because of the allow-overlap settings.
        //  Symbol B has allow-overlap: false, and gets placed where A's text would be
        //  On panning in, there is a short period when Symbol B and Symbol A will overlap
        //  This is the reverse of our normal policy of "fade in on pan", but should look like any other
        //  collision and hopefully not be too noticeable.
        // See https://github.com/mapbox/mapbox-gl-js/issues/7172
        let alwaysShowText = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional);
        let alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional);
        if (!bucket.collisionArrays && collisionBoxArray) {
            bucket.deserializeCollisionBoxes(collisionBoxArray);
        }
        if (showCollisionBoxes && updateCollisionBoxIfNecessary) {
            bucket.updateCollisionDebugBuffers(this.transform.zoom, collisionBoxArray);
        }
        const placeSymbol = (symbolInstance, boxIndex, collisionArrays) => {
            const {crossTileID, numVerticalGlyphVertices} = symbolInstance;
            if (clippingData) {
                // Setup globals
                const globals = {
                    zoom: this.transform.zoom,
                    pitch: this.transform.pitch
                };
                // Deserialize feature only if necessary
                let feature = null;
                if (clippingData.dynamicFilterNeedsFeature) {
                    const featureIndex = clippingData.featureIndex;
                    const retainedQueryData = this.retainedQueryData[bucket.bucketInstanceId];
                    feature = featureIndex.loadFeature({
                        featureIndex: symbolInstance.featureIndex,
                        bucketIndex: retainedQueryData.bucketIndex,
                        sourceLayerIndex: retainedQueryData.sourceLayerIndex,
                        layoutVertexArrayOffset: 0
                    });
                }
                const canonicalTileId = this.retainedQueryData[bucket.bucketInstanceId].tileID.canonical;
                const filterFunc = clippingData.dynamicFilter;
                const shouldClip = !filterFunc(globals, feature, canonicalTileId, new Point$2(symbolInstance.tileAnchorX, symbolInstance.tileAnchorY), this.transform.calculateDistanceTileData(clippingData.unwrappedTileID));
                if (shouldClip) {
                    this.placements[crossTileID] = new JointPlacement(false, false, false, true);
                    seenCrossTileIDs.add(crossTileID);
                    return;
                }
            }
            if (seenCrossTileIDs.has(crossTileID))
                return;
            if (holdingForFade) {
                // Mark all symbols from this tile as "not placed", but don't add to seenCrossTileIDs, because we don't
                // know yet if we have a duplicate in a parent tile that _should_ be placed.
                this.placements[crossTileID] = new JointPlacement(false, false, false);
                return;
            }
            let placeText = false;
            let placeIcon = false;
            let offscreen = true;
            let textOccluded = false;
            let iconOccluded = false;
            let shift = null;
            let placed = {
                box: null,
                offscreen: null,
                occluded: null
            };
            let placedVerticalText = {
                box: null,
                offscreen: null,
                occluded: null
            };
            let placedGlyphBoxes = null;
            let placedGlyphCircles = null;
            let placedIconBoxes = null;
            let textFeatureIndex = 0;
            let verticalTextFeatureIndex = 0;
            let iconFeatureIndex = 0;
            if (collisionArrays.textFeatureIndex) {
                textFeatureIndex = collisionArrays.textFeatureIndex;
            } else if (symbolInstance.useRuntimeCollisionCircles) {
                textFeatureIndex = symbolInstance.featureIndex;
            }
            if (collisionArrays.verticalTextFeatureIndex) {
                verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex;
            }
            const updateBoxData = box => {
                box.tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID;
                const elevation = this.transform.elevation;
                box.elevation = symbolInstance.zOffset + (elevation ? elevation.getAtTileOffset(box.tileID, box.tileAnchorX, box.tileAnchorY) : 0);
            };
            const textBox = collisionArrays.textBox;
            if (textBox) {
                updateBoxData(textBox);
                const updatePreviousOrientationIfNotPlaced = isPlaced => {
                    let previousOrientation = WritingMode.horizontal;
                    if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) {
                        const prevPlacedOrientation = this.prevPlacement.placedOrientations[crossTileID];
                        if (prevPlacedOrientation) {
                            this.placedOrientations[crossTileID] = prevPlacedOrientation;
                            previousOrientation = prevPlacedOrientation;
                            this.markUsedOrientation(bucket, previousOrientation, symbolInstance);
                        }
                    }
                    return previousOrientation;
                };
                const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => {
                    if (bucket.allowVerticalPlacement && numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) {
                        for (const placementMode of bucket.writingModes) {
                            if (placementMode === WritingMode.vertical) {
                                placed = placeVerticalFn();
                                placedVerticalText = placed;
                            } else {
                                placed = placeHorizontalFn();
                            }
                            if (placed && placed.box && placed.box.length)
                                break;
                        }
                    } else {
                        placed = placeHorizontalFn();
                    }
                };
                if (!layout.get('text-variable-anchor')) {
                    const placeBox = (collisionTextBox, orientation) => {
                        const textScale = bucket.getSymbolInstanceTextSize(partiallyEvaluatedTextSize, symbolInstance, this.transform.zoom, boxIndex);
                        const placedFeature = this.collisionIndex.placeCollisionBox(bucket, textScale, collisionTextBox, new Point$2(0, 0), textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
                        if (placedFeature && placedFeature.box && placedFeature.box.length) {
                            this.markUsedOrientation(bucket, orientation, symbolInstance);
                            this.placedOrientations[crossTileID] = orientation;
                        }
                        return placedFeature;
                    };
                    const placeHorizontal = () => {
                        return placeBox(textBox, WritingMode.horizontal);
                    };
                    const placeVertical = () => {
                        const verticalTextBox = collisionArrays.verticalTextBox;
                        if (bucket.allowVerticalPlacement && numVerticalGlyphVertices > 0 && verticalTextBox) {
                            updateBoxData(verticalTextBox);
                            return placeBox(verticalTextBox, WritingMode.vertical);
                        }
                        return {
                            box: null,
                            offscreen: null,
                            occluded: null
                        };
                    };
                    placeTextForPlacementModes(placeHorizontal, placeVertical);
                    const isPlaced = placed && placed.box && placed.box.length;
                    updatePreviousOrientationIfNotPlaced(!!isPlaced);
                } else {
                    let anchors = layout.get('text-variable-anchor');
                    // If this symbol was in the last placement, shift the previously used
                    // anchor to the front of the anchor list, only if the previous anchor
                    // is still in the anchor list
                    if (this.prevPlacement && this.prevPlacement.variableOffsets[crossTileID]) {
                        const prevOffsets = this.prevPlacement.variableOffsets[crossTileID];
                        if (anchors.indexOf(prevOffsets.anchor) > 0) {
                            anchors = anchors.filter(anchor => anchor !== prevOffsets.anchor);
                            anchors.unshift(prevOffsets.anchor);
                        }
                    }
                    const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => {
                        const textScale = bucket.getSymbolInstanceTextSize(partiallyEvaluatedTextSize, symbolInstance, this.transform.zoom, boxIndex);
                        const width = (collisionTextBox.x2 - collisionTextBox.x1) * textScale + 2 * collisionTextBox.padding;
                        const height = (collisionTextBox.y2 - collisionTextBox.y1) * textScale + 2 * collisionTextBox.padding;
                        const variableIconBox = symbolInstance.hasIconTextFit && !iconAllowOverlap ? collisionIconBox : null;
                        if (variableIconBox)
                            updateBoxData(variableIconBox);
                        let placedBox = {
                            box: [],
                            offscreen: false,
                            occluded: false
                        };
                        const placementAttempts = textAllowOverlap ? anchors.length * 2 : anchors.length;
                        for (let i = 0; i < placementAttempts; ++i) {
                            const anchor = anchors[i % anchors.length];
                            const allowOverlap = i >= anchors.length;
                            const result = this.attemptAnchorPlacement(anchor, collisionTextBox, width, height, textScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, collisionGroup, allowOverlap, symbolInstance, boxIndex, bucket, orientation, variableIconBox, partiallyEvaluatedTextSize, partiallyEvaluatedIconSize);
                            if (result) {
                                placedBox = result.placedGlyphBoxes;
                                if (placedBox && placedBox.box && placedBox.box.length) {
                                    placeText = true;
                                    shift = result.shift;
                                    break;
                                }
                            }
                        }
                        return placedBox;
                    };
                    const placeHorizontal = () => {
                        return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal);
                    };
                    const placeVertical = () => {
                        const verticalTextBox = collisionArrays.verticalTextBox;
                        if (verticalTextBox)
                            updateBoxData(verticalTextBox);
                        const wasPlaced = placed && placed.box && placed.box.length;
                        if (bucket.allowVerticalPlacement && !wasPlaced && numVerticalGlyphVertices > 0 && verticalTextBox) {
                            return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical);
                        }
                        return {
                            box: null,
                            offscreen: null,
                            occluded: null
                        };
                    };
                    placeTextForPlacementModes(placeHorizontal, placeVertical);
                    if (placed) {
                        placeText = placed.box;
                        offscreen = placed.offscreen;
                        textOccluded = placed.occluded;
                    }
                    const isPlaced = placed && placed.box;
                    const prevOrientation = updatePreviousOrientationIfNotPlaced(!!isPlaced);
                    // If we didn't get placed, we still need to copy our position from the last placement for
                    // fade animations
                    if (!placeText && this.prevPlacement) {
                        const prevOffset = this.prevPlacement.variableOffsets[crossTileID];
                        if (prevOffset) {
                            this.variableOffsets[crossTileID] = prevOffset;
                            this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation);
                        }
                    }
                }
            }
            placedGlyphBoxes = placed;
            placeText = placedGlyphBoxes && placedGlyphBoxes.box && placedGlyphBoxes.box.length > 0;
            offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen;
            textOccluded = placedGlyphBoxes && placedGlyphBoxes.occluded;
            if (symbolInstance.useRuntimeCollisionCircles) {
                const placedSymbolIndex = symbolInstance.centerJustifiedTextSymbolIndex >= 0 ? symbolInstance.centerJustifiedTextSymbolIndex : symbolInstance.verticalPlacedTextSymbolIndex;
                const placedSymbol = bucket.text.placedSymbolArray.get(placedSymbolIndex);
                const fontSize = evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);
                const textPixelPadding = layout.get('text-padding');
                // Convert circle collision height into pixels
                const circlePixelDiameter = symbolInstance.collisionCircleDiameter * fontSize / ONE_EM;
                placedGlyphCircles = this.collisionIndex.placeCollisionCircles(bucket, textAllowOverlap, placedSymbol, bucket.lineVertexArray, bucket.glyphOffsetArray, fontSize, posMatrix, textLabelPlaneMatrix, labelToScreenMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding, this.retainedQueryData[bucket.bucketInstanceId].tileID);
                // If text-allow-overlap is set, force "placedCircles" to true
                // In theory there should always be at least one circle placed
                // in this case, but for now quirks in text-anchor
                // and text-offset may prevent that from being true.
                placeText = textAllowOverlap || placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected;
                offscreen = offscreen && placedGlyphCircles.offscreen;
                textOccluded = placedGlyphCircles.occluded;
            }
            if (collisionArrays.iconFeatureIndex) {
                iconFeatureIndex = collisionArrays.iconFeatureIndex;
            }
            if (collisionArrays.iconBox) {
                const placeIconFeature = iconBox => {
                    updateBoxData(iconBox);
                    const shiftPoint = symbolInstance.hasIconTextFit && shift ? offsetShift(shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle) : new Point$2(0, 0);
                    const iconScale = bucket.getSymbolInstanceIconSize(partiallyEvaluatedIconSize, this.transform.zoom, symbolInstance.placedIconSymbolIndex);
                    return this.collisionIndex.placeCollisionBox(bucket, iconScale, iconBox, shiftPoint, iconAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
                };
                if (placedVerticalText && placedVerticalText.box && placedVerticalText.box.length && collisionArrays.verticalIconBox) {
                    placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox);
                    placeIcon = placedIconBoxes.box.length > 0;
                } else {
                    placedIconBoxes = placeIconFeature(collisionArrays.iconBox);
                    placeIcon = placedIconBoxes.box.length > 0;
                }
                offscreen = offscreen && placedIconBoxes.offscreen;
                iconOccluded = placedIconBoxes.occluded;
            }
            const iconWithoutText = textOptional || symbolInstance.numHorizontalGlyphVertices === 0 && numVerticalGlyphVertices === 0;
            const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0;
            // Combine the scales for icons and text.
            if (!iconWithoutText && !textWithoutIcon) {
                placeIcon = placeText = placeIcon && placeText;
            } else if (!textWithoutIcon) {
                placeText = placeIcon && placeText;
            } else if (!iconWithoutText) {
                placeIcon = placeIcon && placeText;
            }
            if (placeText && placedGlyphBoxes && placedGlyphBoxes.box) {
                if (placedVerticalText && placedVerticalText.box && verticalTextFeatureIndex) {
                    this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'), bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID);
                } else {
                    this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);
                }
            }
            if (placeIcon && placedIconBoxes) {
                this.collisionIndex.insertCollisionBox(placedIconBoxes.box, layout.get('icon-ignore-placement'), bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID);
            }
            if (placedGlyphCircles) {
                if (placeText) {
                    this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);
                }
                if (showCollisionBoxes) {
                    const id = bucket.bucketInstanceId;
                    let circleArray = this.collisionCircleArrays[id];
                    // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement
                    // for a bucket is not guaranteed to be complete before the commit-function has been called
                    if (circleArray === undefined)
                        circleArray = this.collisionCircleArrays[id] = new CollisionCircleArray();
                    for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {
                        circleArray.circles.push(placedGlyphCircles.circles[i + 0]);
                        // x
                        circleArray.circles.push(placedGlyphCircles.circles[i + 1]);
                        // y
                        circleArray.circles.push(placedGlyphCircles.circles[i + 2]);
                        // radius
                        circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0);    // collisionDetected-flag
                    }
                }
            }
            const notGlobe = bucket.projection.name !== 'globe';
            alwaysShowText = alwaysShowText && (notGlobe || !textOccluded);
            alwaysShowIcon = alwaysShowIcon && (notGlobe || !iconOccluded);
            this.placements[crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded);
            seenCrossTileIDs.add(crossTileID);
        };
        if (zOffset && this.buildingIndex) {
            const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID;
            this.buildingIndex.updateZOffset(bucket, tileID);
            bucket.updateZOffset();
        }
        if (zOrderByViewportY) {
            const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle);
            for (let i = symbolIndexes.length - 1; i >= 0; --i) {
                const symbolIndex = symbolIndexes[i];
                placeSymbol(bucket.symbolInstances.get(symbolIndex), symbolIndex, bucket.collisionArrays[symbolIndex]);
            }
            if (bucket.hasAnyZOffset)
                warnOnce(`${ bucket.layerIds[0] } layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`);
        } else if (bucket.hasAnyZOffset) {
            const indexes = bucket.getSortedIndexesByZOffset();
            for (let i = 0; i < indexes.length; ++i) {
                const symbolIndex = indexes[i];
                placeSymbol(bucket.symbolInstances.get(symbolIndex), symbolIndex, bucket.collisionArrays[symbolIndex]);
            }
        } else {
            for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) {
                placeSymbol(bucket.symbolInstances.get(i), i, bucket.collisionArrays[i]);
            }
        }
        if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) {
            const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId];
            // Store viewport and inverse projection matrices per bucket
            mat4_1.invert(circleArray.invProjMatrix, posMatrix);
            circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix();
        }
        bucket.justReloaded = false;
    }
    markUsedJustification(bucket, placedAnchor, symbolInstance, orientation) {
        const {
            leftJustifiedTextSymbolIndex: left,
            centerJustifiedTextSymbolIndex: center,
            rightJustifiedTextSymbolIndex: right,
            verticalPlacedTextSymbolIndex: vertical,
            crossTileID
        } = symbolInstance;
        const justification = getAnchorJustification(placedAnchor);
        const autoIndex = orientation === WritingMode.vertical ? vertical : justification === 'left' ? left : justification === 'center' ? center : justification === 'right' ? right : -1;
        // If there are multiple justifications and this one isn't it: shift offscreen
        // If either this is the chosen justification or the justification is hardwired: use it
        if (left >= 0)
            bucket.text.placedSymbolArray.get(left).crossTileID = autoIndex >= 0 && left !== autoIndex ? 0 : crossTileID;
        if (center >= 0)
            bucket.text.placedSymbolArray.get(center).crossTileID = autoIndex >= 0 && center !== autoIndex ? 0 : crossTileID;
        if (right >= 0)
            bucket.text.placedSymbolArray.get(right).crossTileID = autoIndex >= 0 && right !== autoIndex ? 0 : crossTileID;
        if (vertical >= 0)
            bucket.text.placedSymbolArray.get(vertical).crossTileID = autoIndex >= 0 && vertical !== autoIndex ? 0 : crossTileID;
    }
    markUsedOrientation(bucket, orientation, symbolInstance) {
        const horizontalOrientation = orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly ? orientation : 0;
        const verticalOrientation = orientation === WritingMode.vertical ? orientation : 0;
        const {
            leftJustifiedTextSymbolIndex: left,
            centerJustifiedTextSymbolIndex: center,
            rightJustifiedTextSymbolIndex: right,
            verticalPlacedTextSymbolIndex: vertical
        } = symbolInstance;
        const array = bucket.text.placedSymbolArray;
        if (left >= 0)
            array.get(left).placedOrientation = horizontalOrientation;
        if (center >= 0)
            array.get(center).placedOrientation = horizontalOrientation;
        if (right >= 0)
            array.get(right).placedOrientation = horizontalOrientation;
        if (vertical >= 0)
            array.get(vertical).placedOrientation = verticalOrientation;
    }
    commit(now) {
        this.commitTime = now;
        this.zoomAtLastRecencyCheck = this.transform.zoom;
        const prevPlacement = this.prevPlacement;
        let placementChanged = false;
        this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0;
        const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1;
        const prevOpacities = prevPlacement ? prevPlacement.opacities : {};
        const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {};
        const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {};
        // add the opacities from the current placement, and copy their current values from the previous placement
        for (const crossTileID in this.placements) {
            const jointPlacement = this.placements[crossTileID];
            const prevOpacity = prevOpacities[crossTileID];
            if (prevOpacity) {
                this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon, null, jointPlacement.clipped);
                placementChanged = placementChanged || jointPlacement.text !== prevOpacity.text.placed || jointPlacement.icon !== prevOpacity.icon.placed;
            } else {
                this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade, jointPlacement.clipped);
                placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon;
            }
        }
        // copy and update values from the previous placement that aren't in the current placement but haven't finished fading
        for (const crossTileID in prevOpacities) {
            const prevOpacity = prevOpacities[crossTileID];
            if (!this.opacities[crossTileID]) {
                const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false);
                if (!jointOpacity.isHidden()) {
                    this.opacities[crossTileID] = jointOpacity;
                    placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed;
                }
            }
        }
        for (const crossTileID in prevOffsets) {
            if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {
                this.variableOffsets[crossTileID] = prevOffsets[crossTileID];
            }
        }
        for (const crossTileID in prevOrientations) {
            if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {
                this.placedOrientations[crossTileID] = prevOrientations[crossTileID];
            }
        }
        if (placementChanged) {
            this.lastPlacementChangeTime = now;
        } else if (typeof this.lastPlacementChangeTime !== 'number') {
            this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now;
        }
    }
    updateLayerOpacities(styleLayer, tiles) {
        const seenCrossTileIDs = new Set();
        for (const tile of tiles) {
            const symbolBucket = tile.getBucket(styleLayer);
            if (symbolBucket && tile.latestFeatureIndex && styleLayer.fqid === symbolBucket.layerIds[0]) {
                this.updateBucketOpacities(symbolBucket, seenCrossTileIDs, tile.collisionBoxArray);
                const layout = symbolBucket.layers[0].layout;
                if (layout.get('symbol-z-elevate') && this.buildingIndex) {
                    this.buildingIndex.updateZOffset(symbolBucket, tile.tileID);
                    symbolBucket.updateZOffset();
                }
            }
        }
    }
    updateBucketOpacities(bucket, seenCrossTileIDs, collisionBoxArray) {
        if (bucket.hasTextData())
            bucket.text.opacityVertexArray.clear();
        if (bucket.hasIconData())
            bucket.icon.opacityVertexArray.clear();
        if (bucket.hasIconCollisionBoxData())
            bucket.iconCollisionBox.collisionVertexArray.clear();
        if (bucket.hasTextCollisionBoxData())
            bucket.textCollisionBox.collisionVertexArray.clear();
        const layout = bucket.layers[0].layout;
        const hasClipping = !!bucket.layers[0].dynamicFilter();
        const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true);
        const textAllowOverlap = layout.get('text-allow-overlap');
        const iconAllowOverlap = layout.get('icon-allow-overlap');
        const variablePlacement = layout.get('text-variable-anchor');
        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';
        const pitchWithMap = layout.get('text-pitch-alignment') === 'map';
        // If allow-overlap is true, we can show symbols before placement runs on them
        // But we have to wait for placement if we potentially depend on a paired icon/text
        // with allow-overlap: false.
        // See https://github.com/mapbox/mapbox-gl-js/issues/7032
        const defaultOpacityState = new JointOpacityState(null, 0, textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')), iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')), true);
        if (!bucket.collisionArrays && collisionBoxArray && (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData())) {
            bucket.deserializeCollisionBoxes(collisionBoxArray);
        }
        const addOpacities = (iconOrText, numVertices, opacity) => {
            for (let i = 0; i < numVertices / 4; i++) {
                iconOrText.opacityVertexArray.emplaceBack(opacity);
            }
        };
        let visibleInstanceCount = 0;
        for (let s = 0; s < bucket.symbolInstances.length; s++) {
            const symbolInstance = bucket.symbolInstances.get(s);
            const {numHorizontalGlyphVertices, numVerticalGlyphVertices, crossTileID, numIconVertices} = symbolInstance;
            const isDuplicate = seenCrossTileIDs.has(crossTileID);
            let opacityState = this.opacities[crossTileID];
            if (isDuplicate) {
                opacityState = duplicateOpacityState;
            } else if (!opacityState) {
                opacityState = defaultOpacityState;
                // store the state so that future placements use it as a starting point
                this.opacities[crossTileID] = opacityState;
            }
            seenCrossTileIDs.add(crossTileID);
            const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;
            const hasIcon = numIconVertices > 0;
            const placedOrientation = this.placedOrientations[crossTileID];
            const horizontalHidden = placedOrientation === WritingMode.vertical;
            const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly;
            if ((hasText || hasIcon) && !opacityState.isHidden())
                visibleInstanceCount++;
            if (hasText) {
                const packedOpacity = packOpacity(opacityState.text);
                // Vertical text fades in/out on collision the same way as corresponding
                // horizontal text. Switch between vertical/horizontal should be instantaneous
                const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
                addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);
                const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
                addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);
                // If this label is completely faded, mark it so that we don't have to calculate
                // its position at render time. If this layer has variable placement, shift the various
                // symbol instances appropriately so that symbols from buckets that have yet to be placed
                // offset appropriately.
                const symbolHidden = opacityState.text.isHidden();
                const {
                    leftJustifiedTextSymbolIndex: left,
                    centerJustifiedTextSymbolIndex: center,
                    rightJustifiedTextSymbolIndex: right,
                    verticalPlacedTextSymbolIndex: vertical
                } = symbolInstance;
                const array = bucket.text.placedSymbolArray;
                const horizontalHiddenValue = symbolHidden || horizontalHidden ? 1 : 0;
                if (left >= 0)
                    array.get(left).hidden = horizontalHiddenValue;
                if (center >= 0)
                    array.get(center).hidden = horizontalHiddenValue;
                if (right >= 0)
                    array.get(right).hidden = horizontalHiddenValue;
                if (vertical >= 0)
                    array.get(vertical).hidden = symbolHidden || verticalHidden ? 1 : 0;
                const prevOffset = this.variableOffsets[crossTileID];
                if (prevOffset) {
                    this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation);
                }
                const prevOrientation = this.placedOrientations[crossTileID];
                if (prevOrientation) {
                    this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation);
                    this.markUsedOrientation(bucket, prevOrientation, symbolInstance);
                }
            }
            if (hasIcon) {
                const packedOpacity = packOpacity(opacityState.icon);
                const {placedIconSymbolIndex, verticalPlacedIconSymbolIndex} = symbolInstance;
                const array = bucket.icon.placedSymbolArray;
                const iconHidden = opacityState.icon.isHidden() ? 1 : 0;
                if (placedIconSymbolIndex >= 0) {
                    const horizontalOpacity = !horizontalHidden ? packedOpacity : PACKED_HIDDEN_OPACITY;
                    addOpacities(bucket.icon, numIconVertices, horizontalOpacity);
                    array.get(placedIconSymbolIndex).hidden = iconHidden;
                }
                if (verticalPlacedIconSymbolIndex >= 0) {
                    const verticalOpacity = !verticalHidden ? packedOpacity : PACKED_HIDDEN_OPACITY;
                    addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity);
                    array.get(verticalPlacedIconSymbolIndex).hidden = iconHidden;
                }
            }
            if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) {
                const collisionArrays = bucket.collisionArrays[s];
                if (collisionArrays) {
                    let shift = new Point$2(0, 0);
                    let used = true;
                    if (collisionArrays.textBox || collisionArrays.verticalTextBox) {
                        if (variablePlacement) {
                            const variableOffset = this.variableOffsets[crossTileID];
                            if (variableOffset) {
                                // This will show either the currently placed position or the last
                                // successfully placed position (so you can visualize what collision
                                // just made the symbol disappear, and the most likely place for the
                                // symbol to come back)
                                shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textScale);
                                if (rotateWithMap) {
                                    shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle);
                                }
                            } else {
                                // No offset -> this symbol hasn't been placed since coming on-screen
                                // No single box is particularly meaningful and all of them would be too noisy
                                // Use the center box just to show something's there, but mark it "not used"
                                used = false;
                            }
                        }
                        if (hasClipping) {
                            used = !opacityState.clipped;
                        }
                        if (collisionArrays.textBox) {
                            updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || horizontalHidden, shift.x, shift.y);
                        }
                        if (collisionArrays.verticalTextBox) {
                            updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || verticalHidden, shift.x, shift.y);
                        }
                    }
                    const verticalIconUsed = used && Boolean(!verticalHidden && collisionArrays.verticalIconBox);
                    if (collisionArrays.iconBox) {
                        updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, verticalIconUsed, symbolInstance.hasIconTextFit ? shift.x : 0, symbolInstance.hasIconTextFit ? shift.y : 0);
                    }
                    if (collisionArrays.verticalIconBox) {
                        updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, !verticalIconUsed, symbolInstance.hasIconTextFit ? shift.x : 0, symbolInstance.hasIconTextFit ? shift.y : 0);
                    }
                }
            }
        }
        bucket.fullyClipped = visibleInstanceCount === 0;
        bucket.sortFeatures(this.transform.angle);
        if (this.retainedQueryData[bucket.bucketInstanceId]) {
            this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder;
        }
        if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) {
            bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray);
        }
        if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) {
            bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray);
        }
        if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) {
            bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray);
        }
        if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) {
            bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray);
        }
        // Push generated collision circles to the bucket for debug rendering
        if (bucket.bucketInstanceId in this.collisionCircleArrays) {
            const instance = this.collisionCircleArrays[bucket.bucketInstanceId];
            bucket.placementInvProjMatrix = instance.invProjMatrix;
            bucket.placementViewportMatrix = instance.viewportMatrix;
            bucket.collisionCircleArray = instance.circles;
            delete this.collisionCircleArrays[bucket.bucketInstanceId];
        }
    }
    symbolFadeChange(now) {
        return this.fadeDuration === 0 ? 1 : (now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment;
    }
    zoomAdjustment(zoom) {
        // When zooming out quickly, labels can overlap each other. This
        // adjustment is used to reduce the interval between placement calculations
        // and to reduce the fade duration when zooming out quickly. Discovering the
        // collisions more quickly and fading them more quickly reduces the unwanted effect.
        return Math.max(0, (this.transform.zoom - zoom) / 1.5);
    }
    hasTransitions(now) {
        return this.stale || now - this.lastPlacementChangeTime < this.fadeDuration;
    }
    stillRecent(now, zoom) {
        // The adjustment makes placement more frequent when zooming.
        // This condition applies the adjustment only after the map has
        // stopped zooming. This avoids adding extra jank while zooming.
        const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? 1 - this.zoomAdjustment(zoom) : 1;
        this.zoomAtLastRecencyCheck = zoom;
        return this.commitTime + this.fadeDuration * durationAdjustment > now;
    }
    setStale() {
        this.stale = true;
    }
}
function updateCollisionVertices(collisionVertexArray, placed, notUsed, shiftX, shiftY) {
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
}
// All four vertices for a glyph will have the same opacity state
// So we pack the opacity into a uint8, and then repeat it four times
// to make a single uint32 that we can upload for each glyph in the
// label.
const shift25 = Math.pow(2, 25);
const shift24 = Math.pow(2, 24);
const shift17 = Math.pow(2, 17);
const shift16 = Math.pow(2, 16);
const shift9 = Math.pow(2, 9);
const shift8 = Math.pow(2, 8);
const shift1 = Math.pow(2, 1);
function packOpacity(opacityState) {
    if (opacityState.opacity === 0 && !opacityState.placed) {
        return 0;
    } else if (opacityState.opacity === 1 && opacityState.placed) {
        return 4294967295;
    }
    const targetBit = opacityState.placed ? 1 : 0;
    const opacityBits = Math.floor(opacityState.opacity * 127);
    return opacityBits * shift25 + targetBit * shift24 + opacityBits * shift17 + targetBit * shift16 + opacityBits * shift9 + targetBit * shift8 + opacityBits * shift1 + targetBit;
}
const PACKED_HIDDEN_OPACITY = 0;

//      
class LayerPlacement {
    constructor(styleLayer) {
        this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' && styleLayer.layout.get('symbol-sort-key').constantOr(1) !== undefined;
        this._currentTileIndex = 0;
        this._currentPartIndex = 0;
        this._seenCrossTileIDs = new Set();
        this._bucketParts = [];
    }
    continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement) {
        const bucketParts = this._bucketParts;
        while (this._currentTileIndex < tiles.length) {
            const tile = tiles[this._currentTileIndex];
            placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles);
            this._currentTileIndex++;
            if (shouldPausePlacement()) {
                return true;
            }
        }
        if (this._sortAcrossTiles) {
            this._sortAcrossTiles = false;
            bucketParts.sort((a, b) => a.sortKey - b.sortKey);
        }
        while (this._currentPartIndex < bucketParts.length) {
            const bucketPart = bucketParts[this._currentPartIndex];
            placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes, bucketPart.symbolInstanceStart === 0);
            this._currentPartIndex++;
            if (shouldPausePlacement()) {
                return true;
            }
        }
        return false;
    }
}
class PauseablePlacement {
    constructor(transform, order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, prevPlacement, fogState, buildingIndex) {
        this.placement = new Placement(transform, fadeDuration, crossSourceCollisions, prevPlacement, fogState, buildingIndex);
        this._currentPlacementIndex = order.length - 1;
        this._forceFullPlacement = forceFullPlacement;
        this._showCollisionBoxes = showCollisionBoxes;
        this._done = false;
    }
    isDone() {
        return this._done;
    }
    continuePlacement(order, layers, layerTiles, layerTilesInYOrder) {
        const startTime = exported$1.now();
        const shouldPausePlacement = () => {
            const elapsedTime = exported$1.now() - startTime;
            return this._forceFullPlacement ? false : elapsedTime > 2;
        };
        while (this._currentPlacementIndex >= 0) {
            const layerId = order[this._currentPlacementIndex];
            const layer = layers[layerId];
            const placementZoom = this.placement.collisionIndex.transform.zoom;
            if (layer.type === 'symbol' && (!layer.minzoom || layer.minzoom <= placementZoom) && (!layer.maxzoom || layer.maxzoom > placementZoom)) {
                const symbolLayer = layer;
                const zOffset = symbolLayer.layout.get('symbol-z-elevate');
                const inProgressLayer = this._inProgressLayer = this._inProgressLayer || new LayerPlacement(symbolLayer);
                const sourceId = makeFQID(layer.source, layer.scope);
                const pausePlacement = inProgressLayer.continuePlacement(zOffset ? layerTilesInYOrder[sourceId] : layerTiles[sourceId], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement);
                if (pausePlacement) {
                    // We didn't finish placing all layers within 2ms,
                    // but we can keep rendering with a partial placement
                    // We'll resume here on the next frame
                    return;
                }
                delete this._inProgressLayer;
            }
            this._currentPlacementIndex--;
        }
        this._done = true;
    }
    commit(now) {
        this.placement.commit(now);
        return this.placement;
    }
}

const ARRAY_TYPES = [
    Int8Array,
    Uint8Array,
    Uint8ClampedArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Float32Array,
    Float64Array
];
/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
const VERSION = 1;
// serialized format version
const HEADER_SIZE = 8;
class KDBush {
    /**
     * Creates an index from raw `ArrayBuffer` data.
     * @param {ArrayBuffer} data
     */
    static from(data) {
        if (!(data instanceof ArrayBuffer)) {
            throw new Error('Data must be an instance of ArrayBuffer.');
        }
        const [magic, versionAndType] = new Uint8Array(data, 0, 2);
        if (magic !== 219) {
            throw new Error('Data does not appear to be in a KDBush format.');
        }
        const version = versionAndType >> 4;
        if (version !== VERSION) {
            throw new Error(`Got v${ version } data when expected v${ VERSION }.`);
        }
        const ArrayType = ARRAY_TYPES[versionAndType & 15];
        if (!ArrayType) {
            throw new Error('Unrecognized array type.');
        }
        const [nodeSize] = new Uint16Array(data, 2, 1);
        const [numItems] = new Uint32Array(data, 4, 1);
        return new KDBush(numItems, nodeSize, ArrayType, data);
    }
    /**
     * Creates an index that will hold a given number of items.
     * @param {number} numItems
     * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
     * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
     * @param {ArrayBuffer} [data] (For internal use only)
     */
    constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
        if (isNaN(numItems) || numItems < 0)
            throw new Error(`Unpexpected numItems value: ${ numItems }.`);
        this.numItems = +numItems;
        this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
        this.ArrayType = ArrayType;
        this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
        const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
        const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
        const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
        const padCoords = (8 - idsByteSize % 8) % 8;
        if (arrayTypeIndex < 0) {
            throw new Error(`Unexpected typed array class: ${ ArrayType }.`);
        }
        if (data && data instanceof ArrayBuffer) {
            // reconstruct an index from a buffer
            this.data = data;
            this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
            this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
            this._pos = numItems * 2;
            this._finished = true;
        } else {
            // initialize a new index
            this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
            this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
            this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
            this._pos = 0;
            this._finished = false;
            // set header
            new Uint8Array(this.data, 0, 2).set([
                219,
                (VERSION << 4) + arrayTypeIndex
            ]);
            new Uint16Array(this.data, 2, 1)[0] = nodeSize;
            new Uint32Array(this.data, 4, 1)[0] = numItems;
        }
    }
    /**
     * Add a point to the index.
     * @param {number} x
     * @param {number} y
     * @returns {number} An incremental index associated with the added item (starting from `0`).
     */
    add(x, y) {
        const index = this._pos >> 1;
        this.ids[index] = index;
        this.coords[this._pos++] = x;
        this.coords[this._pos++] = y;
        return index;
    }
    /**
     * Perform indexing of the added points.
     */
    finish() {
        const numAdded = this._pos >> 1;
        if (numAdded !== this.numItems) {
            throw new Error(`Added ${ numAdded } items when expected ${ this.numItems }.`);
        }
        // kd-sort both arrays for efficient search
        sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
        this._finished = true;
        return this;
    }
    /**
     * Search the index for items within a given bounding box.
     * @param {number} minX
     * @param {number} minY
     * @param {number} maxX
     * @param {number} maxY
     * @returns {number[]} An array of indices correponding to the found items.
     */
    range(minX, minY, maxX, maxY) {
        if (!this._finished)
            throw new Error('Data not yet indexed - call index.finish().');
        const {ids, coords, nodeSize} = this;
        const stack = [
            0,
            ids.length - 1,
            0
        ];
        const result = [];
        // recursively search for items in range in the kd-sorted arrays
        while (stack.length) {
            const axis = stack.pop() || 0;
            const right = stack.pop() || 0;
            const left = stack.pop() || 0;
            // if we reached "tree node", search linearly
            if (right - left <= nodeSize) {
                for (let i = left; i <= right; i++) {
                    const x = coords[2 * i];
                    const y = coords[2 * i + 1];
                    if (x >= minX && x <= maxX && y >= minY && y <= maxY)
                        result.push(ids[i]);
                }
                continue;
            }
            // otherwise find the middle index
            const m = left + right >> 1;
            // include the middle item if it's in range
            const x = coords[2 * m];
            const y = coords[2 * m + 1];
            if (x >= minX && x <= maxX && y >= minY && y <= maxY)
                result.push(ids[m]);
            // queue search in halves that intersect the query
            if (axis === 0 ? minX <= x : minY <= y) {
                stack.push(left);
                stack.push(m - 1);
                stack.push(1 - axis);
            }
            if (axis === 0 ? maxX >= x : maxY >= y) {
                stack.push(m + 1);
                stack.push(right);
                stack.push(1 - axis);
            }
        }
        return result;
    }
    /**
     * Search the index for items within a given radius.
     * @param {number} qx
     * @param {number} qy
     * @param {number} r Query radius.
     * @returns {number[]} An array of indices correponding to the found items.
     */
    within(qx, qy, r) {
        if (!this._finished)
            throw new Error('Data not yet indexed - call index.finish().');
        const {ids, coords, nodeSize} = this;
        const stack = [
            0,
            ids.length - 1,
            0
        ];
        const result = [];
        const r2 = r * r;
        // recursively search for items within radius in the kd-sorted arrays
        while (stack.length) {
            const axis = stack.pop() || 0;
            const right = stack.pop() || 0;
            const left = stack.pop() || 0;
            // if we reached "tree node", search linearly
            if (right - left <= nodeSize) {
                for (let i = left; i <= right; i++) {
                    if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2)
                        result.push(ids[i]);
                }
                continue;
            }
            // otherwise find the middle index
            const m = left + right >> 1;
            // include the middle item if it's in range
            const x = coords[2 * m];
            const y = coords[2 * m + 1];
            if (sqDist(x, y, qx, qy) <= r2)
                result.push(ids[m]);
            // queue search in halves that intersect the query
            if (axis === 0 ? qx - r <= x : qy - r <= y) {
                stack.push(left);
                stack.push(m - 1);
                stack.push(1 - axis);
            }
            if (axis === 0 ? qx + r >= x : qy + r >= y) {
                stack.push(m + 1);
                stack.push(right);
                stack.push(1 - axis);
            }
        }
        return result;
    }
}
/**
 * @param {Uint16Array | Uint32Array} ids
 * @param {InstanceType<TypedArrayConstructor>} coords
 * @param {number} nodeSize
 * @param {number} left
 * @param {number} right
 * @param {number} axis
 */
function sort(ids, coords, nodeSize, left, right, axis) {
    if (right - left <= nodeSize)
        return;
    const m = left + right >> 1;
    // middle index
    // sort ids and coords around the middle index so that the halves lie
    // either left/right or top/bottom correspondingly (taking turns)
    select(ids, coords, m, left, right, axis);
    // recursively kd-sort first half and second half on the opposite axis
    sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
    sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
}
/**
 * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
 * [left..k-1] items are smaller than k-th item (on either x or y axis)
 * @param {Uint16Array | Uint32Array} ids
 * @param {InstanceType<TypedArrayConstructor>} coords
 * @param {number} k
 * @param {number} left
 * @param {number} right
 * @param {number} axis
 */
function select(ids, coords, k, left, right, axis) {
    while (right > left) {
        if (right - left > 600) {
            const n = right - left + 1;
            const m = k - left + 1;
            const z = Math.log(n);
            const s = 0.5 * Math.exp(2 * z / 3);
            const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
            const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
            const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
            select(ids, coords, k, newLeft, newRight, axis);
        }
        const t = coords[2 * k + axis];
        let i = left;
        let j = right;
        swapItem(ids, coords, left, k);
        if (coords[2 * right + axis] > t)
            swapItem(ids, coords, left, right);
        while (i < j) {
            swapItem(ids, coords, i, j);
            i++;
            j--;
            while (coords[2 * i + axis] < t)
                i++;
            while (coords[2 * j + axis] > t)
                j--;
        }
        if (coords[2 * left + axis] === t)
            swapItem(ids, coords, left, j);
        else {
            j++;
            swapItem(ids, coords, j, right);
        }
        if (j <= k)
            left = j + 1;
        if (k <= j)
            right = j - 1;
    }
}
/**
 * @param {Uint16Array | Uint32Array} ids
 * @param {InstanceType<TypedArrayConstructor>} coords
 * @param {number} i
 * @param {number} j
 */
function swapItem(ids, coords, i, j) {
    swap(ids, i, j);
    swap(coords, 2 * i, 2 * j);
    swap(coords, 2 * i + 1, 2 * j + 1);
}
/**
 * @param {InstanceType<TypedArrayConstructor>} arr
 * @param {number} i
 * @param {number} j
 */
function swap(arr, i, j) {
    const tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
/**
 * @param {number} ax
 * @param {number} ay
 * @param {number} bx
 * @param {number} by
 */
function sqDist(ax, ay, bx, by) {
    const dx = ax - bx;
    const dy = ay - by;
    return dx * dx + dy * dy;
}

//      
/*
    The CrossTileSymbolIndex generally works on the assumption that
    a conceptual "unique symbol" can be identified by the text of
    the label combined with the anchor point. The goal is to assign
    these conceptual "unique symbols" a shared crossTileID that can be
    used by Placement to keep fading opacity states consistent and to
    deduplicate labels.

    The CrossTileSymbolIndex indexes all the current symbol instances and
    their crossTileIDs. When a symbol bucket gets added or updated, the
    index assigns a crossTileID to each of it's symbol instances by either
    matching it with an existing id or assigning a new one.
*/
// Round anchor positions to roughly 4 pixel grid
const roundingFactor = 512 / EXTENT / 2;
class TileLayerIndex {
    constructor(tileID, symbolInstances, bucketInstanceId) {
        this.tileID = tileID;
        this.bucketInstanceId = bucketInstanceId;
        // create a spatial index for deduplicating symbol instances;
        // use a low nodeSize because we're optimizing for search performance, not indexing
        this.index = new KDBush(symbolInstances.length, 16, Int32Array);
        this.keys = [];
        this.crossTileIDs = [];
        const tx = tileID.canonical.x * EXTENT;
        const ty = tileID.canonical.y * EXTENT;
        for (let i = 0; i < symbolInstances.length; i++) {
            const {key, crossTileID, tileAnchorX, tileAnchorY} = symbolInstances.get(i);
            // Converts the coordinates of the input symbol instance into coordinates that be can compared
            // against other symbols in this index. Coordinates are:
            // (1) world-based (so after conversion the source tile is irrelevant)
            // (2) converted to the z-scale of this TileLayerIndex
            // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be
            //     more tolerant of small differences between tiles.
            const x = Math.floor((tx + tileAnchorX) * roundingFactor);
            const y = Math.floor((ty + tileAnchorY) * roundingFactor);
            this.index.add(x, y);
            this.keys.push(key);
            this.crossTileIDs.push(crossTileID);
        }
        this.index.finish();
    }
    findMatches(symbolInstances, newTileID, zoomCrossTileIDs) {
        const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z);
        const scale = roundingFactor / Math.pow(2, newTileID.canonical.z - this.tileID.canonical.z);
        const tx = newTileID.canonical.x * EXTENT;
        const ty = newTileID.canonical.y * EXTENT;
        for (let i = 0; i < symbolInstances.length; i++) {
            const symbolInstance = symbolInstances.get(i);
            if (symbolInstance.crossTileID) {
                // already has a match, skip
                continue;
            }
            const {key, tileAnchorX, tileAnchorY} = symbolInstance;
            const x = Math.floor((tx + tileAnchorX) * scale);
            const y = Math.floor((ty + tileAnchorY) * scale);
            // Return any symbol with the same keys whose coordinates are within 1
            // grid unit. (with a 4px grid, this covers a 12px by 12px area)
            const matchedIds = this.index.range(x - tolerance, y - tolerance, x + tolerance, y + tolerance);
            for (const id of matchedIds) {
                const crossTileID = this.crossTileIDs[id];
                if (this.keys[id] === key && !zoomCrossTileIDs.has(crossTileID)) {
                    // Once we've marked ourselves duplicate against this parent symbol,
                    // don't let any other symbols at the same zoom level duplicate against
                    // the same parent (see issue #5993)
                    zoomCrossTileIDs.add(crossTileID);
                    symbolInstance.crossTileID = crossTileID;
                    break;
                }
            }
        }
    }
}
class CrossTileIDs {
    constructor() {
        this.maxCrossTileID = 0;
    }
    generate() {
        return ++this.maxCrossTileID;
    }
}
class CrossTileSymbolLayerIndex {
    constructor() {
        this.indexes = {};
        this.usedCrossTileIDs = {};
        this.lng = 0;
    }
    /*
     * Sometimes when a user pans across the antimeridian the longitude value gets wrapped.
     * To prevent labels from flashing out and in we adjust the tileID values in the indexes
     * so that they match the new wrapped version of the map.
     */
    handleWrapJump(lng) {
        const wrapDelta = Math.round((lng - this.lng) / 360);
        if (wrapDelta !== 0) {
            for (const zoom in this.indexes) {
                const zoomIndexes = this.indexes[zoom];
                const newZoomIndex = {};
                for (const key in zoomIndexes) {
                    // change the tileID's wrap and add it to a new index
                    const index = zoomIndexes[key];
                    index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta);
                    newZoomIndex[index.tileID.key] = index;
                }
                this.indexes[zoom] = newZoomIndex;
            }
        }
        this.lng = lng;
    }
    addBucket(tileID, bucket, crossTileIDs) {
        if (this.indexes[tileID.overscaledZ] && this.indexes[tileID.overscaledZ][tileID.key]) {
            if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === bucket.bucketInstanceId) {
                return false;
            } else {
                // We're replacing this bucket with an updated version
                // Remove the old bucket's "used crossTileIDs" now so that
                // the new bucket can claim them.
                // The old index entries themselves stick around until
                // 'removeStaleBuckets' is called.
                this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]);
            }
        }
        for (let i = 0; i < bucket.symbolInstances.length; i++) {
            const symbolInstance = bucket.symbolInstances.get(i);
            symbolInstance.crossTileID = 0;
        }
        if (!this.usedCrossTileIDs[tileID.overscaledZ]) {
            this.usedCrossTileIDs[tileID.overscaledZ] = new Set();
        }
        const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ];
        for (const zoom in this.indexes) {
            const zoomIndexes = this.indexes[zoom];
            if (Number(zoom) > tileID.overscaledZ) {
                for (const id in zoomIndexes) {
                    const childIndex = zoomIndexes[id];
                    if (childIndex.tileID.isChildOf(tileID)) {
                        childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);
                    }
                }
            } else {
                const parentCoord = tileID.scaledTo(Number(zoom));
                const parentIndex = zoomIndexes[parentCoord.key];
                if (parentIndex) {
                    parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);
                }
            }
        }
        for (let i = 0; i < bucket.symbolInstances.length; i++) {
            const symbolInstance = bucket.symbolInstances.get(i);
            if (!symbolInstance.crossTileID) {
                // symbol did not match any known symbol, assign a new id
                symbolInstance.crossTileID = crossTileIDs.generate();
                zoomCrossTileIDs.add(symbolInstance.crossTileID);
            }
        }
        if (this.indexes[tileID.overscaledZ] === undefined) {
            this.indexes[tileID.overscaledZ] = {};
        }
        this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId);
        return true;
    }
    removeBucketCrossTileIDs(zoom, removedBucket) {
        for (const crossTileID of removedBucket.crossTileIDs) {
            this.usedCrossTileIDs[zoom].delete(crossTileID);
        }
    }
    removeStaleBuckets(currentIDs) {
        let tilesChanged = false;
        for (const z in this.indexes) {
            const zoomIndexes = this.indexes[z];
            for (const tileKey in zoomIndexes) {
                if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) {
                    this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]);
                    delete zoomIndexes[tileKey];
                    tilesChanged = true;
                }
            }
        }
        return tilesChanged;
    }
}
class CrossTileSymbolIndex {
    constructor() {
        this.layerIndexes = {};
        this.crossTileIDs = new CrossTileIDs();
        this.maxBucketInstanceId = 0;
        this.bucketsInCurrentPlacement = {};
    }
    addLayer(styleLayer, tiles, lng, projection) {
        let layerIndex = this.layerIndexes[styleLayer.fqid];
        if (layerIndex === undefined) {
            layerIndex = this.layerIndexes[styleLayer.fqid] = new CrossTileSymbolLayerIndex();
        }
        let symbolBucketsChanged = false;
        const currentBucketIDs = {};
        if (projection.name !== 'globe') {
            layerIndex.handleWrapJump(lng);
        }
        for (const tile of tiles) {
            const symbolBucket = tile.getBucket(styleLayer);
            if (!symbolBucket || styleLayer.fqid !== symbolBucket.layerIds[0])
                continue;
            if (!symbolBucket.bucketInstanceId) {
                symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId;
            }
            if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) {
                symbolBucketsChanged = true;
            }
            currentBucketIDs[symbolBucket.bucketInstanceId] = true;
        }
        if (layerIndex.removeStaleBuckets(currentBucketIDs)) {
            symbolBucketsChanged = true;
        }
        return symbolBucketsChanged;
    }
    pruneUnusedLayers(usedLayers) {
        const usedLayerMap = {};
        usedLayers.forEach(usedLayer => {
            usedLayerMap[usedLayer] = true;
        });
        for (const layerId in this.layerIndexes) {
            if (!usedLayerMap[layerId]) {
                delete this.layerIndexes[layerId];
            }
        }
    }
}

var preludeCommon = "\n#define EPSILON 0.0000001\n#define PI 3.141592653589793\n#define EXTENT 8192.0\n#define HALF_PI PI/2.0\n#define QUARTER_PI PI/4.0\n#define RAD_TO_DEG 180.0/PI\n#define DEG_TO_RAD PI/180.0\n#define GLOBE_RADIUS EXTENT/PI/2.0\nvec3 linearTosRGB(vec3 color)\n{return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn)\n{return pow(srgbIn,vec3(2.2));}vec3 linearProduct(vec3 srgbIn,vec3 k)\n{return srgbIn*pow(k,vec3(1./2.2));}\n#if __VERSION__ >=300\n#define _HANDLE_WIREFRAME_DEPTH gl_FragDepth=gl_FragCoord.z-0.0001;\n#else\n#define _HANDLE_WIREFRAME_DEPTH\n#endif\n#ifdef DEBUG_WIREFRAME\n#define HANDLE_WIREFRAME_DEBUG \\\ngl_FragColor=vec4(0.7,0.0,0.0,0.7); \\\n_HANDLE_WIREFRAME_DEPTH;\n#else\n#define HANDLE_WIREFRAME_DEBUG\n#endif\n#ifdef RENDER_CUTOFF\nfloat cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w-0.0001;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);}\n#endif";

var preludeFrag = "\n#if __VERSION__ >=300\n#define varying in\n#define gl_FragColor glFragColor\n#define texture2D texture\n#define textureCube texture\nout vec4 glFragColor;\n#endif\nhighp vec3 hash(highp vec2 p) {highp vec3 p3=fract(p.xyx*vec3(443.8975,397.2973,491.1871));p3+=dot(p3,p3.yxz+19.19);return fract((p3.xxy+p3.yzz)*p3.zyx);}vec3 dither(vec3 color,highp vec2 seed) {vec3 rnd=hash(seed)+hash(seed+0.59374)-0.5;return color+rnd/255.0;}highp float unpack_depth(highp vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\n#ifdef INDICATOR_CUTOUT\nuniform vec2 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params;\n#endif\nvec4 applyCutout(vec4 color) {\n#ifdef INDICATOR_CUTOUT\nfloat holeMinOpacity=u_indicator_cutout_params.x;float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0);\n#else\nreturn color;\n#endif\n}\n#ifdef RENDER_CUTOFF\nuniform highp vec4 u_cutoff_params;varying float v_cutoff_opacity;\n#endif";

var preludeVert = "\n#if __VERSION__ >=300\n#define attribute in\n#define varying out\n#define texture2D texture\n#endif\nfloat wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;}\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) {\n#ifndef PROJECTED_POS_ON_VIEWPORT\nfloat tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz;\n#else\nreturn vec3(0.0);\n#endif\n}vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);}\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(\nunpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef RENDER_CUTOFF\nuniform vec4 u_cutoff_params;varying float v_cutoff_opacity;\n#endif\nconst vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);//Normalized device coordinate that is not rendered.";

var backgroundFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform vec4 u_color;uniform float u_opacity;\n#ifdef LIGHTING_3D_MODE\nvarying vec4 v_color;\n#endif\nvoid main() {vec4 out_color;\n#ifdef LIGHTING_3D_MODE\nout_color=v_color;\n#else\nout_color=u_color;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\ngl_FragColor=out_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var backgroundVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_lighting.glsl\"\nattribute vec2 a_pos;uniform mat4 u_matrix;\n#ifdef LIGHTING_3D_MODE\nuniform mediump vec4 u_color;varying vec4 v_color;uniform float u_emissive_strength;\n#endif\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0,1);\n#ifdef LIGHTING_3D_MODE\nv_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var backgroundPatternFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;varying vec2 v_pos;void main() {vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=texture2D(u_image,pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\ngl_FragColor=out_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var backgroundPatternVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_tile_units_to_pixels,a_pos);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var circleFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nvarying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nuniform float u_emissive_strength;void main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(\nantialiased_blur,0.0,extrude_length-radius/(radius+stroke_width)\n);vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_apply_premultiplied(out_color,v_fog_pos);\n#endif\ngl_FragColor=out_color*(v_visibility*opacity_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";

var circleVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\n#define NUM_VISIBILITY_RINGS 2\n#define INV_SQRT2 0.70710678\n#define ELEVATION_BIAS 0.0001\n#define NUM_SAMPLES_PER_RING 16\nuniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_pos_3;attribute vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\nvarying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1,-1),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1,-1),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1,1),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1,1),radius,stroke_width,view_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) {\n#if defined(TERRAIN)\nreturn elevation(pos)+ELEVATION_BIAS;\n#else\nreturn 0.0;\n#endif\n}vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_scale);\n#ifdef PITCH_WITH_MAP\n#ifdef PROJECTION_GLOBE_VIEW\nreturn u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) );\n#else\nreturn u_matrix*( world_center+vec4(sample_offset,0,0) );\n#endif\n#else\nreturn projected_center+vec4(sample_offset,0,0);\n#endif\n}float get_sample_step() {\n#ifdef PITCH_WITH_MAP\nreturn 2.0*PI/float(NUM_SAMPLES_PER_RING);\n#else\nreturn PI/float(NUM_SAMPLES_PER_RING);\n#endif\n}void main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);vec4 world_center;mat3 surface_vectors;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=a_pos_normal_3/16384.0;surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*circle_elevation(circle_center);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*circle_elevation(circle_center);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1);\n#else \nsurface_vectors=mat3(1.0);float height=circle_elevation(circle_center);world_center=vec4(circle_center,height,1);\n#endif\nvec4 projected_center=u_matrix*world_center;float view_scale=0.0;\n#ifdef PITCH_WITH_MAP\n#ifdef SCALE_WITH_MAP\nview_scale=1.0;\n#else\nview_scale=projected_center.w/u_camera_to_center_distance;\n#endif\n#else\n#ifdef SCALE_WITH_MAP\nview_scale=u_camera_to_center_distance;\n#else\nview_scale=projected_center.w;\n#endif\n#endif\ngl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,view_scale,surface_vectors);float visibility=0.0;\n#ifdef TERRAIN\nfloat step=get_sample_step();vec4 occlusion_world_center;vec4 occlusion_projected_center;\n#ifdef PITCH_WITH_MAP\nfloat cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,view_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center;\n#else\nocclusion_world_center=world_center;occlusion_projected_center=projected_center;\n#endif\nfor(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float scale=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*scale;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,view_scale,surface_vectors);visibility+=float(!isOccluded(frag_pos));}}visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_SAMPLES_PER_RING);\n#else\nvisibility=1.0;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nvisibility=1.0;\n#endif\nv_visibility=visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);\n#ifdef FOG\nv_fog_pos=fog_position(world_center.xyz);\n#endif\n}";

var clippingMaskFrag = "void main() {gl_FragColor=vec4(1.0);}";

var clippingMaskVert = "attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";

var heatmapFrag = "#include \"_prelude_fog.fragment.glsl\"\nuniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef FOG\nif (u_is_globe==0) {gl_FragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var heatmapVert = "#include \"_prelude_terrain.vertex.glsl\"\n#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_pos_3;attribute vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\nvarying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(a_pos*0.5);vec3 pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=a_pos_normal_3/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#else\npos=vec3(tilePos+extrude,elevation(tilePos));\n#endif\ngl_Position=u_matrix*vec4(pos,1);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}";

var heatmapTextureFrag = "uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var heatmapTextureVert = "attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=a_pos*0.5+0.5;}";

var collisionBoxFrag = "varying float v_placed;varying float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);gl_FragColor =mix(red,blue,step(0.5,v_placed))*0.5;gl_FragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}";

var collisionBoxVert = "#include \"_prelude_terrain.vertex.glsl\"\nattribute vec3 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;attribute float a_size_scale;attribute vec2 a_padding;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_pos+elevationVector(a_anchor_pos)*elevation(a_anchor_pos),1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(a_extrude*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}";

var collisionCircleFrag = "varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}";

var collisionCircleVert = "attribute vec2 a_pos_2f;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd  =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz  /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos_2f;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(\nmix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}";

var debugFrag = "uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}";

var debugVert = "#include \"_prelude_terrain.vertex.glsl\"\nattribute vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_pos_3;\n#endif\nvarying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {float h=elevation(a_pos);v_uv=a_pos/8192.0;\n#ifdef PROJECTION_GLOBE_VIEW\ngl_Position=u_matrix*vec4(a_pos_3+elevationVector(a_pos)*h,1);\n#else\ngl_Position=u_matrix*vec4(a_pos*u_overlay_scale,h,1);\n#endif\n}";

var fillFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nuniform float u_emissive_strength;void main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nvec4 out_color=color;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\ngl_FragColor=out_color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillVert = "#include \"_prelude_fog.vertex.glsl\"\nattribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var fillOutlineFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nvarying vec2 v_pos;uniform float u_emissive_strength;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\ngl_FragColor=out_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillOutlineVert = "#include \"_prelude_fog.vertex.glsl\"\nattribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var fillOutlinePatternFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_emissive_strength;varying vec2 v_pos;varying vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=texture2D(u_image,pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\ngl_FragColor=out_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillOutlinePatternVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos;varying vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\n#pragma mapbox: define lowp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos);v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var fillPatternFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform vec2 u_texsize;uniform sampler2D u_image;varying vec2 v_pos;uniform float u_emissive_strength;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);vec4 out_color=texture2D(u_image,pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\ngl_FragColor=out_color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillPatternVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\n#pragma mapbox: define lowp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var fillExtrusionFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nvarying vec4 v_color;\n#ifdef RENDER_SHADOWS\nvarying highp vec4 v_pos_light_view_0;varying highp vec4 v_pos_light_view_1;varying float v_depth;\n#endif\nuniform lowp float u_opacity;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;varying vec2 v_ao;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nvarying vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nvarying highp vec3 v_normal;\n#endif\nuniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor;\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nvarying float v_flood_radius;varying float v_has_floodlight;\n#endif\nvarying float v_height;void main() {\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nvec3 normal=normalize(v_normal);\n#endif\nfloat z;vec4 color=v_color;\n#ifdef ZERO_ROOF_RADIUS\nz=float(normal.z > 0.00001);\n#ifdef LIGHTING_3D_MODE\nnormal=mix(normal,vec3(0.0,0.0,1.0),z);\n#else\ncolor=mix(v_color,v_roof_color,z);\n#endif\n#endif\nfloat h=max(0.0,v_height);float ao_shade=1.0;\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;\n#ifdef ZERO_ROOF_RADIUS\nconcave*=(1.0-z);\n#endif\nfloat x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave);\n#ifdef LIGHTING_3D_MODE\n#ifdef FLOOD_LIGHT\ncolor.rgb*=mix(ao_shade,1.0,v_has_floodlight);\n#else\ncolor.rgb*=ao_shade;\n#endif\n#else\ncolor.rgb*=ao_shade;\n#endif\n#endif\n#ifdef LIGHTING_3D_MODE\nfloat flood_radiance=0.0;\n#ifdef FLOOD_LIGHT\nflood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight;\n#endif\n#ifdef RENDER_SHADOWS\n#ifdef FLOOD_LIGHT\nfloat ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,v_depth);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance);\n#else\nfloat shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor);\n#endif\n#else\ncolor.rgb=apply_lighting(color.rgb,normal);\n#ifdef FLOOD_LIGHT\ncolor.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance);\n#endif\n#endif\ncolor*=u_opacity;\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h));\n#endif\n#ifdef RENDER_CUTOFF\ncolor*=v_cutoff_opacity;\n#endif\n#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color);\n#endif\ngl_FragColor=color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillExtrusionVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\n#include \"_prelude_lighting.glsl\"\n#if __VERSION__ >=300\n#ifdef RENDER_CUTOFF\ninvariant gl_Position;\n#endif\n#endif\nuniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;attribute vec4 a_pos_normal_ed;attribute vec2 a_centroid_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_pos_3;attribute vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\nuniform highp float u_vertical_scale;varying vec4 v_color;\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;varying highp vec4 v_pos_light_view_0;varying highp vec4 v_pos_light_view_1;varying float v_depth;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nvarying vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nvarying highp vec3 v_normal;\n#endif\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;varying vec2 v_ao;\n#endif\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nvarying float v_flood_radius;varying float v_has_floodlight;\n#endif\nvarying float v_height;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define highp float flood_light_wall_radius\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize highp float flood_light_wall_radius\nbase*=u_vertical_scale;height*=u_vertical_scale;vec4 pos_nx=floor(a_pos_normal_ed*0.5);vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nv_normal=normal;\n#endif\nbase=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=a_centroid_pos;\n#endif\nfloat ele=0.0;float h=0.0;float c_ele;vec3 pos;\n#ifdef TERRAIN\nbool flat_roof=centroid_pos.x !=0.0 && t > 0.0;ele=elevation(pos_nx.xy);c_ele=flat_roof ? centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos) : ele;h=flat_roof ? max(c_ele+height,ele+base+2.0) : ele+(t > 0.0 ? height : base==0.0 ?-5.0 : base);pos=vec3(pos_nx.xy,h);\n#else\nh=t > 0.0 ? height : base;pos=vec3(pos_nx.xy,h);\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\nfloat hidden=float(centroid_pos.x==0.0 && centroid_pos.y==1.0);gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);h=h-ele;v_height=h;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=pos;vec3 shd_pos1=pos;\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\nfloat NdotL=0.0;float colorvalue=0.0;\n#ifndef LIGHTING_3D_MODE\ncolorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=(\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\n#endif\n#ifdef FAUX_AO\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\n#ifdef TERRAIN\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\n#endif\nv_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\ngl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\n#endif\n#ifdef LIGHTING_3D_MODE\n#ifdef FLOOD_LIGHT\nfloat is_wall=1.0-float(t > 0.0 && top_up_ny.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale;\n#endif\nv_color=vec4(color.rgb,1.0);\n#else\nv_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nfloat roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n#ifdef RENDER_CUTOFF\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\n#endif\n}";

var fillExtrusionPatternFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;varying vec3 v_ao;\n#endif\n#ifdef LIGHTING_3D_MODE\nvarying vec3 v_normal;\n#endif\nvarying vec2 v_pos;varying vec4 v_lighting;uniform lowp float u_opacity;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define mediump vec4 pattern\n#pragma mapbox: define highp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize highp float pixel_ratio\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);vec4 out_color=texture2D(u_image,pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting(out_color,normalize(v_normal))*u_opacity;\n#else\nout_color=out_color*v_lighting;\n#endif\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color);\n#endif\ngl_FragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillExtrusionPatternVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec4 a_pos_normal_ed;attribute vec2 a_centroid_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_pos_3;attribute vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\nvarying vec2 v_pos;varying vec4 v_lighting;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;varying vec3 v_ao;\n#endif\n#ifdef LIGHTING_3D_MODE\nvarying vec3 v_normal;\n#endif\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define mediump vec4 pattern\n#pragma mapbox: define highp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize highp float pixel_ratio\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec4 pos_nx=floor(a_pos_normal_ed*0.5);mediump vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;mediump vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=a_pos_normal_ed.w;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=a_centroid_pos;\n#endif\nfloat ele=0.0;float h=z;vec3 p;float c_ele;\n#ifdef TERRAIN\nbool flat_roof=centroid_pos.x !=0.0 && t > 0.0;ele=elevation(pos_nx.xy);c_ele=flat_roof ? centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos) : ele;h=flat_roof ? max(c_ele+height,ele+base+2.0) : ele+(t > 0.0 ? height : base==0.0 ?-5.0 : base);p=vec3(pos_nx.xy,h);\n#else\np=vec3(pos_nx.xy,z);\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\nfloat hidden=float(centroid_pos.x==0.0 && centroid_pos.y==1.0);gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0\n? pos_nx.xy\n: vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0;\n#ifdef LIGHTING_3D_MODE\nNdotL=calculate_NdotL(normal);\n#else\nNdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL);\n#endif\nif (normal.y !=0.0) {float r=0.84;\n#ifndef LIGHTING_3D_MODE\nr=mix(0.7,0.98,1.0-u_lightintensity);\n#endif\nNdotL*=(\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\n#ifdef FAUX_AO\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\n#ifdef TERRAIN\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\n#endif\nv_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\ngl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\n#endif\n#ifdef LIGHTING_3D_MODE\nv_normal=normal;\n#else\nv_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;\n#endif \n#ifdef FOG\nv_fog_pos=fog_position(p);\n#endif\n}";

var hillshadePrepareFrag = "#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nreturn texture(u_image,coord).r/4.0;\n#else\nvec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;\n#endif\n}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2(\n(c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c)\n)/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(\nderiv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}";

var fillExtrusionGroundEffectFrag = "uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size;\n#ifdef SDF_SUBPASS\nvarying highp vec2 v_pos;varying highp vec4 v_line_segment;varying highp float v_flood_light_radius_tile;varying highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);}\n#ifdef FOG\nvarying highp float v_fog;\n#endif\n#endif\nvoid main() {\n#ifdef CLEAR_SUBPASS\nvec4 color=vec4(1.0);\n#ifdef CLEAR_FROM_TEXTURE\ncolor=texture2D(u_fb,gl_FragCoord.xy/vec2(u_fb_size));\n#endif\ngl_FragColor=color;\n#else\n#ifdef SDF_SUBPASS\nhighp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0;\n#ifdef FOG\nfog=v_fog;\n#endif\n#ifdef RENDER_CUTOFF\nfog*=v_cutoff_opacity;\n#endif\ngl_FragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog));\n#else\nvec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass);\n#ifdef OVERDRAW_INSPECTOR\ncolor=vec4(1.0);\n#endif\ngl_FragColor=color;HANDLE_WIREFRAME_DEBUG;\n#endif\n#endif\n}";

var fillExtrusionGroundEffectVert = "#include \"_prelude_fog.vertex.glsl\"\nattribute highp vec4 a_pos_end;attribute highp float a_angular_offset_factor;attribute highp float a_hidden_by_landmark;\n#ifdef SDF_SUBPASS\nvarying highp vec2 v_pos;varying highp vec4 v_line_segment;varying highp float v_flood_light_radius_tile;varying highp vec2 v_ao;\n#ifdef FOG\nvarying highp float v_fog;\n#endif\n#endif\nuniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp vec2 u_ao;\n#pragma mapbox: define highp float flood_light_ground_radius\nconst float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() {\n#pragma mapbox: initialize highp float flood_light_ground_radius\nvec2 p=a_pos_end.xy;vec2 q=floor(a_pos_end.zw*0.5);vec2 start_bottom=a_pos_end.zw-q*2.0;float fl_ground_radius=flood_light_ground_radius;\n#ifdef FORCE_ABS_FL_GROUND_RADIUS\nfl_ground_radius=abs(flood_light_ground_radius);\n#endif\nfloat flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=a_angular_offset_factor/NORM*TANGENT_CUTOFF;float angular_offset=angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(1.0,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp;\n#ifdef SDF_SUBPASS\nv_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius);\n#ifdef FOG\nv_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos);\n#endif\n#endif\nfloat hidden_by_landmark=0.0;\n#ifdef HAS_CENTROID\nhidden_by_landmark=a_hidden_by_landmark;\n#endif\nfloat isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0));\n#ifdef RENDER_CUTOFF\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\n#endif\n}";

var hillshadePrepareVert = "uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}";

var hillshadeFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef LIGHTING_3D_MODE\ngl_FragColor=apply_lighting_with_emission_ground(gl_FragColor,u_emissive_strength);\n#endif\n#ifdef FOG\ngl_FragColor=fog_dither(fog_apply_premultiplied(gl_FragColor,v_fog_pos));\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var hillshadeVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}";

var lineFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform lowp float u_device_pixel_ratio;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec4 v_uv;\n#ifdef RENDER_LINE_DASH\nuniform sampler2D u_dash_image;varying vec2 v_tex;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform sampler2D u_gradient_image;\n#endif\nfloat luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;}uniform float u_emissive_strength;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 dash\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float border_width\n#pragma mapbox: define lowp vec4 border_color\nfloat linearstep(float edge0,float edge1,float x) {return  clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize lowp vec4 dash\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float border_width\n#pragma mapbox: initialize lowp vec4 border_color\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);\n#ifdef RENDER_LINE_DASH\nfloat sdfdist=texture2D(u_dash_image,v_tex).a;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/dash.z;alpha*=linearstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);\n#endif\nhighp vec4 out_color;\n#ifdef RENDER_LINE_GRADIENT\nout_color=texture2D(u_gradient_image,v_uv.xy);\n#else\nout_color=color;\n#endif\nfloat trimmed=1.0;\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float start=v_uv[2];highp float end=v_uv[3];highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=(start+(v_uv.x)*(end-start));if (trim_end > trim_start) {if (line_progress <=trim_end && line_progress >=trim_start) {out_color=vec4(0,0,0,0);trimmed=0.0;}}\n#endif\nif (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}}\n#ifdef RENDER_LINE_BORDER\nfloat edgeBlur=(border_width+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2.t-edgeBlur),v_width2.s-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {    \nfloat Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color.rgb=mix(border_color.rgb*border_color.a*trimmed,out_color.rgb,smoothAlpha);}}\n#endif\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nout_color*=(alpha*opacity);\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color);\n#endif\ngl_FragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var lineVert = "#include \"_prelude_fog.vertex.glsl\"\n#define EXTRUDE_SCALE 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nattribute highp vec4 a_packed;\n#endif\n#ifdef RENDER_LINE_DASH\nattribute float a_linesofar;\n#endif\nuniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec4 v_uv;\n#ifdef RENDER_LINE_DASH\nuniform vec2 u_texsize;uniform float u_tile_units_to_pixels;varying vec2 v_tex;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform float u_image_height;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 dash\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float border_width\n#pragma mapbox: define lowp vec4 border_color\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize lowp vec4 dash\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float border_width\n#pragma mapbox: initialize lowp vec4 border_color\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist*u_pixels_to_tile_units,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude;\n#ifndef RENDER_TO_TEXTURE\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#else\nv_gamma_scale=1.0;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nfloat a_uv_x=a_packed[0];float a_split_index=a_packed[1];highp float a_clip_start=a_packed[2];highp float a_clip_end=a_packed[3];\n#ifdef RENDER_LINE_GRADIENT\nhighp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec4(a_uv_x,a_split_index*texel_height-half_texel_height,a_clip_start,a_clip_end);\n#else\nv_uv=vec4(a_uv_x,0.0,a_clip_start,a_clip_end);\n#endif\n#endif\n#ifdef RENDER_LINE_DASH\nfloat scale=dash.z==0.0 ? 0.0 : u_tile_units_to_pixels/dash.z;float height=dash.y;v_tex=vec2(a_linesofar*scale/floorwidth,(-normal.y*height+dash.x+0.5)/u_texsize.y);\n#endif\nv_width2=vec2(outset,inset);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}";

var linePatternFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern\n#pragma mapbox: define lowp float pixel_ratio\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;vec2 pattern_size=vec2(display_size.x/u_tile_units_to_pixels,display_size.y);float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x=mod(v_linesofar/pattern_size.x*aspect,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));vec4 color=texture2D(u_image,pos);\n#ifdef LIGHTING_3D_MODE\ncolor=apply_lighting_ground(color);\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ncolor*=(alpha*opacity);\n#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color);\n#endif\ngl_FragColor=color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var linePatternVert = "#include \"_prelude_fog.vertex.glsl\"\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_linesofar;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern\n#pragma mapbox: define lowp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist*u_pixels_to_tile_units,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude;\n#ifndef RENDER_TO_TEXTURE\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#else\nv_gamma_scale=1.0;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}";

var rasterFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;\n#ifdef RASTER_COLOR\nuniform sampler2D u_color_ramp;uniform highp vec2 u_colorization_scale;uniform highp vec4 u_colorization_mix;highp vec4 colormap (highp float value) {highp float scaled_value=value*u_colorization_scale.y+u_colorization_scale.x;highp vec2 coords=vec2(scaled_value,0.5);return texture2D(u_color_ramp,coords);}\n#endif\nvoid main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);vec4 color;\n#ifdef RASTER_COLOR\nhighp vec4 fadedColor=mix(color0,color1,u_fade_t);color=colormap(dot(vec4(fadedColor.rgb,1),u_colorization_mix));color.a*=fadedColor.a;if (color.a > 0.0) {color.rgb/=color.a;}\n#else\nif (color0.a > 0.0) {color0.rgb/=color0.a;}if (color1.a > 0.0) {color1.rgb/=color1.a;}color=mix(color0,color1,u_fade_t);\n#endif\ncolor.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(\ndot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_ground(out_color);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply(out_color,v_fog_pos));\n#endif\ngl_FragColor=vec4(out_color*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var rasterVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_globe_pos;attribute vec2 a_uv;\n#else\nattribute vec2 a_pos;attribute vec2 a_texture_pos;\n#endif\nvarying vec2 v_pos0;varying vec2 v_pos1;void main() {vec2 uv;\n#ifdef PROJECTION_GLOBE_VIEW\ngl_Position=u_matrix*u_globe_matrix*vec4(a_globe_pos,1.0);uv=a_uv;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz);\n#endif\n#else\nfloat w=1.0+dot(a_texture_pos,u_perspective_transform);gl_Position=u_matrix*vec4(a_pos*w,0,w);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\nuv=a_texture_pos/8192.0;\n#endif\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}";

var symbolIconFrag = "#include \"_prelude_lighting.glsl\"\nuniform sampler2D u_texture;\n#ifdef ICON_TRANSITION\nuniform float u_icon_transition;\n#endif\nvarying float v_fade_opacity;varying vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nvarying vec2 v_tex_b;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float emissive_strength\nlowp float alpha=opacity*v_fade_opacity;vec4 out_color;\n#ifdef ICON_TRANSITION\nvec4 a=texture2D(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture2D(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b)*alpha;\n#else\nout_color=texture2D(u_texture,v_tex_a)*alpha;\n#endif\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#endif\ngl_FragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var symbolIconVert = "#include \"_prelude_terrain.vertex.glsl\"\nattribute vec4 a_pos_offset;attribute vec4 a_tex_size;attribute vec4 a_pixeloffset;attribute vec4 a_projected_pos;attribute float a_fade_opacity;\n#ifdef Z_OFFSET\nattribute float a_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_globe_anchor;attribute vec3 a_globe_normal;\n#endif\n#ifdef ICON_TRANSITION\nattribute vec2 a_texb;\n#endif\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform vec3 u_up_vector;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\n#endif\nvarying vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nvarying vec2 v_tex_b;\n#endif\nvarying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float emissive_strength\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_min_font_scale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=elevation(tile_anchor);\n#ifdef Z_OFFSET\ne+=a_z_offset;\n#endif\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos=mix_globe_mercator(a_globe_anchor+h,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\n#else\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjected_point;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetProjected_point=u_matrix*vec4(a_globe_anchor+displacement,1);\n#else\noffsetProjected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);\n#endif\nvec2 a=projected_point.xy/projected_point.w;vec2 b=offsetProjected_point.xy/offsetProjected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz+h,mercator_pos,u_zoom_transition);projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\n#else\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\n#endif\nhighp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0);\n#ifdef TERRAIN\n#ifdef PITCH_WITH_MAP_TERRAIN\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\n#endif\n#endif\nfloat occlusion_fade=occlusionFade(projected_point)*globe_occlusion_fade;float projection_transition_fade=1.0;\n#if defined(PROJECTED_POS_ON_VIEWPORT) && defined(PROJECTION_GLOBE_VIEW)\nprojection_transition_fade=1.0-step(EPSILON,u_zoom_transition);\n#endif\nvec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change))*projection_transition_fade;float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\n#else\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\n#endif\nv_tex_a=a_tex/u_texsize;\n#ifdef ICON_TRANSITION\nv_tex_b=a_texb/u_texsize;\n#endif\nv_fade_opacity=out_fade_opacity;}";

var symbolSDFFrag = "#include \"_prelude_lighting.glsl\"\n#define SDF_PX 8.0\nuniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;\n#if __VERSION__ >=300\nflat varying float v_draw_halo;\n#endif\nvarying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\n#pragma mapbox: initialize lowp float emissive_strength\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo;\n#if __VERSION__ >=300\ndraw_halo=v_draw_halo > 0.0;\n#else\ndraw_halo=u_is_halo;\n#endif\nif (draw_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);vec4 out_color=color*(alpha*opacity*fade_opacity);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#endif\ngl_FragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var symbolSDFVert = "#include \"_prelude_terrain.vertex.glsl\"\nattribute vec4 a_pos_offset;attribute vec4 a_tex_size;attribute vec4 a_pixeloffset;attribute vec4 a_projected_pos;attribute float a_fade_opacity;\n#ifdef Z_OFFSET\nattribute float a_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_globe_anchor;attribute vec3 a_globe_normal;\n#endif\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform bool u_is_halo;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\n#endif\n#if __VERSION__ >=300\nflat varying float v_draw_halo;\n#endif\nvarying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\n#pragma mapbox: initialize lowp float emissive_strength\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[3];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=elevation(tile_anchor);\n#ifdef Z_OFFSET\ne+=a_z_offset;\n#endif\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos=mix_globe_mercator(a_globe_anchor+h,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\n#else\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(a_globe_anchor+displacement,1);\n#else\noffsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);\n#endif\nvec2 a=projected_point.xy/projected_point.w;vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz+h,mercator_pos,u_zoom_transition);projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\n#else\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\n#endif\nhighp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset);\n#ifdef TERRAIN\n#ifdef PITCH_WITH_MAP_TERRAIN\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\n#endif\n#endif\nfloat occlusion_fade=occlusionFade(projected_point)*globe_occlusion_fade;float projection_transition_fade=1.0;\n#if defined(PROJECTED_POS_ON_VIEWPORT) && defined(PROJECTION_GLOBE_VIEW)\nprojection_transition_fade=1.0-step(EPSILON,u_zoom_transition);\n#endif\nvec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));float out_fade_opacity=interpolated_fade_opacity*projection_transition_fade;float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\n#else\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\n#endif\nfloat gamma_scale=gl_Position.w;\n#if __VERSION__ >=300\nv_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;\n#endif\nv_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,out_fade_opacity);}";

var symbolTextAndIconFrag = "#include \"_prelude_lighting.glsl\"\n#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_halo;\n#if __VERSION__ >=300\nflat varying float v_draw_halo;\n#endif\nvarying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\n#pragma mapbox: initialize lowp float emissive_strength\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo;\n#if __VERSION__ >=300\ndraw_halo=v_draw_halo > 0.0;\n#else\ndraw_halo=u_is_halo;\n#endif\nif (draw_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);vec4 out_color=color*(alpha*opacity*fade_opacity);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#endif\ngl_FragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var symbolTextAndIconVert = "#include \"_prelude_terrain.vertex.glsl\"\nattribute vec4 a_pos_offset;attribute vec4 a_tex_size;attribute vec4 a_projected_pos;attribute float a_fade_opacity;\n#ifdef Z_OFFSET\nattribute float a_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nattribute vec3 a_globe_anchor;attribute vec3 a_globe_normal;\n#endif\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\n#endif\n#if __VERSION__ >=300\nflat varying float v_draw_halo;\n#endif\nvarying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\n#pragma mapbox: initialize lowp float emissive_strength\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[3];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=elevation(tile_anchor);\n#ifdef Z_OFFSET\ne+=a_z_offset;\n#endif\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos=mix_globe_mercator(a_globe_anchor+h,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\n#else\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offset_projected_point=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projected_point.xy/projected_point.w;vec2 b=offset_projected_point.xy/offset_projected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz+h,mercator_pos,u_zoom_transition);projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\n#else\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\n#endif\nhighp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*font_scale);\n#ifdef TERRAIN\n#ifdef PITCH_WITH_MAP_TERRAIN\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\n#endif\n#endif\nfloat occlusion_fade=occlusionFade(projected_point)*globe_occlusion_fade;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));float projection_transition_fade=1.0;\n#if defined(PROJECTED_POS_ON_VIEWPORT) && defined(PROJECTION_GLOBE_VIEW)\nprojection_transition_fade=1.0-step(EPSILON,u_zoom_transition);\n#endif\nfloat out_fade_opacity=interpolated_fade_opacity*projection_transition_fade;float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\n#else\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\n#endif\nfloat gamma_scale=gl_Position.w;\n#if __VERSION__ >=300\nv_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;\n#endif\nv_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,out_fade_opacity,is_sdf);}";

var skyboxFrag = "#include \"_prelude_fog.fragment.glsl\"\nvarying lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep(\ncos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=textureCube(u_cubemap,uv).rgb;\n#ifdef FOG\nsky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color);\n#endif\nsky_color.rgb=dither(sky_color.rgb,gl_FragCoord.xy+u_temporal_offset);sky_color+=0.1*sun_disk(v_uv,u_sun_direction);gl_FragColor=vec4(sky_color*u_opacity,u_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";

var skyboxGradientFrag = "#include \"_prelude_fog.fragment.glsl\"\nvarying highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture2D(u_color_ramp,vec2(progress,0.5));\n#ifdef FOG\ncolor.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a;\n#endif\ncolor*=u_opacity;color.rgb=dither(color.rgb,gl_FragCoord.xy+u_temporal_offset);gl_FragColor=color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";

var skyboxVert = "attribute highp vec3 a_pos_3f;uniform lowp mat4 u_matrix;varying highp vec3 v_uv;void main() {const mat3 half_neg_pi_around_x=mat3(1.0,0.0, 0.0,0.0,0.0,-1.0,0.0,1.0, 0.0);v_uv=half_neg_pi_around_x*a_pos_3f;vec4 pos=u_matrix*vec4(a_pos_3f,1.0);gl_Position=pos.xyww;}";

var terrainRasterFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform sampler2D u_image0;varying vec2 v_pos0;\n#ifdef FOG\nvarying float v_fog_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nvarying vec4 v_pos_light_view_0;varying vec4 v_pos_light_view_1;varying float v_depth;\n#endif\nuniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture2D(u_image0,v_pos0);vec4 color;\n#ifdef LIGHTING_3D_MODE\nconst vec3 normal=vec3(0.0,0.0,1.0);\n#ifdef RENDER_SHADOWS\nfloat cutoffOpacity=1.0;\n#ifdef RENDER_CUTOFF\ncutoffOpacity=cutoff_opacity(u_cutoff_params,v_depth);\n#endif\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nvec3 unlit_base=image_color.rgb*(1.0-image_color.a);vec3 emissive_base=image_color.rgb*image_color.a;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,v_depth,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0;\n#else\nfloat lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity));\n#endif\n#else\nfloat lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor);\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\ncolor.rgb=mix(color.rgb,image_color.rgb,image_color.a);color.a=1.0;\n#endif\n#endif\n#else\ncolor=image_color;\n#endif\n#ifdef FOG\n#ifdef ZERO_EXAGGERATION\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#else\ncolor=fog_dither(fog_apply_from_vert(color,v_fog_opacity));\n#endif\n#endif\ngl_FragColor=color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var terrainRasterVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\nuniform mat4 u_matrix;uniform float u_skirt_height;attribute vec2 a_pos;varying vec2 v_pos0;\n#ifdef FOG\nvarying float v_fog_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;varying vec4 v_pos_light_view_0;varying vec4 v_pos_light_view_1;varying float v_depth;\n#endif\nvoid main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0);\n#ifdef FOG\n#ifdef ZERO_EXAGGERATION\nv_fog_pos=fog_position(decodedPos);\n#else\nv_fog_opacity=fog(fog_position(vec3(decodedPos,elevation)));\n#endif\n#endif\n#ifdef RENDER_SHADOWS\nvec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.);v_depth=gl_Position.w;\n#endif\n}";

var terrainDepthFrag = "#ifdef GL_ES\nprecision highp float;\n#endif\nvarying float v_depth;void main() {gl_FragColor=pack_depth(v_depth);}";

var terrainDepthVert = "#include \"_prelude_terrain.vertex.glsl\"\nuniform mat4 u_matrix;attribute vec2 a_pos;varying float v_depth;void main() {float elevation=elevation(a_pos);gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}";

var preludeTerrainVert = "\n#define ELEVATION_SCALE 7.0\n#define ELEVATION_OFFSET 450.0\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;vec3 elevationVector(vec2 pos) {vec2 uv=pos/EXTENT;vec3 up=normalize(mix(\nmix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;}\n#else\nvec3 elevationVector(vec2 pos) { return vec3(0,0,1); }\n#endif\nconst float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(vec2 posWithComposedSkirt)\n{float skirt=float(posWithComposedSkirt.x >=skirtOffset);vec2 pos=posWithComposedSkirt-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);}\n#ifdef TERRAIN\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nuniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;\n#else\nuniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;\n#endif\nuniform vec4 u_dem_unpack;uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;uniform sampler2D u_depth;uniform vec2 u_depth_size_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float decodeElevation(vec4 v) {return dot(vec4(v.xyz*255.0,-1.0),u_dem_unpack);}float currentElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=decodeElevation(texture2D(u_dem,pos));float tr=decodeElevation(texture2D(u_dem,pos+vec2(dd,0.0)));float bl=decodeElevation(texture2D(u_dem,pos+vec2(0.0,dd)));float br=decodeElevation(texture2D(u_dem,pos+vec2(dd,dd)));return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}float prevElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=decodeElevation(texture2D(u_dem_prev,pos));float tr=decodeElevation(texture2D(u_dem_prev,pos+vec2(dd,0.0)));float bl=decodeElevation(texture2D(u_dem_prev,pos+vec2(0.0,dd)));float br=decodeElevation(texture2D(u_dem_prev,pos+vec2(dd,dd)));return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}\n#ifdef TERRAIN_VERTEX_MORPHING\nfloat elevation(vec2 apos) {\n#ifdef ZERO_EXAGGERATION\nreturn 0.0;\n#endif\nfloat nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);}\n#else\nfloat elevation(vec2 apos) {\n#ifdef ZERO_EXAGGERATION\nreturn 0.0;\n#endif\nreturn currentElevation(apos);}\n#endif\nhighp float unpack_depth(highp vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;float depth=unpack_depth(texture2D(u_depth,(coord.xy+1.0)*0.5));return coord.z > depth+0.0005;}float occlusionFade(vec4 frag) {vec3 coord=frag.xyz/frag.w;vec3 df=vec3(5.0*u_depth_size_inv,0.0);vec2 uv=0.5*coord.xy+0.5;vec4 depth=vec4(\nunpack_depth(texture2D(u_depth,uv-df.xz)),unpack_depth(texture2D(u_depth,uv+df.xz)),unpack_depth(texture2D(u_depth,uv-df.zy)),unpack_depth(texture2D(u_depth,uv+df.zy))\n);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z-0.001)-depth),0.0,1.0));}vec4 fourSample(vec2 pos,vec2 off) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nfloat tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;\n#else\nvec4 demtl=vec4(texture2D(u_dem,pos).xyz*255.0,-1.0);float tl=dot(demtl,u_dem_unpack);vec4 demtr=vec4(texture2D(u_dem,pos+vec2(off.x,0.0)).xyz*255.0,-1.0);float tr=dot(demtr,u_dem_unpack);vec4 dembl=vec4(texture2D(u_dem,pos+vec2(0.0,off.y)).xyz*255.0,-1.0);float bl=dot(dembl,u_dem_unpack);vec4 dembr=vec4(texture2D(u_dem,pos+off).xyz*255.0,-1.0);float br=dot(dembr,u_dem_unpack);\n#endif\nreturn vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);}\n#else\nfloat elevation(vec2 pos) { return 0.0; }bool isOccluded(vec4 frag) { return false; }float occlusionFade(vec4 frag) { return 1.0; }\n#endif";

var preludeFogVert = "#ifdef FOG\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump mat4 u_fog_matrix;varying vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);}\n#endif";

var preludeFogFrag = "#ifdef FOG\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;varying vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=gl_FragCoord.xy/u_viewport;highp vec3 ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,opacity);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {\n#ifdef FOG_DITHERING\nvec2 dither_seed=gl_FragCoord.xy+u_fog_temporal_offset;return dither(color,dither_seed);\n#else\nreturn color;\n#endif\n}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);}\n#endif";

var preludeLighting = "\n#ifdef LIGHTING_3D_MODE\nuniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);}\n#endif//LIGHTING_3D_MODE";

var skyboxCaptureFrag = "\nvarying highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;\n#ifdef GL_ES\nprecision highp float;\n#endif\n#define BETA_R                  vec3(5.5e-6,13.0e-6,22.4e-6)\n#define BETA_M                  vec3(21e-6,21e-6,21e-6)\n#define MIE_G                   0.76\n#define DENSITY_HEIGHT_SCALE_R  8000.0\n#define DENSITY_HEIGHT_SCALE_M  1200.0\n#define PLANET_RADIUS           6360e3\n#define ATMOSPHERE_RADIUS       6420e3\n#define SAMPLE_STEPS            10\n#define DENSITY_STEPS           4\nfloat ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;gl_FragColor=vec4(color,1.0);}";

var skyboxCaptureVert = "attribute highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;varying highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=pos.xyz;v_position.y*=-1.0;v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}";

var globeFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform sampler2D u_image0;varying vec2 v_pos0;\n#ifndef FOG\nuniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport;\n#endif\nvoid main() {vec4 color;\n#ifdef CUSTOM_ANTIALIASING\nvec2 uv=gl_FragCoord.xy/u_viewport;highp vec3 ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);vec3 dir=normalize(ray_dir);vec3 closest_point=dot(u_globe_pos,dir)*dir;float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture2D(u_image0,v_pos0);\n#ifdef LIGHTING_3D_MODE\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nraster=apply_lighting_with_emission_ground(raster,raster.a);color=vec4(raster.rgb*antialias,antialias);\n#else\nraster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias);\n#endif\n#else\ncolor=vec4(raster.rgb*antialias,raster.a*antialias);\n#endif\n#else\ncolor=texture2D(u_image0,v_pos0);\n#ifdef LIGHTING_3D_MODE\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\ncolor=apply_lighting_with_emission_ground(color,color.a);color.a=1.0;\n#else\ncolor=apply_lighting_ground(color);\n#endif\n#endif\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ngl_FragColor=color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var globeVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\nuniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height;\n#ifdef GLOBE_POLES\nattribute vec3 a_globe_pos;attribute vec2 a_uv;\n#else\nattribute vec2 a_pos;\n#endif\nvarying vec2 v_pos0;float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(QUARTER_PI+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);}void main() {\n#ifdef GLOBE_POLES\nvec3 globe_pos=a_globe_pos;vec2 uv=a_uv;\n#else\nfloat tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY);\n#endif\nv_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale;\n#ifdef GLOBE_POLES\nvec3 up_vector=globe_derived_up_vector;\n#else\nvec3 up_vector=elevationVector(tile_pos);\n#endif\nfloat height=elevation(tile_pos);globe_pos+=up_vector*height;\n#ifndef GLOBE_POLES\nglobe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z;\n#endif\n#ifdef GLOBE_POLES\nvec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0);\n#else\nvec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0);\n#endif\ngl_Position=u_proj_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n}";

var atmosphereFrag = "#include \"_prelude_fog.fragment.glsl\"\nuniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;varying highp vec3 v_ray_dir;varying highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir;\n#ifdef PROJECTION_GLOBE_VIEW\nglobe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) {\n#ifdef ALPHA_PASS\ngl_FragColor=vec4(0,0,0,0);return;\n#else\n#ifdef NATIVE\ngl_FragColor=vec4(1,1,1,1);\n#else\ngl_FragColor=vec4(0,0,0,1);\n#endif\nreturn;\n#endif\n}\n#endif\nhighp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ?\n0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle;\n#ifdef PROJECTION_GLOBE_VIEW\nhighp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ?\nPI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t);\n#else\nhorizon_angle=horizon_angle_mercator;\n#endif\nhorizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb;\n#ifdef ALPHA_PASS\nfloat a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);gl_FragColor=vec4(1.0,1.0,1.0,a);\n#else\nvec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;\n#ifndef NATIVE\nc=dither(c,gl_FragCoord.xy+u_temporal_offset);\n#endif\ngl_FragColor=vec4(c*t,t);\n#endif\n}";

var atmosphereVert = "attribute vec3 a_pos;attribute vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;varying highp vec3 v_ray_dir;varying highp vec3 v_horizon_dir;void main() {v_ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix(\nmix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}";

var starsFrag = "varying highp vec2 v_uv;varying mediump float v_intensity;float shapeCircle(in vec2 uv)\n{float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;gl_FragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}";

var starsVert = "\nattribute vec3 a_pos_3f;attribute vec2 a_uv;attribute float a_size_scale;attribute float a_fade_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;varying highp vec2 v_uv;varying mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_fade_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}";

var fillExtrusionDepthFrag = "varying highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\ngl_FragColor=pack_depth(v_depth);\n#endif\n}";

var fillExtrusionDepthVert = "#include \"_prelude_terrain.vertex.glsl\"\nuniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_vertical_scale;attribute vec4 a_pos_normal_ed;attribute vec2 a_centroid_pos;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\nvarying highp float v_depth;void main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\nbase*=u_vertical_scale;height*=u_vertical_scale;vec3 pos_nx=floor(a_pos_normal_ed.xyz*0.5);mediump vec3 top_up_ny=a_pos_normal_ed.xyz-2.0*pos_nx;base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=a_centroid_pos;\n#endif\nvec3 pos;\n#ifdef TERRAIN\nbool flat_roof=centroid_pos.x !=0.0 && t > 0.0;float ele=elevation(pos_nx.xy);float c_ele=flat_roof ? centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos) : ele;float h=flat_roof ? max(c_ele+height,ele+base+2.0) : ele+(t > 0.0 ? height : base);pos=vec3(pos_nx.xy,h);\n#else\npos=vec3(pos_nx.xy,t > 0.0 ? height : base);\n#endif\nfloat hidden=float(centroid_pos.x==0.0 && centroid_pos.y==1.0);gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);v_depth=gl_Position.z/gl_Position.w;}";

var groundShadowFrag = "#include \"_prelude_shadow.fragment.glsl\"\n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec3 u_ground_shadow_factor;varying vec4 v_pos_light_view_0;varying vec4 v_pos_light_view_1;varying float v_depth;\n#ifdef FOG\nvarying float v_fog_opacity;\n#endif\nvoid main() {float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light);\n#ifdef RENDER_CUTOFF\nshadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,v_depth));\n#endif\n#ifdef FOG\nshadow=mix(shadow,vec3(1.0),v_fog_opacity);\n#endif\n#ifdef INDICATOR_CUTOUT\nshadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0)).r);\n#endif\ngl_FragColor=vec4(shadow,1.0);}";

var groundShadowVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;attribute vec2 a_pos;varying vec4 v_pos_light_view_0;varying vec4 v_pos_light_view_1;varying float v_depth;\n#ifdef FOG\nvarying float v_fog_opacity;\n#endif\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0);v_depth=gl_Position.w;\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);v_fog_opacity=fog(v_fog_pos);\n#endif\n}";

var modelVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\nattribute vec3 a_pos_3f;\n#pragma mapbox: define-attribute highp vec3 normal_3f\n#pragma mapbox: define-attribute highp vec2 uv_2f\n#pragma mapbox: define-attribute highp vec3 color_3f\n#pragma mapbox: define-attribute highp vec4 color_4f\n#pragma mapbox: define-attribute-vertex-shader-only highp vec4 pbr\n#pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength\nuniform mat4 u_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix;\n#ifdef INSTANCED_ARRAYS\nattribute vec4 a_normal_matrix0;attribute vec4 a_normal_matrix1;attribute vec4 a_normal_matrix2;attribute vec4 a_normal_matrix3;\n#else\nuniform highp mat4 u_normal_matrix;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;varying vec4 v_pos_light_view_0;varying vec4 v_pos_light_view_1;varying float v_depth_shadows;\n#endif\nvarying vec4 v_position_height;varying lowp vec4 v_color_mix;\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nvarying highp float v_depth;\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\nvarying lowp vec4 v_roughness_metallic_emissive_alpha;varying mediump vec4 v_height_based_emission_params;\n#endif\nvoid main() {\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\n#pragma mapbox: initialize-attribute highp vec3 color_3f\n#pragma mapbox: initialize-attribute highp vec4 color_4f\n#pragma mapbox: initialize-attribute-custom highp vec4 pbr\n#pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength\nhighp mat4 normal_matrix;\n#ifdef INSTANCED_ARRAYS\nnormal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\n#else\nnormal_matrix=u_normal_matrix;\n#endif\nvec3 local_pos;mat3 rs;\n#ifdef MODEL_POSITION_ON_GPU\nvec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=u_matrix*pos;pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos;\n#else\nlocal_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a);\n#endif\nv_position_height.w=a_pos_3f.z;\n#ifdef HAS_ATTRIBUTE_a_pbr\nvec4 albedo_c=decode_color(pbr.xy);vec2 e_r_m=unpack_float(pbr.z);vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(pbr.w)/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(local_pos);\n#endif\n#ifdef RENDER_CUTOFF\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\n#endif\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef HAS_ATTRIBUTE_a_normal_3f\n#ifdef MODEL_POSITION_ON_GPU\nfloat x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f);\n#else\nnormal_3f=vec3(normal_matrix*vec4(normal_3f,0));\n#endif\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\n#ifdef HAS_ATTRIBUTE_a_color_4f\nv_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0);\n#endif\n#endif\n#ifdef RENDER_SHADOWS\nvec3 shadow_pos=local_pos;\n#ifdef NORMAL_OFFSET\n#ifdef HAS_ATTRIBUTE_a_normal_3f\n#ifdef MODEL_POSITION_ON_GPU\nvec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos+=offset*shadow_normal_offset_multiplier0();\n#else\nvec3 offset=shadow_normal_offset_model(normalize(normal_3f));shadow_pos+=offset*shadow_normal_offset_multiplier0();\n#endif\n#endif\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1);v_depth_shadows=gl_Position.w;\n#endif\n}";

var modelFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform float u_opacity;uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;varying highp vec4 v_position_height;varying lowp vec4 v_color_mix;\n#ifdef RENDER_SHADOWS\nvarying vec4 v_pos_light_view_0;varying vec4 v_pos_light_view_1;varying float v_depth_shadows;\n#endif\n#pragma mapbox: define-attribute highp vec3 normal_3f\n#pragma mapbox: define-attribute highp vec3 color_3f\n#pragma mapbox: define-attribute highp vec4 color_4f\n#pragma mapbox: define-attribute highp vec2 uv_2f\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\n#pragma mapbox: initialize-attribute highp vec3 color_3f\n#pragma mapbox: initialize-attribute highp vec4 color_4f\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\n#ifdef HAS_ATTRIBUTE_a_pbr\nvarying lowp vec4 v_roughness_metallic_emissive_alpha;varying mediump vec4 v_height_based_emission_params;\n#endif\n#ifdef HAS_TEXTURE_u_baseColorTexture\nuniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff;\n#endif\n#ifdef HAS_TEXTURE_u_metallicRoughnessTexture\nuniform sampler2D u_metallicRoughnessTexture;\n#endif\n#ifdef HAS_TEXTURE_u_occlusionTexture\nuniform sampler2D u_occlusionTexture;uniform float u_aoIntensity;\n#endif\n#ifdef HAS_TEXTURE_u_normalTexture\nuniform sampler2D u_normalTexture;\n#endif\n#ifdef HAS_TEXTURE_u_emissionTexture\nuniform sampler2D u_emissionTexture;\n#endif\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nvarying highp float v_depth;uniform sampler2D u_depthTexture;uniform vec2 u_inv_depth_size;bool isOccluded() {vec2 coord=gl_FragCoord.xy*u_inv_depth_size;highp float depth=unpack_depth(texture2D(u_depthTexture,coord));return v_depth > depth+0.0005;}\n#endif\nconst float M_PI=3.141592653589793;\n#define saturate(_x) clamp(_x,0.,1.)\nfloat calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor)\n{\n#ifdef LIGHTING_3D_MODE\nvec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor;\n#ifdef RENDER_SHADOWS\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\n#else\nlighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir));\n#endif\nreturn apply_lighting(albedo,transformed_normal,lighting_factor);\n#else\nvec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3;\n#endif\n}vec4 getBaseColor() {vec4 albedo=u_baseColorFactor;\n#ifdef HAS_ATTRIBUTE_a_color_3f\nalbedo*=vec4(color_3f,1.0);\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\n#else\n#ifdef HAS_ATTRIBUTE_a_color_4f\nalbedo*=color_4f;\n#endif\n#endif\n#if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f)\nvec4 texColor=texture2D(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}}\n#ifdef UNPREMULT_TEXTURE_IN_SHADER\nif(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0;\n#endif\ntexColor.rgb=sRGBToLinear(texColor.rgb);if(u_baseTextureIsAlpha) {if (texColor.w < 0.5) {discard;}albedo*=mix(vec4(texColor.rgb,texColor.a),vec4(texColor.a),float(u_baseTextureIsAlpha));} else {albedo*=texColor;}\n#endif\nreturn vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a);}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) {\n#ifdef HAS_TEXTURE_u_normalTexture\nhighp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res;\n#else\nreturn mat3(1.0);\n#endif\n}highp vec3 getNormal(){highp vec3 n;\n#ifdef HAS_ATTRIBUTE_a_normal_3f\nn=normalize(normal_3f);\n#else\nhighp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z));n=normalize(cross(fdx,fdy))*-1.0;\n#endif\n#if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nvec3 nMap=texture2D( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap);\n#endif\nreturn n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor;\n#ifdef HAS_ATTRIBUTE_a_pbr\nmat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w;\n#endif\n#if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) \nvec4 mrSample=texture2D(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b;\n#endif\nconst float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness)\n{float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH)\n{return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH)\n{float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness)\n{highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(M_PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV)\n{float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/M_PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat)\n{\n#ifdef LIGHTING_3D_MODE\nreturn mat.diffuseColor;\n#else\nreturn mat.diffuseColor/M_PI;\n#endif\n}vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV)\n{vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal)\n{vec3 env_light=vec3(0.65,0.65,0.65);\n#ifdef LIGHTING_3D_MODE\nfloat ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor;\n#endif\nvec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor)\n{highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor;\n#ifdef RENDER_SHADOWS\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\n#else\nlighting_factor=NdotL;\n#endif\nvec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0;\n#if !defined(LIGHTING_3D_MODE)\nconst vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL);\n#endif\ncolor*=intensityFactor;return color;}void main() {\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nif (isOccluded()) {discard;}\n#endif\nvec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor;\n#ifdef LIGHTING_3D_MODE\nlightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color;\n#endif\nvec4 finalColor;\n#ifdef DIFFUSE_SHADED\nvec3 N=getNormal();vec3 diffuse=getDiffuseShadedColor(getBaseColor().rgb,N,lightDir,lightColor);\n#ifdef HAS_TEXTURE_u_occlusionTexture\nfloat ao=(texture2D(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao;\n#endif\nfinalColor=vec4(diffuse,1.0)*u_opacity;\n#else\nMaterial mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);\n#if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nfloat ao=(texture2D(u_occlusionTexture,uv_2f).x-1.0)*u_aoIntensity+1.0;color*=ao;\n#endif\nvec4 emissive=u_emissiveFactor;\n#if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nemissive.rgb*=sRGBToLinear(texture2D(u_emissionTexture,uv_2f).rgb);\n#endif\ncolor+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity;\n#ifdef HAS_ATTRIBUTE_a_pbr\nfloat resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);color=mix(color,v_color_mix.rgb,min(1.0,resEmission));\n#ifdef HAS_ATTRIBUTE_a_color_4f\nfloat distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance);\n#endif\n#endif\ncolor=mix(color,mat.baseColor.rgb,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity);\n#endif\n#ifdef FOG\nfinalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w));\n#endif\n#ifdef RENDER_CUTOFF\nfinalColor*=v_cutoff_opacity;\n#endif\n#ifdef INDICATOR_CUTOUT\nfinalColor=applyCutout(finalColor);\n#endif\ngl_FragColor=finalColor;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var modelDepthVert = "attribute vec3 a_pos_3f;uniform mat4 u_matrix;varying highp float v_depth;\n#ifdef MODEL_POSITION_ON_GPU\n#ifdef INSTANCED_ARRAYS\nattribute vec4 a_normal_matrix0;attribute vec4 a_normal_matrix1;attribute vec4 a_normal_matrix2;attribute vec4 a_normal_matrix3;\n#else\nuniform highp mat4 u_instance;\n#endif\nuniform highp mat4 u_node_matrix;\n#endif\nvoid main() {\n#ifdef MODEL_POSITION_ON_GPU\nhighp mat4 instance;\n#ifdef INSTANCED_ARRAYS\ninstance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\n#else\ninstance=u_instance;\n#endif\nvec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=u_matrix*pos;\n#else\ngl_Position=u_matrix*vec4(a_pos_3f,1);\n#endif\nv_depth=gl_Position.z/gl_Position.w;}";

var modelDepthFrag = "varying highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\ngl_FragColor=pack_depth(v_depth);\n#endif\n}";

var preludeShadowVert = "#ifdef RENDER_SHADOWS\nuniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];}\n#endif//RENDER_SHADOWS";

var preludeShadowFrag = "#ifdef RENDER_SHADOWS\n#if defined(NATIVE) && __VERSION__ >=300\n#define TEXTURE_GATHER\n#endif\n#ifdef DEPTH_TEXTURE\nuniform highp sampler2D u_shadowmap_0;uniform highp sampler2D u_shadowmap_1;\n#else\nuniform sampler2D u_shadowmap_0;uniform sampler2D u_shadowmap_1;\n#endif\nuniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;highp float shadow_sample_1(highp vec2 uv,highp float compare) {highp float shadow_depth;\n#ifdef DEPTH_TEXTURE\nshadow_depth=texture2D(u_shadowmap_1,uv).r;\n#else\nshadow_depth=unpack_depth(texture2D(u_shadowmap_1,uv))*0.5+0.5;\n#endif\nreturn step(shadow_depth,compare);}highp float shadow_sample_0(highp vec2 uv,highp float compare) {highp float shadow_depth;\n#ifdef DEPTH_TEXTURE\nshadow_depth=texture2D(u_shadowmap_0,uv).r;\n#else\nshadow_depth=unpack_depth(texture2D(u_shadowmap_0,uv))*0.5+0.5;\n#endif\nreturn step(shadow_depth,compare);}float shadow_occlusion_1(highp vec4 pos,highp float bias) {highp vec2 uv=pos.xy;return shadow_sample_1(uv,pos.z-bias);}float shadow_occlusion_0(highp vec4 pos,highp float bias) {highp float compare0=pos.z-bias;\n#ifdef TEXTURE_GATHER\nhighp vec2 uv=pos.xy;highp vec4 samples=textureGather(u_shadowmap_0,uv,0);lowp vec4 stepSamples=step(samples,vec4(compare0));\n#else\nhighp vec2 uv00=pos.xy-vec2(0.5*u_shadow_texel_size);highp vec2 uv10=uv00+vec2(u_shadow_texel_size,0.0);highp vec2 uv01=uv00+vec2(0.0,u_shadow_texel_size);highp vec2 uv11=uv01+vec2(u_shadow_texel_size,0.0);lowp vec4 stepSamples=vec4(\nshadow_sample_0(uv01,compare0),shadow_sample_0(uv11,compare0),shadow_sample_0(uv10,compare0),shadow_sample_0(uv00,compare0)\n);\n#endif\nvec2 f=fract(pos.xy*u_shadow_map_resolution-vec2(0.5));lowp vec2 lerpx=mix(stepSamples.wx,stepSamples.zy,f.xx);return mix(lerpx.x,lerpx.y,f.y);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {\n#ifdef SHADOWS_SINGLE_CASCADE\nlight_view_pos0.xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;return shadow_occlusion_0(light_view_pos0,bias);\n#else\nlight_view_pos0.xyz/=light_view_pos0.w;light_view_pos1.xyz/=light_view_pos1.w;vec4 uv=vec4(light_view_pos0.xy,light_view_pos1.xy);vec4 abs_bounds=abs(uv);if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {light_view_pos0.xyz=light_view_pos0.xyz*0.5+0.5;return shadow_occlusion_0(light_view_pos0,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}light_view_pos1.xyz=light_view_pos1.xyz*0.5+0.5;float occlusion1=shadow_occlusion_1(light_view_pos1,bias);return mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth));\n#endif\n}highp float calculate_shadow_bias(float NDotL) {\n#ifdef NORMAL_OFFSET\nreturn 0.5*u_shadow_bias.x;\n#else\nreturn 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z));\n#endif\n}float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);}\n#endif";

// Disable Flow annotations here because Flow doesn't support importing GLSL files
/* eslint-disable flowtype/require-valid-file-annotation */
const commonDefines = [];
parseUsedPreprocessorDefines(preludeCommon, commonDefines);
const includeMap = {
    '_prelude_fog.vertex.glsl': preludeFogVert,
    '_prelude_terrain.vertex.glsl': preludeTerrainVert,
    '_prelude_shadow.vertex.glsl': preludeShadowVert,
    '_prelude_fog.fragment.glsl': preludeFogFrag,
    '_prelude_shadow.fragment.glsl': preludeShadowFrag,
    '_prelude_lighting.glsl': preludeLighting
};
// Populated during precompilation
const defineMap = {};
compile('', preludeTerrainVert);
compile(preludeFogFrag, preludeFogVert);
compile(preludeShadowFrag, preludeShadowVert);
const prelude = compile(preludeFrag, preludeVert);
const preludeCommonSource = preludeCommon;
const preludeVertPrecisionQualifiers = `
#ifdef GL_ES
precision highp float;
#else

#if !defined(lowp)
#define lowp
#endif

#if !defined(mediump)
#define mediump
#endif

#if !defined(highp)
#define highp
#endif

#endif`;
const preludeFragPrecisionQualifiers = `
#ifdef GL_ES
precision mediump float;
#else

#if !defined(lowp)
#define lowp
#endif

#if !defined(mediump)
#define mediump
#endif

#if !defined(highp)
#define highp
#endif

#endif`;
var shaders = {
    background: compile(backgroundFrag, backgroundVert),
    backgroundPattern: compile(backgroundPatternFrag, backgroundPatternVert),
    circle: compile(circleFrag, circleVert),
    clippingMask: compile(clippingMaskFrag, clippingMaskVert),
    heatmap: compile(heatmapFrag, heatmapVert),
    heatmapTexture: compile(heatmapTextureFrag, heatmapTextureVert),
    collisionBox: compile(collisionBoxFrag, collisionBoxVert),
    collisionCircle: compile(collisionCircleFrag, collisionCircleVert),
    debug: compile(debugFrag, debugVert),
    fill: compile(fillFrag, fillVert),
    fillOutline: compile(fillOutlineFrag, fillOutlineVert),
    fillOutlinePattern: compile(fillOutlinePatternFrag, fillOutlinePatternVert),
    fillPattern: compile(fillPatternFrag, fillPatternVert),
    fillExtrusion: compile(fillExtrusionFrag, fillExtrusionVert),
    fillExtrusionDepth: compile(fillExtrusionDepthFrag, fillExtrusionDepthVert),
    fillExtrusionPattern: compile(fillExtrusionPatternFrag, fillExtrusionPatternVert),
    groundShadow: compile(groundShadowFrag, groundShadowVert),
    fillExtrusionGroundEffect: compile(fillExtrusionGroundEffectFrag, fillExtrusionGroundEffectVert),
    hillshadePrepare: compile(hillshadePrepareFrag, hillshadePrepareVert),
    hillshade: compile(hillshadeFrag, hillshadeVert),
    line: compile(lineFrag, lineVert),
    linePattern: compile(linePatternFrag, linePatternVert),
    raster: compile(rasterFrag, rasterVert),
    symbolIcon: compile(symbolIconFrag, symbolIconVert),
    symbolSDF: compile(symbolSDFFrag, symbolSDFVert),
    symbolTextAndIcon: compile(symbolTextAndIconFrag, symbolTextAndIconVert),
    terrainRaster: compile(terrainRasterFrag, terrainRasterVert),
    terrainDepth: compile(terrainDepthFrag, terrainDepthVert),
    skybox: compile(skyboxFrag, skyboxVert),
    skyboxGradient: compile(skyboxGradientFrag, skyboxVert),
    skyboxCapture: compile(skyboxCaptureFrag, skyboxCaptureVert),
    globeRaster: compile(globeFrag, globeVert),
    globeAtmosphere: compile(atmosphereFrag, atmosphereVert),
    model: compile(modelFrag, modelVert),
    modelDepth: compile(modelDepthFrag, modelDepthVert),
    stars: compile(starsFrag, starsVert)
};
function parseUsedPreprocessorDefines(source, defines) {
    const lines = source.replace(/\s*\/\/[^\n]*\n/g, '\n').split('\n');
    for (let line of lines) {
        line = line.trim();
        if (line[0] === '#') {
            if (line.includes('if') && !line.includes('endif')) {
                line = line.replace('#', '').replace(/ifdef|ifndef|elif|if/g, '').replace(/!|defined|\(|\)|\|\||&&/g, '').replace(/\s+/g, ' ').trim();
                const newDefines = line.split(' ');
                for (const define of newDefines) {
                    if (!defines.includes(define)) {
                        defines.push(define);
                    }
                }
            }
        }
    }
}
// Expand #pragmas to #ifdefs.
function compile(fragmentSource, vertexSource) {
    const includeRegex = /#include\s+"([^"]+)"/g;
    const pragmaRegex = /#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g;
    const attributeRegex = /attribute(\S*) (highp |mediump |lowp )?([\w]+) ([\w]+)/g;
    let staticAttributes = vertexSource.match(attributeRegex);
    // remove duplicates as Safari does not support lookbehind in regex
    // so we need to get rid of initialize-* expressions
    if (staticAttributes) {
        staticAttributes = staticAttributes.filter((element, index) => {
            return staticAttributes.indexOf(element) === index;
        });
    }
    const fragmentPragmas = {};
    const vertexIncludes = [];
    const fragmentIncludes = [];
    fragmentSource = fragmentSource.replace(includeRegex, (match, name) => {
        fragmentIncludes.push(name);
        return '';
    });
    vertexSource = vertexSource.replace(includeRegex, (match, name) => {
        vertexIncludes.push(name);
        return '';
    });
    let usedDefines = [...commonDefines];
    parseUsedPreprocessorDefines(fragmentSource, usedDefines);
    parseUsedPreprocessorDefines(vertexSource, usedDefines);
    for (const includePath of [
            ...vertexIncludes,
            ...fragmentIncludes
        ]) {
        if (!includeMap[includePath]) {
            console.error(`Undefined include: ${ includePath }`);
        }
        if (!defineMap[includePath]) {
            defineMap[includePath] = [];
            parseUsedPreprocessorDefines(includeMap[includePath], defineMap[includePath]);
        }
        usedDefines = [
            ...usedDefines,
            ...defineMap[includePath]
        ];
    }
    fragmentSource = fragmentSource.replace(pragmaRegex, (match, operation, precision, type, name) => {
        fragmentPragmas[name] = true;
        if (operation === 'define') {
            return `
#ifndef HAS_UNIFORM_u_${ name }
varying ${ precision } ${ type } ${ name };
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
        } else if (operation === 'initialize') {
            return `
#ifdef HAS_UNIFORM_u_${ name }
    ${ precision } ${ type } ${ name } = u_${ name };
#endif
`;
        } else if (operation === 'define-attribute') {
            return `
#ifdef HAS_ATTRIBUTE_a_${ name }
    varying ${ precision } ${ type } ${ name };
#endif
`;
        } else if (operation === 'initialize-attribute') {
            return '';
        }
    });
    vertexSource = vertexSource.replace(pragmaRegex, (match, operation, precision, type, name) => {
        const attrType = type === 'float' ? 'vec2' : type;
        const unpackType = name.match(/color/) ? 'color' : attrType;
        if (operation === 'define-attribute-vertex-shader-only') {
            return `
#ifdef HAS_ATTRIBUTE_a_${ name }
attribute ${ precision } ${ type } a_${ name };
#endif
`;
        } else if (fragmentPragmas[name]) {
            if (operation === 'define') {
                return `
#ifndef HAS_UNIFORM_u_${ name }
uniform lowp float u_${ name }_t;
attribute ${ precision } ${ attrType } a_${ name };
varying ${ precision } ${ type } ${ name };
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
            } else if (operation === 'initialize') {
                if (unpackType === 'vec4') {
                    // vec4 attributes are only used for cross-faded properties, and are not packed
                    return `
#ifndef HAS_UNIFORM_u_${ name }
    ${ name } = a_${ name };
#else
    ${ precision } ${ type } ${ name } = u_${ name };
#endif
`;
                } else {
                    return `
#ifndef HAS_UNIFORM_u_${ name }
    ${ name } = unpack_mix_${ unpackType }(a_${ name }, u_${ name }_t);
#else
    ${ precision } ${ type } ${ name } = u_${ name };
#endif
`;
                }
            } else if (operation === 'define-attribute') {
                return `
#ifdef HAS_ATTRIBUTE_a_${ name }
    attribute ${ precision } ${ type } a_${ name };
    varying ${ precision } ${ type } ${ name };
#endif
`;
            } else if (operation === 'initialize-attribute') {
                return `
#ifdef HAS_ATTRIBUTE_a_${ name }
    ${ name } = a_${ name };
#endif
`;
            }
        } else {
            if (operation === 'define') {
                return `
#ifndef HAS_UNIFORM_u_${ name }
uniform lowp float u_${ name }_t;
attribute ${ precision } ${ attrType } a_${ name };
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
            } else if (operation === 'define-instanced') {
                if (unpackType === 'mat4') {
                    return `
#ifdef INSTANCED_ARRAYS
attribute vec4 a_${ name }0;
attribute vec4 a_${ name }1;
attribute vec4 a_${ name }2;
attribute vec4 a_${ name }3;
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
                } else {
                    return `
#ifdef INSTANCED_ARRAYS
attribute ${ precision } ${ attrType } a_${ name };
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
                }
            } else if (operation === 'initialize-attribute-custom') {
                return `
#ifdef HAS_ATTRIBUTE_a_${ name }
    ${ precision } ${ type } ${ name } = a_${ name };
#endif
`;
            } else
                /* if (operation === 'initialize') */
                {
                    if (unpackType === 'vec4') {
                        // vec4 attributes are only used for cross-faded properties, and are not packed
                        return `
#ifndef HAS_UNIFORM_u_${ name }
    ${ precision } ${ type } ${ name } = a_${ name };
#else
    ${ precision } ${ type } ${ name } = u_${ name };
#endif
`;
                    } else
                        /* */
                        {
                            return `
#ifndef HAS_UNIFORM_u_${ name }
    ${ precision } ${ type } ${ name } = unpack_mix_${ unpackType }(a_${ name }, u_${ name }_t);
#else
    ${ precision } ${ type } ${ name } = u_${ name };
#endif
`;
                        }
                }
        }
    });
    return {
        fragmentSource,
        vertexSource,
        staticAttributes,
        usedDefines,
        vertexIncludes,
        fragmentIncludes
    };
}

//      
class VertexArrayObject {
    constructor() {
        this.boundProgram = null;
        this.boundLayoutVertexBuffer = null;
        this.boundPaintVertexBuffers = [];
        this.boundIndexBuffer = null;
        this.boundVertexOffset = null;
        this.boundDynamicVertexBuffers = [];
        this.vao = null;
    }
    bind(context, program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffers, vertexAttribDivisorValue) {
        this.context = context;
        let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length;
        for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) {
            if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) {
                paintBuffersDiffer = true;
            }
        }
        let dynamicBuffersDiffer = this.boundDynamicVertexBuffers.length !== dynamicVertexBuffers.length;
        for (let i = 0; !dynamicBuffersDiffer && i < dynamicVertexBuffers.length; i++) {
            if (this.boundDynamicVertexBuffers[i] !== dynamicVertexBuffers[i]) {
                dynamicBuffersDiffer = true;
            }
        }
        const isFreshBindRequired = !this.vao || this.boundProgram !== program || this.boundLayoutVertexBuffer !== layoutVertexBuffer || paintBuffersDiffer || dynamicBuffersDiffer || this.boundIndexBuffer !== indexBuffer || this.boundVertexOffset !== vertexOffset;
        if (isFreshBindRequired) {
            this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffers, vertexAttribDivisorValue);
        } else {
            context.bindVertexArrayOES.set(this.vao);
            for (const dynamicBuffer of dynamicVertexBuffers) {
                if (dynamicBuffer) {
                    dynamicBuffer.bind();
                    if (vertexAttribDivisorValue && dynamicBuffer.instanceCount) {
                        dynamicBuffer.setVertexAttribDivisor(context.gl, program, vertexAttribDivisorValue);
                    }
                }
            }
            if (indexBuffer && indexBuffer.dynamicDraw) {
                indexBuffer.bind();
            }
        }
    }
    freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffers, vertexAttribDivisorValue) {
        const numNextAttributes = program.numAttributes;
        const context = this.context;
        const gl = context.gl;
        if (this.vao)
            this.destroy();
        this.vao = context.gl.createVertexArray();
        context.bindVertexArrayOES.set(this.vao);
        // store the arguments so that we can verify them when the vao is bound again
        this.boundProgram = program;
        this.boundLayoutVertexBuffer = layoutVertexBuffer;
        this.boundPaintVertexBuffers = paintVertexBuffers;
        this.boundIndexBuffer = indexBuffer;
        this.boundVertexOffset = vertexOffset;
        this.boundDynamicVertexBuffers = dynamicVertexBuffers;
        layoutVertexBuffer.enableAttributes(gl, program);
        layoutVertexBuffer.bind();
        layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);
        for (const vertexBuffer of paintVertexBuffers) {
            vertexBuffer.enableAttributes(gl, program);
            vertexBuffer.bind();
            vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);
        }
        for (const dynamicBuffer of dynamicVertexBuffers) {
            if (dynamicBuffer) {
                dynamicBuffer.enableAttributes(gl, program);
                dynamicBuffer.bind();
                dynamicBuffer.setVertexAttribPointers(gl, program, vertexOffset);
                if (vertexAttribDivisorValue && dynamicBuffer.instanceCount) {
                    dynamicBuffer.setVertexAttribDivisor(gl, program, vertexAttribDivisorValue);
                }
            }
        }
        if (indexBuffer) {
            indexBuffer.bind();
        }
        context.currentNumAttributes = numNextAttributes;
    }
    destroy() {
        if (this.vao) {
            this.context.gl.deleteVertexArray(this.vao);
            this.vao = null;
        }
    }
}

//      
const hillshadeUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_image': new Uniform1i(context),
    'u_latrange': new Uniform2f(context),
    'u_light': new Uniform2f(context),
    'u_shadow': new UniformColor(context),
    'u_highlight': new UniformColor(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_accent': new UniformColor(context)
});
const hillshadePrepareUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_image': new Uniform1i(context),
    'u_dimension': new Uniform2f(context),
    'u_zoom': new Uniform1f(context),
    'u_unpack': new Uniform4f(context)
});
const hillshadeUniformValues = (painter, tile, layer, matrix) => {
    const shadow = layer.paint.get('hillshade-shadow-color');
    const highlight = layer.paint.get('hillshade-highlight-color');
    const accent = layer.paint.get('hillshade-accent-color');
    const emissiveStrength = layer.paint.get('hillshade-emissive-strength');
    let azimuthal = degToRad(layer.paint.get('hillshade-illumination-direction'));
    // modify azimuthal angle by map rotation if light is anchored at the viewport
    if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') {
        azimuthal -= painter.transform.angle;
    } else if (painter.style && painter.style.enable3dLights()) {
        // hillshade-illumination-anchor = map & 3d lights enabled
        if (painter.style.directionalLight) {
            const direction = painter.style.directionalLight.properties.get('direction');
            const spherical = cartesianPositionToSpherical(direction.x, direction.y, direction.z);
            azimuthal = degToRad(spherical[1]);
        }
    }
    const align = !painter.options.moving;
    return {
        'u_matrix': matrix ? matrix : painter.transform.calculateProjMatrix(tile.tileID.toUnwrapped(), align),
        'u_image': 0,
        'u_latrange': getTileLatRange(painter, tile.tileID),
        'u_light': [
            layer.paint.get('hillshade-exaggeration'),
            azimuthal
        ],
        'u_shadow': shadow,
        'u_highlight': highlight,
        'u_emissive_strength': emissiveStrength,
        'u_accent': accent
    };
};
const hillshadeUniformPrepareValues = (tileID, dem) => {
    const stride = dem.stride;
    const matrix = mat4_1.create();
    // Flip rendering at y axis.
    mat4_1.ortho(matrix, 0, EXTENT, -EXTENT, 0, 0, 1);
    mat4_1.translate(matrix, matrix, [
        0,
        -EXTENT,
        0
    ]);
    return {
        'u_matrix': matrix,
        'u_image': 1,
        'u_dimension': [
            stride,
            stride
        ],
        'u_zoom': tileID.overscaledZ,
        'u_unpack': dem.unpackVector
    };
};
function getTileLatRange(painter, tileID) {
    // for scaling the magnitude of a points slope by its latitude
    const tilesAtZoom = Math.pow(2, tileID.canonical.z);
    const y = tileID.canonical.y;
    return [
        new MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat,
        new MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat
    ];
}

//      
function drawHillshade(painter, sourceCache, layer, tileIDs) {
    if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent')
        return;
    const context = painter.context;
    // When rendering to texture, coordinates are already sorted: primary by
    // proxy id and secondary sort is by Z.
    const renderingToTexture = painter.terrain && painter.terrain.renderingToTexture;
    const [stencilModes, coords] = painter.renderPass === 'translucent' && !renderingToTexture ? painter.stencilConfigForOverlap(tileIDs) : [
        {},
        tileIDs
    ];
    for (const coord of coords) {
        const tile = sourceCache.getTile(coord);
        if (tile.needsHillshadePrepare && painter.renderPass === 'offscreen') {
            prepareHillshade(painter, tile, layer);
        } else if (painter.renderPass === 'translucent') {
            const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
            const emissiveStrength = layer.paint.get('hillshade-emissive-strength');
            const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
            const stencilMode = renderingToTexture && painter.terrain ? painter.terrain.stencilModeForRTTOverlap(coord) : stencilModes[coord.overscaledZ];
            renderHillshade(painter, coord, tile, layer, depthMode, stencilMode, colorMode);
        }
    }
    context.viewport.set([
        0,
        0,
        painter.width,
        painter.height
    ]);
    painter.resetStencilClippingMasks();
}
function renderHillshade(painter, coord, tile, layer, depthMode, stencilMode, colorMode) {
    const context = painter.context;
    const gl = context.gl;
    const fbo = tile.hillshadeFBO;
    if (!fbo)
        return;
    painter.prepareDrawTile();
    const affectedByFog = painter.isTileAffectedByFog(coord);
    const program = painter.getOrCreateProgram('hillshade', { overrideFog: affectedByFog });
    context.activeTexture.set(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
    const uniformValues = hillshadeUniformValues(painter, tile, layer, painter.terrain ? coord.projMatrix : null);
    painter.uploadCommonUniforms(context, program, coord.toUnwrapped());
    const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = painter.getTileBoundsBuffers(tile);
    program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
}
function prepareDEMTexture(painter, tile, dem) {
    if (!tile.needsDEMTextureUpload)
        return;
    const context = painter.context;
    const gl = context.gl;
    context.pixelStoreUnpackPremultiplyAlpha.set(false);
    const textureStride = dem.stride;
    tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride);
    const demImage = dem.getPixels();
    if (tile.demTexture) {
        tile.demTexture.update(demImage, { premultiply: false });
    } else {
        tile.demTexture = new Texture(context, demImage, painter.terrainUseFloatDEM() ? gl.R32F : gl.RGBA, { premultiply: false });
    }
    tile.needsDEMTextureUpload = false;
}
// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y
// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels.
function prepareHillshade(painter, tile, layer) {
    const context = painter.context;
    const gl = context.gl;
    if (!tile.dem)
        return;
    const dem = tile.dem;
    context.activeTexture.set(gl.TEXTURE1);
    prepareDEMTexture(painter, tile, dem);
    if (!tile.demTexture)
        return;
    // Silence flow.
    tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
    const tileSize = dem.dim;
    context.activeTexture.set(gl.TEXTURE0);
    let fbo = tile.hillshadeFBO;
    if (!fbo) {
        const renderTexture = new Texture(context, {
            width: tileSize,
            height: tileSize,
            data: null
        }, gl.RGBA);
        renderTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        fbo = tile.hillshadeFBO = context.createFramebuffer(tileSize, tileSize, true, 'renderbuffer');
        fbo.colorAttachment.set(renderTexture.texture);
    }
    context.bindFramebuffer.set(fbo.framebuffer);
    context.viewport.set([
        0,
        0,
        tileSize,
        tileSize
    ]);
    const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = painter.getMercatorTileBoundsBuffers();
    const definesValues = [];
    if (painter.terrainUseFloatDEM())
        definesValues.push('TERRAIN_DEM_FLOAT_FORMAT');
    painter.getOrCreateProgram('hillshadePrepare', { defines: definesValues }).draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.unblended, CullFaceMode.disabled, hillshadeUniformPrepareValues(tile.tileID, dem), layer.id, tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
    tile.needsHillshadePrepare = false;
}

//      
const terrainRasterUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_image0': new Uniform1i(context),
    'u_skirt_height': new Uniform1f(context),
    'u_ground_shadow_factor': new Uniform3f(context)
});
const terrainRasterUniformValues = (matrix, skirtHeight, groundShadowFactor) => ({
    'u_matrix': matrix,
    'u_image0': 0,
    'u_skirt_height': skirtHeight,
    'u_ground_shadow_factor': groundShadowFactor
});

//      
const globeRasterUniforms = context => ({
    'u_proj_matrix': new UniformMatrix4f(context),
    'u_globe_matrix': new UniformMatrix4f(context),
    'u_normalize_matrix': new UniformMatrix4f(context),
    'u_merc_matrix': new UniformMatrix4f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_merc_center': new Uniform2f(context),
    'u_image0': new Uniform1i(context),
    'u_grid_matrix': new UniformMatrix3f(context),
    'u_skirt_height': new Uniform1f(context),
    'u_frustum_tl': new Uniform3f(context),
    'u_frustum_tr': new Uniform3f(context),
    'u_frustum_br': new Uniform3f(context),
    'u_frustum_bl': new Uniform3f(context),
    'u_globe_pos': new Uniform3f(context),
    'u_globe_radius': new Uniform1f(context),
    'u_viewport': new Uniform2f(context)
});
const atmosphereUniforms = context => ({
    'u_frustum_tl': new Uniform3f(context),
    'u_frustum_tr': new Uniform3f(context),
    'u_frustum_br': new Uniform3f(context),
    'u_frustum_bl': new Uniform3f(context),
    'u_horizon': new Uniform1f(context),
    'u_transition': new Uniform1f(context),
    'u_fadeout_range': new Uniform1f(context),
    'u_color': new Uniform4f(context),
    'u_high_color': new Uniform4f(context),
    'u_space_color': new Uniform4f(context),
    'u_temporal_offset': new Uniform1f(context),
    'u_horizon_angle': new Uniform1f(context)
});
const globeRasterUniformValues = (projMatrix, globeMatrix, globeMercatorMatrix, normalizeMatrix, zoomTransition, mercCenter, frustumDirTl, frustumDirTr, frustumDirBr, frustumDirBl, globePosition, globeRadius, viewport, skirtHeight, gridMatrix) => ({
    'u_proj_matrix': Float32Array.from(projMatrix),
    'u_globe_matrix': globeMatrix,
    'u_normalize_matrix': Float32Array.from(normalizeMatrix),
    'u_merc_matrix': globeMercatorMatrix,
    'u_zoom_transition': zoomTransition,
    'u_merc_center': mercCenter,
    'u_image0': 0,
    'u_frustum_tl': frustumDirTl,
    'u_frustum_tr': frustumDirTr,
    'u_frustum_br': frustumDirBr,
    'u_frustum_bl': frustumDirBl,
    'u_globe_pos': globePosition,
    'u_globe_radius': globeRadius,
    'u_viewport': viewport,
    'u_grid_matrix': gridMatrix ? Float32Array.from(gridMatrix) : new Float32Array(9),
    'u_skirt_height': skirtHeight
});
const atmosphereUniformValues = (frustumDirTl, frustumDirTr, frustumDirBr, frustumDirBl, horizon, transitionT, fadeoutRange, color, highColor, spaceColor, temporalOffset, horizonAngle) => ({
    'u_frustum_tl': frustumDirTl,
    'u_frustum_tr': frustumDirTr,
    'u_frustum_br': frustumDirBr,
    'u_frustum_bl': frustumDirBl,
    'u_horizon': horizon,
    'u_transition': transitionT,
    'u_fadeout_range': fadeoutRange,
    'u_color': color,
    'u_high_color': highColor,
    'u_space_color': spaceColor,
    'u_temporal_offset': temporalOffset,
    'u_horizon_angle': horizonAngle
});

//      
const cutoffUniforms = context => ({ 'u_cutoff_params': new Uniform4f(context) });
// This function returns the parameters of the cutoff effect for the LOD content (before the tileCover shows lower zoom
// level tiles)
//
// The first 2 values are the near and far plane distances in pixels, which are used to linearize the depth values of
// the vertices after the projection
//
// The 3rd value is the distance from which the content will be hidden, which is relative to the range of the near and
// far plane distance
//
// The 4th value is the distance where the linear fade out from value 3 should end
const getCutoffParams = (painter, cutoffFadeRange) => {
    if (cutoffFadeRange > 0 && painter.terrain) {
        // To be fixed: https://mapbox.atlassian.net/browse/MAPS3D-1034
        warnOnce('Cutoff is currently disabled on terrain');
    }
    if (cutoffFadeRange <= 0 || painter.terrain) {
        return {
            shouldRenderCutoff: false,
            uniformValues: {
                'u_cutoff_params': [
                    0,
                    0,
                    0,
                    0
                ]
            }
        };
    }
    const lerp = (a, b, t) => {
        return (1 - t) * a + t * b;
    };
    const tr = painter.transform;
    const zoomScale = Math.max(Math.abs(tr._zoom - (painter.minCutoffZoom - 1)), 1);
    const pitchScale = tr.isLODDisabled(false) ? smoothstep(MIN_LOD_PITCH, MIN_LOD_PITCH - 15, tr.pitch) : smoothstep(30, 15, tr.pitch);
    const zRange = tr._farZ - tr._nearZ;
    const cameraToCenterDistance = tr.cameraToCenterDistance;
    const fadeRangePixels = cutoffFadeRange * tr.height;
    // Scaled down by 0.75 because at the minimum zoom level the first LOD tile closer than the center
    const cutoffDistance = lerp(cameraToCenterDistance * 0.75, tr._farZ + fadeRangePixels, pitchScale) * zoomScale;
    const relativeCutoffDistance = (cutoffDistance - tr._nearZ) / zRange;
    const relativeCutoffFadeDistance = (cutoffDistance - fadeRangePixels - tr._nearZ) / zRange;
    return {
        shouldRenderCutoff: pitchScale < 1,
        uniformValues: {
            'u_cutoff_params': [
                tr._nearZ,
                tr._farZ,
                relativeCutoffDistance,
                relativeCutoffFadeDistance
            ]
        }
    };
};

//      
class VertexMorphing {
    constructor() {
        this.operations = {};
    }
    newMorphing(key, from, to, now, duration) {
        if (key in this.operations) {
            const op = this.operations[key];
            // Queue the target tile unless it's being morphed to already
            if (op.to.tileID.key !== to.tileID.key)
                op.queued = to;
        } else {
            this.operations[key] = {
                startTime: now,
                phase: 0,
                duration,
                from,
                to,
                queued: null
            };
        }
    }
    getMorphValuesForProxy(key) {
        if (!(key in this.operations))
            return null;
        const op = this.operations[key];
        const from = op.from;
        const to = op.to;
        return {
            from,
            to,
            phase: op.phase
        };
    }
    update(now) {
        for (const key in this.operations) {
            const op = this.operations[key];
            op.phase = (now - op.startTime) / op.duration;
            // Start the queued operation if the current one is finished or the data has expired
            while (op.phase >= 1 || !this._validOp(op)) {
                if (!this._nextOp(op, now)) {
                    delete this.operations[key];
                    break;
                }
            }
        }
    }
    _nextOp(op, now) {
        if (!op.queued)
            return false;
        op.from = op.to;
        op.to = op.queued;
        op.queued = null;
        op.phase = 0;
        op.startTime = now;
        return true;
    }
    _validOp(op) {
        return op.from.hasData() && op.to.hasData();
    }
}
function demTileChanged(prev, next) {
    if (prev == null || next == null)
        return false;
    if (!prev.hasData() || !next.hasData())
        return false;
    if (prev.demTexture == null || next.demTexture == null)
        return false;
    return prev.tileID.key !== next.tileID.key;
}
const vertexMorphing = new VertexMorphing();
const SHADER_DEFAULT = 0;
const SHADER_MORPHING = 1;
const defaultDuration = 250;
const shaderDefines = {
    '0': null,
    '1': 'TERRAIN_VERTEX_MORPHING'
};
function drawTerrainForGlobe(painter, terrain, sourceCache, tileIDs, now) {
    const context = painter.context;
    const gl = context.gl;
    let program, programMode;
    const tr = painter.transform;
    const useCustomAntialiasing = globeUseCustomAntiAliasing(painter, context, tr);
    const setShaderMode = (coord, mode) => {
        if (programMode === mode)
            return;
        const defines = [
            shaderDefines[mode],
            'PROJECTION_GLOBE_VIEW'
        ];
        if (useCustomAntialiasing)
            defines.push('CUSTOM_ANTIALIASING');
        const affectedByFog = painter.isTileAffectedByFog(coord);
        program = painter.getOrCreateProgram('globeRaster', {
            defines,
            overrideFog: affectedByFog
        });
        programMode = mode;
    };
    const colorMode = painter.colorModeForRenderPass();
    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    vertexMorphing.update(now);
    const globeMercatorMatrix = calculateGlobeMercatorMatrix(tr);
    const mercatorCenter = [
        mercatorXfromLng(tr.center.lng),
        mercatorYfromLat(tr.center.lat)
    ];
    const sharedBuffers = painter.globeSharedBuffers;
    const viewport = [
        tr.width * exported$1.devicePixelRatio,
        tr.height * exported$1.devicePixelRatio
    ];
    const globeMatrix = Float32Array.from(tr.globeMatrix);
    const elevationOptions = { useDenormalizedUpVectorScale: true };
    {
        const tr = painter.transform;
        const skirtHeightValue = skirtHeight(tr.zoom, terrain.exaggeration(), terrain.sourceCache._source.tileSize);
        programMode = -1;
        const primitive = gl.TRIANGLES;
        for (const coord of tileIDs) {
            const tile = sourceCache.getTile(coord);
            const stencilMode = StencilMode.disabled;
            const prevDemTile = terrain.prevTerrainTileForTile[coord.key];
            const nextDemTile = terrain.terrainTileForTile[coord.key];
            if (demTileChanged(prevDemTile, nextDemTile)) {
                vertexMorphing.newMorphing(coord.key, prevDemTile, nextDemTile, now, defaultDuration);
            }
            // Bind the main draped texture
            context.activeTexture.set(gl.TEXTURE0);
            tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            const morph = vertexMorphing.getMorphValuesForProxy(coord.key);
            const shaderMode = morph ? SHADER_MORPHING : SHADER_DEFAULT;
            if (morph) {
                extend(elevationOptions, {
                    morphing: {
                        srcDemTile: morph.from,
                        dstDemTile: morph.to,
                        phase: easeCubicInOut(morph.phase)
                    }
                });
            }
            const tileBounds = tileCornersToBounds(coord.canonical);
            const latitudinalLod = getLatitudinalLod(tileBounds.getCenter().lat);
            const gridMatrix = getGridMatrix(coord.canonical, tileBounds, latitudinalLod, tr.worldSize / tr._pixelsPerMercatorPixel);
            const normalizeMatrix = globeNormalizeECEF(globeTileBounds(coord.canonical));
            const uniformValues = globeRasterUniformValues(tr.projMatrix, globeMatrix, globeMercatorMatrix, normalizeMatrix, globeToMercatorTransition(tr.zoom), mercatorCenter, tr.frustumCorners.TL, tr.frustumCorners.TR, tr.frustumCorners.BR, tr.frustumCorners.BL, tr.globeCenterInViewSpace, tr.globeRadius, viewport, skirtHeightValue, gridMatrix);
            setShaderMode(coord, shaderMode);
            if (!program) {
                continue;
            }
            terrain.setupElevationDraw(tile, program, elevationOptions);
            painter.uploadCommonUniforms(context, program, coord.toUnwrapped());
            if (sharedBuffers) {
                const [buffer, indexBuffer, segments] = sharedBuffers.getGridBuffers(latitudinalLod, skirtHeightValue !== 0);
                program.draw(painter, primitive, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, 'globe_raster', buffer, indexBuffer, segments);
            }
        }
    }
    // Render the poles.
    if (sharedBuffers && (painter.renderDefaultNorthPole || painter.renderDefaultSouthPole)) {
        const defines = [
            'GLOBE_POLES',
            'PROJECTION_GLOBE_VIEW'
        ];
        if (useCustomAntialiasing)
            defines.push('CUSTOM_ANTIALIASING');
        program = painter.getOrCreateProgram('globeRaster', { defines });
        for (const coord of tileIDs) {
            // Fill poles by extrapolating adjacent border tiles
            const {x, y, z} = coord.canonical;
            const topCap = y === 0;
            const bottomCap = y === (1 << z) - 1;
            const [northPoleBuffer, southPoleBuffer, indexBuffer, segment] = sharedBuffers.getPoleBuffers(z, false);
            if (segment && (topCap || bottomCap)) {
                const tile = sourceCache.getTile(coord);
                // Bind the main draped texture
                context.activeTexture.set(gl.TEXTURE0);
                tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
                let poleMatrix = globePoleMatrixForTile(z, x, tr);
                const normalizeMatrix = globeNormalizeECEF(globeTileBounds(coord.canonical));
                const drawPole = (program, vertexBuffer) => program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, globeRasterUniformValues(tr.projMatrix, poleMatrix, poleMatrix, normalizeMatrix, 0, mercatorCenter, tr.frustumCorners.TL, tr.frustumCorners.TR, tr.frustumCorners.BR, tr.frustumCorners.BL, tr.globeCenterInViewSpace, tr.globeRadius, viewport, 0), 'globe_pole_raster', vertexBuffer, indexBuffer, segment);
                terrain.setupElevationDraw(tile, program, elevationOptions);
                painter.uploadCommonUniforms(context, program, coord.toUnwrapped());
                if (topCap && painter.renderDefaultNorthPole) {
                    drawPole(program, northPoleBuffer);
                }
                if (bottomCap && painter.renderDefaultSouthPole) {
                    poleMatrix = mat4_1.scale(mat4_1.create(), poleMatrix, [
                        1,
                        -1,
                        1
                    ]);
                    drawPole(program, southPoleBuffer);
                }
            }
        }
    }
}
function drawTerrainRaster(painter, terrain, sourceCache, tileIDs, now) {
    if (painter.transform.projection.name === 'globe') {
        drawTerrainForGlobe(painter, terrain, sourceCache, tileIDs, now);
    } else {
        const context = painter.context;
        const gl = context.gl;
        let program, programMode;
        const shadowRenderer = painter.shadowRenderer;
        const cutoffParams = getCutoffParams(painter, painter.longestCutoffRange);
        const setShaderMode = mode => {
            if (programMode === mode)
                return;
            const modes = [];
            modes.push(shaderDefines[mode]);
            if (cutoffParams.shouldRenderCutoff) {
                modes.push('RENDER_CUTOFF');
            }
            program = painter.getOrCreateProgram('terrainRaster', { defines: modes });
            programMode = mode;
        };
        const colorMode = painter.colorModeForRenderPass();
        const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
        vertexMorphing.update(now);
        const tr = painter.transform;
        const skirt = skirtHeight(tr.zoom, terrain.exaggeration(), terrain.sourceCache._source.tileSize);
        let groundShadowFactor = [
            0,
            0,
            0
        ];
        if (shadowRenderer) {
            const directionalLight = painter.style.directionalLight;
            const ambientLight = painter.style.ambientLight;
            if (directionalLight && ambientLight) {
                groundShadowFactor = calculateGroundShadowFactor(directionalLight, ambientLight);
            }
        }
        {
            programMode = -1;
            const primitive = gl.TRIANGLES;
            const [buffer, segments] = [
                terrain.gridIndexBuffer,
                terrain.gridSegments
            ];
            for (const coord of tileIDs) {
                const tile = sourceCache.getTile(coord);
                const stencilMode = StencilMode.disabled;
                const prevDemTile = terrain.prevTerrainTileForTile[coord.key];
                const nextDemTile = terrain.terrainTileForTile[coord.key];
                if (demTileChanged(prevDemTile, nextDemTile)) {
                    vertexMorphing.newMorphing(coord.key, prevDemTile, nextDemTile, now, defaultDuration);
                }
                // Bind the main draped texture
                context.activeTexture.set(gl.TEXTURE0);
                tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
                const morph = vertexMorphing.getMorphValuesForProxy(coord.key);
                const shaderMode = morph ? SHADER_MORPHING : SHADER_DEFAULT;
                let elevationOptions;
                if (morph) {
                    elevationOptions = {
                        morphing: {
                            srcDemTile: morph.from,
                            dstDemTile: morph.to,
                            phase: easeCubicInOut(morph.phase)
                        }
                    };
                }
                const uniformValues = terrainRasterUniformValues(coord.projMatrix, isEdgeTile(coord.canonical, tr.renderWorldCopies) ? skirt / 10 : skirt, groundShadowFactor);
                setShaderMode(shaderMode);
                if (!program) {
                    continue;
                }
                terrain.setupElevationDraw(tile, program, elevationOptions);
                const unwrappedId = coord.toUnwrapped();
                if (shadowRenderer) {
                    shadowRenderer.setupShadows(unwrappedId, program);
                }
                painter.uploadCommonUniforms(context, program, unwrappedId, null, cutoffParams);
                program.draw(painter, primitive, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, 'terrain_raster', terrain.gridBuffer, buffer, segments);
            }
        }
    }
}
function drawTerrainDepth(painter, terrain, sourceCache, tileIDs) {
    if (painter.transform.projection.name === 'globe') {
        return;
    }
    const context = painter.context;
    const gl = context.gl;
    context.clear({ depth: 1 });
    const program = painter.getOrCreateProgram('terrainDepth');
    const depthMode = new DepthMode(gl.LESS, DepthMode.ReadWrite, painter.depthRangeFor3D);
    for (const coord of tileIDs) {
        const tile = sourceCache.getTile(coord);
        const uniformValues = terrainRasterUniformValues(coord.projMatrix, 0, [
            0,
            0,
            0
        ]);
        terrain.setupElevationDraw(tile, program);
        program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.unblended, CullFaceMode.backCCW, uniformValues, 'terrain_depth', terrain.gridBuffer, terrain.gridIndexBuffer, terrain.gridNoSkirtSegments);
    }
}
function skirtHeight(zoom, terrainExaggeration, tileSize) {
    // Skirt height calculation is heuristic: provided value hides
    // seams between tiles and it is not too large: 9 at zoom 22, ~20000m at zoom 0.
    if (terrainExaggeration === 0)
        return 0;
    const exaggerationFactor = terrainExaggeration < 1 && tileSize === 514 ? 0.25 / terrainExaggeration : 1;
    return 6 * Math.pow(1.5, 22 - zoom) * Math.max(terrainExaggeration, 1) * exaggerationFactor;
}
function isEdgeTile(cid, renderWorldCopies) {
    const numTiles = 1 << cid.z;
    return !renderWorldCopies && (cid.x === 0 || cid.x === numTiles - 1) || cid.y === 0 || cid.y === numTiles - 1;
}

//      
const clippingMaskUniforms = context => ({ 'u_matrix': new UniformMatrix4f(context) });
const clippingMaskUniformValues = matrix => ({ 'u_matrix': matrix });

//      
function rasterFade(tile, parentTile, sourceCache, transform, fadeDuration) {
    if (fadeDuration > 0) {
        const now = exported$1.now();
        const sinceTile = (now - tile.timeAdded) / fadeDuration;
        const sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1;
        const source = sourceCache.getSource();
        const idealZ = transform.coveringZoomLevel({
            tileSize: source.tileSize,
            roundZoom: source.roundZoom
        });
        // if no parent or parent is older, fade in; if parent is younger, fade out
        const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ);
        const childOpacity = fadeIn && tile.refreshedUponExpiration ? 1 : clamp(fadeIn ? sinceTile : 1 - sinceParent, 0, 1);
        // we don't crossfade tiles that were just refreshed upon expiring:
        // once they're old enough to pass the crossfading threshold
        // (fadeDuration), unset the `refreshedUponExpiration` flag so we don't
        // incorrectly fail to crossfade them when zooming
        if (tile.refreshedUponExpiration && sinceTile >= 1)
            tile.refreshedUponExpiration = false;
        if (parentTile) {
            return {
                opacity: 1,
                mix: 1 - childOpacity
            };
        } else {
            return {
                opacity: childOpacity,
                mix: 0
            };
        }
    } else {
        return {
            opacity: 1,
            mix: 0
        };
    }
}

//      
const GRID_DIM = 128;
const FBO_POOL_SIZE = 5;
const RENDER_CACHE_MAX_SIZE = 50;
class MockSourceCache extends SourceCache {
    constructor(map) {
        const sourceSpec = {
            type: 'raster-dem',
            maxzoom: map.transform.maxZoom
        };
        const sourceDispatcher = new Dispatcher(getGlobalWorkerPool(), null);
        const source = create('mock-dem', sourceSpec, sourceDispatcher, map.style);
        super('mock-dem', source, false);
        source.setEventedParent(this);
        this._sourceLoaded = true;
    }
    _loadTile(tile, callback) {
        tile.state = 'loaded';
        callback(null);
    }
}
/**
 * Proxy source cache gets ideal screen tile cover coordinates. All the other
 * source caches's coordinates get mapped to subrects of proxy coordinates (or
 * vice versa, subrects of larger tiles from all source caches get mapped to
 * full proxy tile). This happens on every draw call in Terrain.updateTileBinding.
 * Approach is used here for terrain : all the visible source tiles of all the
 * source caches get rendered to proxy source cache textures and then draped over
 * terrain. It is in future reusable for handling overscalling as buckets could be
 * constructed only for proxy tile content, not for full overscalled vector tile.
 */
class ProxySourceCache extends SourceCache {
    constructor(map) {
        const source = create('proxy', {
            type: 'geojson',
            maxzoom: map.transform.maxZoom
        }, new Dispatcher(getGlobalWorkerPool(), null), map.style);
        super('proxy', source, false);
        source.setEventedParent(this);
        // This source is not to be added as a map source: we use it's tile management.
        // For that, initialize internal structures used for tile cover update.
        this.map = this.getSource().map = map;
        this.used = this._sourceLoaded = true;
        this.renderCache = [];
        this.renderCachePool = [];
        this.proxyCachedFBO = {};
    }
    // Override for transient nature of cover here: don't cache and retain.
    update(transform, tileSize, updateForTerrain) {
        // eslint-disable-line no-unused-vars
        if (transform.freezeTileCoverage) {
            return;
        }
        this.transform = transform;
        const idealTileIDs = transform.coveringTiles({
            tileSize: this._source.tileSize,
            minzoom: this._source.minzoom,
            maxzoom: this._source.maxzoom,
            roundZoom: this._source.roundZoom,
            reparseOverscaled: this._source.reparseOverscaled
        });
        const incoming = idealTileIDs.reduce((acc, tileID) => {
            acc[tileID.key] = '';
            if (!this._tiles[tileID.key]) {
                const tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), transform.tileZoom);
                tile.state = 'loaded';
                this._tiles[tileID.key] = tile;
            }
            return acc;
        }, {});
        for (const id in this._tiles) {
            if (!(id in incoming)) {
                this.freeFBO(id);
                this._tiles[id].unloadVectorData();
                delete this._tiles[id];
            }
        }
    }
    freeFBO(id) {
        const fbos = this.proxyCachedFBO[id];
        if (fbos !== undefined) {
            const fboIds = Object.values(fbos);
            this.renderCachePool.push(...fboIds);
            delete this.proxyCachedFBO[id];
        }
    }
    deallocRenderCache() {
        this.renderCache.forEach(fbo => fbo.fb.destroy());
        this.renderCache = [];
        this.renderCachePool = [];
        this.proxyCachedFBO = {};
    }
}
/**
 * Canonical, wrap and overscaledZ contain information of original source cache tile.
 * This tile gets ortho-rendered to proxy tile (defined by proxyTileKey).
 * `posMatrix` holds orthographic, scaling and translation information that is used
 * for rendering original tile content to a proxy tile. Proxy tile covers whole
 * or sub-rectangle of the original tile.
 */
class ProxiedTileID extends OverscaledTileID {
    constructor(tileID, proxyTileKey, projMatrix) {
        super(tileID.overscaledZ, tileID.wrap, tileID.canonical.z, tileID.canonical.x, tileID.canonical.y);
        this.proxyTileKey = proxyTileKey;
        this.projMatrix = projMatrix;
    }
}
class Terrain extends Elevation {
    constructor(painter, style) {
        super();
        this.painter = painter;
        this.terrainTileForTile = {};
        this.prevTerrainTileForTile = {};
        // Terrain rendering grid is 129x129 cell grid, made by 130x130 points.
        // 130 vertices map to 128 DEM data + 1px padding on both sides.
        // DEM texture is padded (1, 1, 1, 1) and padding pixels are backfilled
        // by neighboring tile edges. This way we achieve tile stitching as
        // edge vertices from neighboring tiles evaluate to the same 3D point.
        const [triangleGridArray, triangleGridIndices, skirtIndicesOffset] = createGrid(GRID_DIM + 1);
        const context = painter.context;
        this.gridBuffer = context.createVertexBuffer(triangleGridArray, posAttributes.members);
        this.gridIndexBuffer = context.createIndexBuffer(triangleGridIndices);
        this.gridSegments = SegmentVector.simpleSegment(0, 0, triangleGridArray.length, triangleGridIndices.length);
        this.gridNoSkirtSegments = SegmentVector.simpleSegment(0, 0, triangleGridArray.length, skirtIndicesOffset);
        this.proxyCoords = [];
        this.proxiedCoords = {};
        this._visibleDemTiles = [];
        this._drapedRenderBatches = [];
        this._sourceTilesOverlap = {};
        this.proxySourceCache = new ProxySourceCache(style.map);
        this.orthoMatrix = mat4_1.create();
        const epsilon = this.painter.transform.projection.name === 'globe' ? 0.015 : 0;
        // Experimentally the smallest value to avoid rendering artifacts (https://github.com/mapbox/mapbox-gl-js/issues/11975)
        mat4_1.ortho(this.orthoMatrix, epsilon, EXTENT, 0, EXTENT, 0, 1);
        const gl = context.gl;
        this._overlapStencilMode = new StencilMode({
            func: gl.GEQUAL,
            mask: 255
        }, 0, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
        this._previousZoom = painter.transform.zoom;
        this.pool = [];
        this._findCoveringTileCache = {};
        this._tilesDirty = {};
        this.style = style;
        this._useVertexMorphing = true;
        this._exaggeration = 1;
        this._mockSourceCache = new MockSourceCache(style.map);
        this._pendingGroundEffectLayers = [];
    }
    set style(style) {
        // $FlowFixMe[method-unbinding]
        style.on('data', this._onStyleDataEvent.bind(this));
        // $FlowFixMe[method-unbinding]
        this._style = style;
        this._style.map.on('moveend', () => {
            this._clearLineLayersFromRenderCache();
        });
    }
    /*
     * Validate terrain and update source cache used for elevation.
     * Explicitly pass transform to update elevation (Transform.updateElevation)
     * before using transform for source cache update.
     */
    update(style, transform, adaptCameraAltitude) {
        if (style && style.terrain) {
            if (this._style !== style) {
                this.style = style;
                this._evaluationZoom = undefined;
            }
            const terrainProps = style.terrain.properties;
            const isDrapeModeDeferred = style.terrain.drapeRenderMode === DrapeRenderMode.deferred;
            const zoomDependentExaggeration = style.terrain.isZoomDependent();
            this._previousUpdateTimestamp = this.enabled ? this._updateTimestamp : undefined;
            this._updateTimestamp = exported$1.now();
            const scope = style.terrain && style.terrain.scope;
            const sourceCacheId = terrainProps.get('source');
            const sourceCache = isDrapeModeDeferred ? this._mockSourceCache : style.getSourceCache(sourceCacheId, scope);
            if (!sourceCache) {
                warnOnce(`Couldn't find terrain source "${ sourceCacheId }".`);
                return;
            }
            this.sourceCache = sourceCache;
            this._exaggeration = zoomDependentExaggeration ? this.calculateExaggeration(transform) : terrainProps.get('exaggeration');
            if (!transform.projection.requiresDraping && zoomDependentExaggeration && this._exaggeration === 0) {
                this._disable();
                return;
            }
            this.enabled = true;
            const updateSourceCache = () => {
                if (this.sourceCache.used) {
                    warnOnce(`Raster DEM source '${ this.sourceCache.id }' is used both for terrain and as layer source.\n` + 'This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.');
                }
                // Lower tile zoom is sufficient for terrain, given the size of terrain grid.
                const scaledDemTileSize = this.getScaledDemTileSize();
                // Dem tile needs to be parent or at least of the same zoom level as proxy tile.
                // Tile cover roundZoom behavior is set to the same as for proxy (false) in SourceCache.update().
                this.sourceCache.update(transform, scaledDemTileSize, true);
                // As a result of update, we get new set of tiles: reset lookup cache.
                this.resetTileLookupCache(this.sourceCache.id);
            };
            if (!this.sourceCache.usedForTerrain) {
                // Init cache entry.
                this.resetTileLookupCache(this.sourceCache.id);
                // When toggling terrain on/off load available terrain tiles from cache
                // before reading elevation at center.
                this.sourceCache.usedForTerrain = true;
                updateSourceCache();
                this._initializing = true;
            }
            updateSourceCache();
            // Camera gets constrained over terrain. Issue constrainCameraOverTerrain = true
            // here to cover potential under terrain situation on data, style, or other camera changes.
            transform.updateElevation(true, adaptCameraAltitude);
            // Reset tile lookup cache and update draped tiles coordinates.
            this.resetTileLookupCache(this.proxySourceCache.id);
            this.proxySourceCache.update(transform);
            this._emptyDEMTextureDirty = true;
            this._previousZoom = transform.zoom;
        } else {
            this._disable();
        }
    }
    calculateExaggeration(transform) {
        const previousAltitude = this._previousCameraAltitude;
        const altitude = transform.getFreeCameraOptions().position.z / transform.pixelsPerMeter * transform.worldSize;
        this._previousCameraAltitude = altitude;
        // 2 meters as threshold for constant sea elevation movement.
        const altitudeDelta = previousAltitude != null ? altitude - previousAltitude : Number.MAX_VALUE;
        if (Math.abs(altitudeDelta) < 2) {
            // Returns current value and avoids any unpleasant terrain change.
            return this._exaggeration;
        }
        const cameraZoom = transform.zoom;
        const terrainStyle = this._style.terrain;
        if (!this._previousUpdateTimestamp) {
            // covers also 0 (timestamp in render tests is 0).
            return terrainStyle.getExaggeration(cameraZoom);
        }
        let zoomDelta = cameraZoom - this._previousZoom;
        const previousUpdateTimestamp = this._previousUpdateTimestamp;
        let z = cameraZoom;
        if (this._evaluationZoom != null) {
            z = this._evaluationZoom;
            // incorporate any difference of _evaluationZoom and real zoom here.
            // Smoothening below resolves flicker.
            if (Math.abs(cameraZoom - z) > 0.5) {
                zoomDelta = 0.5 * (cameraZoom - z + zoomDelta);
            }
            if (zoomDelta * altitudeDelta < 0) {
                // if they have different sign, e.g. zooming in and recenter calculates lower zoom, do not advance.
                z += zoomDelta;
            }
        }
        this._evaluationZoom = z;
        const evaluatedExaggeration = terrainStyle.getExaggeration(z);
        // evaluate if we are in area with fixed exaggeration. 0.1 is random - idea is to
        // interpolate faster to desired value.
        const evaluatedExaggerationLowerZ = terrainStyle.getExaggeration(Math.max(0, z - 0.1));
        const fixedExaggeration = evaluatedExaggeration === evaluatedExaggerationLowerZ;
        const lowExaggerationTreshold = 0.1;
        const exaggerationSmoothTarget = 0.01;
        if (fixedExaggeration && Math.abs(evaluatedExaggeration - this._exaggeration) < exaggerationSmoothTarget) {
            return evaluatedExaggeration;
        }
        // smoothen the changes further to reduce flickering
        let interpolateStrength = Math.min(0.1, (this._updateTimestamp - previousUpdateTimestamp) * 0.00375);
        // Empiric value, e.g. ~0.06 at 60 FPS
        if (fixedExaggeration || evaluatedExaggeration < lowExaggerationTreshold || Math.abs(zoomDelta) < 0.0001) {
            // interpolate faster, when out of dynamic exaggeration range, near zero or when zooming out/in stops.
            interpolateStrength = Math.min(0.2, interpolateStrength * 4);
        }
        return number(this._exaggeration, evaluatedExaggeration, interpolateStrength);
    }
    resetTileLookupCache(sourceCacheID) {
        this._findCoveringTileCache[sourceCacheID] = {};
    }
    getScaledDemTileSize() {
        const demScale = this.sourceCache.getSource().tileSize / GRID_DIM;
        const proxyTileSize = this.proxySourceCache.getSource().tileSize;
        return demScale * proxyTileSize;
    }
    _onStyleDataEvent(event) {
        if (event.coord && event.dataType === 'source') {
            this._clearRenderCacheForTile(event.sourceCacheId, event.coord);
        } else if (event.dataType === 'style') {
            this.invalidateRenderCache = true;
            this._evaluationZoom = undefined;
            this._previousUpdateTimestamp = undefined;
            this._previousCameraAltitude = undefined;
        }
    }
    // Terrain
    _disable() {
        if (!this.enabled)
            return;
        this.enabled = false;
        this._sharedDepthStencil = undefined;
        this._evaluationZoom = undefined;
        this._previousUpdateTimestamp = undefined;
        this.proxySourceCache.deallocRenderCache();
        if (this._style) {
            for (const id in this._style._mergedSourceCaches) {
                this._style._mergedSourceCaches[id].usedForTerrain = false;
            }
        }
    }
    destroy() {
        this._disable();
        if (this._emptyDEMTexture)
            this._emptyDEMTexture.destroy();
        if (this._emptyDepthBufferTexture)
            this._emptyDepthBufferTexture.destroy();
        this.pool.forEach(fbo => fbo.fb.destroy());
        this.pool = [];
        if (this._depthFBO) {
            this._depthFBO.destroy();
            this._depthFBO = undefined;
            this._depthTexture = undefined;
        }
        if (this.framebufferCopyTexture)
            this.framebufferCopyTexture.destroy();
    }
    // Implements Elevation::_source.
    _source() {
        return this.enabled ? this.sourceCache : null;
    }
    isUsingMockSource() {
        return this.sourceCache === this._mockSourceCache;
    }
    // Implements Elevation::exaggeration.
    exaggeration() {
        return this._exaggeration;
    }
    get visibleDemTiles() {
        return this._visibleDemTiles;
    }
    get drapeBufferSize() {
        const extent = this.proxySourceCache.getSource().tileSize * 2;
        // *2 is to avoid upscaling bitmap on zoom.
        return [
            extent,
            extent
        ];
    }
    set useVertexMorphing(enable) {
        this._useVertexMorphing = enable;
    }
    // For every renderable coordinate in every source cache, assign one proxy
    // tile (see _setupProxiedCoordsForOrtho). Mapping of source tile to proxy
    // tile is modeled by ProxiedTileID. In general case, source and proxy tile
    // are of different zoom: ProxiedTileID.projMatrix models ortho, scale and
    // translate from source to proxy. This matrix is used when rendering source
    // tile to proxy tile's texture.
    // One proxy tile can have multiple source tiles, or pieces of source tiles,
    // that get rendered to it.
    // For each proxy tile we assign one terrain tile (_assignTerrainTiles). The
    // terrain tile provides elevation data when rendering (draping) proxy tile
    // texture over terrain grid.
    updateTileBinding(sourcesCoords) {
        if (!this.enabled)
            return;
        this.prevTerrainTileForTile = this.terrainTileForTile;
        const proxySourceCache = this.proxySourceCache;
        const tr = this.painter.transform;
        if (this._initializing) {
            // Don't activate terrain until center tile gets loaded.
            this._initializing = tr._centerAltitude === 0 && this.getAtPointOrZero(MercatorCoordinate.fromLngLat(tr.center), -1) === -1;
            this._emptyDEMTextureDirty = !this._initializing;
        }
        const coords = this.proxyCoords = proxySourceCache.getIds().map(id => {
            const tileID = proxySourceCache.getTileByID(id).tileID;
            tileID.projMatrix = tr.calculateProjMatrix(tileID.toUnwrapped());
            return tileID;
        });
        sortByDistanceToCamera(coords, this.painter);
        const previousProxyToSource = this.proxyToSource || {};
        this.proxyToSource = {};
        coords.forEach(tileID => {
            this.proxyToSource[tileID.key] = {};
        });
        this.terrainTileForTile = {};
        const sourceCaches = this._style._mergedSourceCaches;
        for (const fqid in sourceCaches) {
            const sourceCache = sourceCaches[fqid];
            if (!sourceCache.used)
                continue;
            if (sourceCache !== this.sourceCache)
                this.resetTileLookupCache(sourceCache.id);
            this._setupProxiedCoordsForOrtho(sourceCache, sourcesCoords[fqid], previousProxyToSource);
            if (sourceCache.usedForTerrain)
                continue;
            const coordinates = sourcesCoords[fqid];
            if (sourceCache.getSource().reparseOverscaled) {
                // Do this for layers that are not rasterized to proxy tile.
                this._assignTerrainTiles(coordinates);
            }
        }
        // Background has no source. Using proxy coords with 1-1 ortho (this.proxiedCoords[proxySourceCache.id])
        // when rendering background to proxy tiles.
        this.proxiedCoords[proxySourceCache.id] = coords.map(tileID => new ProxiedTileID(tileID, tileID.key, this.orthoMatrix));
        this._assignTerrainTiles(coords);
        this._prepareDEMTextures();
        this._setupDrapedRenderBatches();
        this._initFBOPool();
        this._setupRenderCache(previousProxyToSource);
        this.renderingToTexture = false;
        // Gather all dem tiles that are assigned to proxy tiles
        const visibleKeys = {};
        this._visibleDemTiles = [];
        for (const id of this.proxyCoords) {
            const demTile = this.terrainTileForTile[id.key];
            if (!demTile)
                continue;
            const key = demTile.tileID.key;
            if (key in visibleKeys)
                continue;
            this._visibleDemTiles.push(demTile);
            visibleKeys[key] = key;
        }
    }
    _assignTerrainTiles(coords) {
        if (this._initializing)
            return;
        coords.forEach(tileID => {
            if (this.terrainTileForTile[tileID.key])
                return;
            const demTile = this._findTileCoveringTileID(tileID, this.sourceCache);
            if (demTile)
                this.terrainTileForTile[tileID.key] = demTile;
        });
    }
    _prepareDEMTextures() {
        const context = this.painter.context;
        const gl = context.gl;
        for (const key in this.terrainTileForTile) {
            const tile = this.terrainTileForTile[key];
            const dem = tile.dem;
            if (dem && (!tile.demTexture || tile.needsDEMTextureUpload)) {
                context.activeTexture.set(gl.TEXTURE1);
                prepareDEMTexture(this.painter, tile, dem);
            }
        }
    }
    _prepareDemTileUniforms(proxyTile, demTile, uniforms, uniformSuffix) {
        if (!demTile || demTile.demTexture == null)
            return false;
        const proxyId = proxyTile.tileID.canonical;
        const demId = demTile.tileID.canonical;
        const demScaleBy = Math.pow(2, demId.z - proxyId.z);
        const suffix = uniformSuffix || '';
        // $FlowFixMe[prop-missing]
        uniforms[`u_dem_tl${ suffix }`] = [
            proxyId.x * demScaleBy % 1,
            proxyId.y * demScaleBy % 1
        ];
        // $FlowFixMe[prop-missing]
        uniforms[`u_dem_scale${ suffix }`] = demScaleBy;
        return true;
    }
    get emptyDEMTexture() {
        return !this._emptyDEMTextureDirty && this._emptyDEMTexture ? this._emptyDEMTexture : this._updateEmptyDEMTexture();
    }
    get emptyDepthBufferTexture() {
        const context = this.painter.context;
        const gl = context.gl;
        if (!this._emptyDepthBufferTexture) {
            const image = new RGBAImage({
                width: 1,
                height: 1
            }, Uint8Array.of(255, 255, 255, 255));
            this._emptyDepthBufferTexture = new Texture(context, image, gl.RGBA, { premultiply: false });
        }
        return this._emptyDepthBufferTexture;
    }
    _getLoadedAreaMinimum() {
        let nonzero = 0;
        const min = this._visibleDemTiles.reduce((acc, tile) => {
            if (!tile.dem)
                return acc;
            const m = tile.dem.tree.minimums[0];
            acc += m;
            if (m > 0)
                nonzero++;
            return acc;
        }, 0);
        return nonzero ? min / nonzero : 0;
    }
    _updateEmptyDEMTexture() {
        const context = this.painter.context;
        const gl = context.gl;
        context.activeTexture.set(gl.TEXTURE2);
        const min = this._getLoadedAreaMinimum();
        const getTextureParameters = () => {
            if (this.painter.terrainUseFloatDEM()) {
                const image = new Float32Image({
                    width: 1,
                    height: 1
                }, new Float32Array([min]));
                return [
                    gl.R32F,
                    image
                ];
            } else {
                const image = new RGBAImage({
                    width: 1,
                    height: 1
                }, new Uint8Array(DEMData.pack(min, this.sourceCache.getSource().encoding)));
                return [
                    gl.RGBA,
                    image
                ];
            }
        };
        const [internalFormat, image] = getTextureParameters();
        this._emptyDEMTextureDirty = false;
        let texture = this._emptyDEMTexture;
        if (!texture) {
            texture = this._emptyDEMTexture = new Texture(context, image, internalFormat, { premultiply: false });
        } else {
            texture.update(image, { premultiply: false });
        }
        return texture;
    }
    // useDepthForOcclusion: Pre-rendered depth to texture (this._depthTexture) is
    // used to hide (actually moves all object's vertices out of viewport).
    // useMeterToDem: u_meter_to_dem uniform is not used for all terrain programs,
    // optimization to avoid unnecessary computation and upload.
    setupElevationDraw(tile, program, options) {
        const context = this.painter.context;
        const gl = context.gl;
        const uniforms = defaultTerrainUniforms(this.sourceCache.getSource().encoding);
        uniforms['u_exaggeration'] = this.exaggeration();
        let demTile = null;
        let prevDemTile = null;
        let morphingPhase = 1;
        if (options && options.morphing && this._useVertexMorphing) {
            const srcTile = options.morphing.srcDemTile;
            const dstTile = options.morphing.dstDemTile;
            morphingPhase = options.morphing.phase;
            if (srcTile && dstTile) {
                if (this._prepareDemTileUniforms(tile, srcTile, uniforms, '_prev'))
                    prevDemTile = srcTile;
                if (this._prepareDemTileUniforms(tile, dstTile, uniforms))
                    demTile = dstTile;
            }
        }
        const filteringForDemTile = tile => {
            if (!tile || !tile.demTexture) {
                return gl.NEAREST;
            }
            return this.painter.terrainUseFloatDEM() ? gl.LINEAR : gl.NEAREST;
        };
        const setDemSizeUniform = demTexture => {
            uniforms['u_dem_size'] = demTexture.size[0] === 1 ? 1 : demTexture.size[0] - 2;
        };
        if (prevDemTile && demTile) {
            // Both DEM textures are expected to be correctly set if geomorphing is enabled
            context.activeTexture.set(gl.TEXTURE2);
            demTile.demTexture.bind(filteringForDemTile(demTile), gl.CLAMP_TO_EDGE);
            context.activeTexture.set(gl.TEXTURE4);
            prevDemTile.demTexture.bind(filteringForDemTile(prevDemTile), gl.CLAMP_TO_EDGE);
            if (demTile.demTexture) {
                setDemSizeUniform(demTile.demTexture);
            }
            uniforms['u_dem_lerp'] = morphingPhase;
        } else {
            demTile = this.terrainTileForTile[tile.tileID.key];
            context.activeTexture.set(gl.TEXTURE2);
            const demTexture = this._prepareDemTileUniforms(tile, demTile, uniforms) ? demTile.demTexture : this.emptyDEMTexture;
            demTexture.bind(filteringForDemTile(demTile), gl.CLAMP_TO_EDGE);
            setDemSizeUniform(demTexture);
        }
        context.activeTexture.set(gl.TEXTURE3);
        if (options && options.useDepthForOcclusion) {
            if (this._depthTexture)
                this._depthTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
            if (this._depthFBO)
                uniforms['u_depth_size_inv'] = [
                    1 / this._depthFBO.width,
                    1 / this._depthFBO.height
                ];
        } else {
            this.emptyDepthBufferTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
            uniforms['u_depth_size_inv'] = [
                1,
                1
            ];
        }
        if (options && options.useMeterToDem && demTile) {
            const meterToDEM = (1 << demTile.tileID.canonical.z) * mercatorZfromAltitude(1, this.painter.transform.center.lat) * this.sourceCache.getSource().tileSize;
            uniforms['u_meter_to_dem'] = meterToDEM;
        }
        if (options && options.labelPlaneMatrixInv) {
            uniforms['u_label_plane_matrix_inv'] = options.labelPlaneMatrixInv;
        }
        program.setTerrainUniformValues(context, uniforms);
        if (this.painter.transform.projection.name === 'globe') {
            const globeUniforms = this.globeUniformValues(this.painter.transform, tile.tileID.canonical, options && options.useDenormalizedUpVectorScale);
            program.setGlobeUniformValues(context, globeUniforms);
        }
    }
    globeUniformValues(tr, id, useDenormalizedUpVectorScale) {
        const projection = tr.projection;
        return {
            'u_tile_tl_up': projection.upVector(id, 0, 0),
            'u_tile_tr_up': projection.upVector(id, EXTENT, 0),
            'u_tile_br_up': projection.upVector(id, EXTENT, EXTENT),
            'u_tile_bl_up': projection.upVector(id, 0, EXTENT),
            'u_tile_up_scale': useDenormalizedUpVectorScale ? globeMetersToEcef(1) : projection.upVectorScale(id, tr.center.lat, tr.worldSize).metersToTile
        };
    }
    renderToBackBuffer(accumulatedDrapes) {
        const painter = this.painter;
        const context = this.painter.context;
        if (accumulatedDrapes.length === 0) {
            return;
        }
        context.bindFramebuffer.set(null);
        context.viewport.set([
            0,
            0,
            painter.width,
            painter.height
        ]);
        painter.gpuTimingDeferredRenderStart();
        this.renderingToTexture = false;
        drawTerrainRaster(painter, this, this.proxySourceCache, accumulatedDrapes, this._updateTimestamp);
        this.renderingToTexture = true;
        painter.gpuTimingDeferredRenderEnd();
        accumulatedDrapes.splice(0, accumulatedDrapes.length);
    }
    // For each proxy tile, render all layers until the non-draped layer (and
    // render the tile to the screen) before advancing to the next proxy tile.
    // Returns the last drawn index that is used as a start
    // layer for interleaved draped rendering.
    // Apart to layer-by-layer rendering used in 2D, here we have proxy-tile-by-proxy-tile
    // rendering.
    renderBatch(startLayerIndex) {
        if (this._drapedRenderBatches.length === 0) {
            return startLayerIndex + 1;
        }
        this.renderingToTexture = true;
        const painter = this.painter;
        const context = this.painter.context;
        const proxySourceCache = this.proxySourceCache;
        const proxies = this.proxiedCoords[proxySourceCache.id];
        // Consume batch of sequential drape layers and move next
        const drapedLayerBatch = this._drapedRenderBatches.shift();
        const layerIds = painter.style.order;
        const accumulatedDrapes = [];
        let poolIndex = 0;
        for (const proxy of proxies) {
            // bind framebuffer and assign texture to the tile (texture used in drawTerrainRaster).
            const tile = proxySourceCache.getTileByID(proxy.proxyTileKey);
            const renderCacheIndex = proxySourceCache.proxyCachedFBO[proxy.key] ? proxySourceCache.proxyCachedFBO[proxy.key][startLayerIndex] : undefined;
            const fbo = renderCacheIndex !== undefined ? proxySourceCache.renderCache[renderCacheIndex] : this.pool[poolIndex++];
            const useRenderCache = renderCacheIndex !== undefined;
            tile.texture = fbo.tex;
            if (useRenderCache && !fbo.dirty) {
                // Use cached render from previous pass, no need to render again.
                accumulatedDrapes.push(tile.tileID);
                continue;
            }
            context.bindFramebuffer.set(fbo.fb.framebuffer);
            this.renderedToTile = false;
            // reset flag.
            if (fbo.dirty) {
                // Clear on start.
                context.clear({
                    color: Color$1.transparent,
                    stencil: 0
                });
                fbo.dirty = false;
            }
            let currentStencilSource;
            // There is no need to setup stencil for the same source for consecutive layers.
            for (let j = drapedLayerBatch.start; j <= drapedLayerBatch.end; ++j) {
                const layer = painter.style._mergedLayers[layerIds[j]];
                const hidden = layer.isHidden(painter.transform.zoom);
                if (hidden)
                    continue;
                const sourceCache = painter.style.getLayerSourceCache(layer);
                const proxiedCoords = sourceCache ? this.proxyToSource[proxy.key][sourceCache.id] : [proxy];
                if (!proxiedCoords)
                    continue;
                // when tile is not loaded yet for the source cache.
                const coords = proxiedCoords;
                context.viewport.set([
                    0,
                    0,
                    fbo.fb.width,
                    fbo.fb.height
                ]);
                if (currentStencilSource !== (sourceCache ? sourceCache.id : null)) {
                    this._setupStencil(fbo, proxiedCoords, layer, sourceCache);
                    currentStencilSource = sourceCache ? sourceCache.id : null;
                }
                painter.renderLayer(painter, sourceCache, layer, coords);
            }
            const isLastBatch = this._drapedRenderBatches.length === 0;
            if (isLastBatch) {
                for (const id of this._pendingGroundEffectLayers) {
                    const layer = painter.style._mergedLayers[layerIds[id]];
                    if (layer.isHidden(painter.transform.zoom))
                        continue;
                    const sourceCache = painter.style.getLayerSourceCache(layer);
                    const proxiedCoords = sourceCache ? this.proxyToSource[proxy.key][sourceCache.id] : [proxy];
                    if (!proxiedCoords)
                        continue;
                    const coords = proxiedCoords;
                    context.viewport.set([
                        0,
                        0,
                        fbo.fb.width,
                        fbo.fb.height
                    ]);
                    if (currentStencilSource !== (sourceCache ? sourceCache.id : null)) {
                        this._setupStencil(fbo, proxiedCoords, layer, sourceCache);
                        currentStencilSource = sourceCache ? sourceCache.id : null;
                    }
                    painter.renderLayer(painter, sourceCache, layer, coords);
                }
            }
            if (this.renderedToTile) {
                fbo.dirty = true;
                accumulatedDrapes.push(tile.tileID);
            } else if (!useRenderCache) {
                --poolIndex;
            }
            if (poolIndex === FBO_POOL_SIZE) {
                poolIndex = 0;
                this.renderToBackBuffer(accumulatedDrapes);
            }
        }
        // Reset states and render last drapes
        this.renderToBackBuffer(accumulatedDrapes);
        this.renderingToTexture = false;
        context.bindFramebuffer.set(null);
        context.viewport.set([
            0,
            0,
            painter.width,
            painter.height
        ]);
        return drapedLayerBatch.end + 1;
    }
    postRender() {
    }
    isLayerOrderingCorrect(style) {
        const layerCount = style.order.length;
        let drapedMax = -1;
        let immediateMin = layerCount;
        for (let i = 0; i < layerCount; ++i) {
            const layer = style._mergedLayers[style.order[i]];
            if (this._style.isLayerDraped(layer)) {
                drapedMax = Math.max(drapedMax, i);
            } else {
                immediateMin = Math.min(immediateMin, i);
            }
        }
        return immediateMin > drapedMax;
    }
    getMinElevationBelowMSL() {
        let min = 0;
        // The maximum DEM error in meters to be conservative (SRTM).
        const maxDEMError = 30;
        this._visibleDemTiles.filter(tile => tile.dem).forEach(tile => {
            const minMaxTree = tile.dem.tree;
            min = Math.min(min, minMaxTree.minimums[0]);
        });
        return min === 0 ? min : (min - maxDEMError) * this._exaggeration;
    }
    // Performs raycast against visible DEM tiles on the screen and returns the distance travelled along the ray.
    // x & y components of the position are expected to be in normalized mercator coordinates [0, 1] and z in meters.
    raycast(pos, dir, exaggeration) {
        if (!this._visibleDemTiles)
            return null;
        // Perform initial raycasts against root nodes of the available dem tiles
        // and use this information to sort them from closest to furthest.
        const preparedTiles = this._visibleDemTiles.filter(tile => tile.dem).map(tile => {
            const id = tile.tileID;
            const tiles = 1 << id.overscaledZ;
            const {x, y} = id.canonical;
            // Compute tile boundaries in mercator coordinates
            const minx = x / tiles;
            const maxx = (x + 1) / tiles;
            const miny = y / tiles;
            const maxy = (y + 1) / tiles;
            const tree = tile.dem.tree;
            return {
                minx,
                miny,
                maxx,
                maxy,
                t: tree.raycastRoot(minx, miny, maxx, maxy, pos, dir, exaggeration),
                tile
            };
        });
        preparedTiles.sort((a, b) => {
            const at = a.t !== null ? a.t : Number.MAX_VALUE;
            const bt = b.t !== null ? b.t : Number.MAX_VALUE;
            return at - bt;
        });
        for (const obj of preparedTiles) {
            if (obj.t == null)
                return null;
            // Perform more accurate raycast against the dem tree. First intersection is the closest on
            // as all tiles are sorted from closest to furthest
            const tree = obj.tile.dem.tree;
            const t = tree.raycast(obj.minx, obj.miny, obj.maxx, obj.maxy, pos, dir, exaggeration);
            if (t != null)
                return t;
        }
        return null;
    }
    _createFBO() {
        const painter = this.painter;
        const context = painter.context;
        const gl = context.gl;
        const bufferSize = this.drapeBufferSize;
        context.activeTexture.set(gl.TEXTURE0);
        const tex = new Texture(context, {
            width: bufferSize[0],
            height: bufferSize[1],
            data: null
        }, gl.RGBA);
        tex.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        const fb = context.createFramebuffer(bufferSize[0], bufferSize[1], true, null);
        fb.colorAttachment.set(tex.texture);
        fb.depthAttachment = new DepthStencilAttachment(context, fb.framebuffer);
        if (this._sharedDepthStencil === undefined) {
            this._sharedDepthStencil = context.createRenderbuffer(context.gl.DEPTH_STENCIL, bufferSize[0], bufferSize[1]);
            this._stencilRef = 0;
            fb.depthAttachment.set(this._sharedDepthStencil);
            context.clear({ stencil: 0 });
        } else {
            fb.depthAttachment.set(this._sharedDepthStencil);
        }
        if (context.extTextureFilterAnisotropic && !context.extTextureFilterAnisotropicForceOff) {
            gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
        }
        return {
            fb,
            tex,
            dirty: false
        };
    }
    _initFBOPool() {
        while (this.pool.length < Math.min(FBO_POOL_SIZE, this.proxyCoords.length)) {
            this.pool.push(this._createFBO());
        }
    }
    _shouldDisableRenderCache() {
        // Disable render caches on dynamic events due to fading or transitioning.
        if (this._style.hasLightTransitions()) {
            return true;
        }
        for (const id in this._style._mergedSourceCaches) {
            if (this._style._mergedSourceCaches[id].hasTransition()) {
                return true;
            }
        }
        const isTransitioning = id => {
            const layer = this._style._mergedLayers[id];
            const isHidden = layer.isHidden(this.painter.transform.zoom);
            if (layer.type === 'custom') {
                return !isHidden && layer.shouldRedrape();
            }
            return !isHidden && layer.hasTransition();
        };
        return this._style.order.some(isTransitioning);
    }
    _clearLineLayersFromRenderCache() {
        let hasVectorSource = false;
        for (const source of this._style.getSources()) {
            if (source instanceof VectorTileSource) {
                hasVectorSource = true;
                break;
            }
        }
        if (!hasVectorSource)
            return;
        const clearSourceCaches = {};
        for (let i = 0; i < this._style.order.length; ++i) {
            const layer = this._style._mergedLayers[this._style.order[i]];
            const sourceCache = this._style.getLayerSourceCache(layer);
            if (!sourceCache || clearSourceCaches[sourceCache.id])
                continue;
            const isHidden = layer.isHidden(this.painter.transform.zoom);
            if (isHidden || layer.type !== 'line')
                continue;
            // Check if layer has a zoom dependent "line-width" expression
            const widthExpression = layer.widthExpression();
            if (!(widthExpression instanceof ZoomDependentExpression))
                continue;
            // Mark sourceCache as cleared
            clearSourceCaches[sourceCache.id] = true;
            for (const proxy of this.proxyCoords) {
                const proxiedCoords = this.proxyToSource[proxy.key][sourceCache.id];
                const coords = proxiedCoords;
                if (!coords)
                    continue;
                for (const coord of coords) {
                    this._clearRenderCacheForTile(sourceCache.id, coord);
                }
            }
        }
    }
    _clearRasterLayersFromRenderCache() {
        let hasRasterSource = false;
        for (const id in this._style._mergedSourceCaches) {
            if (this._style._mergedSourceCaches[id]._source instanceof RasterTileSource) {
                hasRasterSource = true;
                break;
            }
        }
        if (!hasRasterSource)
            return;
        const clearSourceCaches = {};
        for (let i = 0; i < this._style.order.length; ++i) {
            const layer = this._style._mergedLayers[this._style.order[i]];
            const sourceCache = this._style.getLayerSourceCache(layer);
            if (!sourceCache || clearSourceCaches[sourceCache.id])
                continue;
            const isHidden = layer.isHidden(this.painter.transform.zoom);
            if (isHidden || layer.type !== 'raster')
                continue;
            // Check if any raster tile is in a fading state
            const fadeDuration = layer.paint.get('raster-fade-duration');
            for (const proxy of this.proxyCoords) {
                const proxiedCoords = this.proxyToSource[proxy.key][sourceCache.id];
                const coords = proxiedCoords;
                if (!coords)
                    continue;
                for (const coord of coords) {
                    const tile = sourceCache.getTile(coord);
                    const parent = sourceCache.findLoadedParent(coord, 0);
                    const fade = rasterFade(tile, parent, sourceCache, this.painter.transform, fadeDuration);
                    const isFading = fade.opacity !== 1 || fade.mix !== 0;
                    if (isFading) {
                        this._clearRenderCacheForTile(sourceCache.id, coord);
                    }
                }
            }
        }
    }
    _setupDrapedRenderBatches() {
        const layerIds = this._style.order;
        const layerCount = layerIds.length;
        if (layerCount === 0) {
            return;
        }
        const batches = [];
        this._pendingGroundEffectLayers = [];
        let currentLayer = 0;
        let layer = this._style._mergedLayers[layerIds[currentLayer]];
        while (!this._style.isLayerDraped(layer) && layer.isHidden(this.painter.transform.zoom) && ++currentLayer < layerCount) {
            layer = this._style._mergedLayers[layerIds[currentLayer]];
        }
        let batchStart;
        for (; currentLayer < layerCount; ++currentLayer) {
            const layer = this._style._mergedLayers[layerIds[currentLayer]];
            if (layer.isHidden(this.painter.transform.zoom)) {
                continue;
            }
            if (!this._style.isLayerDraped(layer)) {
                if (layer.type === 'fill-extrusion') {
                    this._pendingGroundEffectLayers.push(currentLayer);
                }
                if (batchStart !== undefined) {
                    batches.push({
                        start: batchStart,
                        end: currentLayer - 1
                    });
                    batchStart = undefined;
                }
                continue;
            }
            if (batchStart === undefined) {
                batchStart = currentLayer;
            }
        }
        if (batchStart !== undefined) {
            batches.push({
                start: batchStart,
                end: currentLayer - 1
            });
        }
        if (batches.length !== 0) {
            const lastBatch = batches[batches.length - 1];
            const groundEffectLayersComeLast = this._pendingGroundEffectLayers.every(id => {
                return id > lastBatch.end;
            });
            if (!groundEffectLayersComeLast) {
                warnOnce('fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.');
            }
        }
        this._drapedRenderBatches = batches;
    }
    _setupRenderCache(previousProxyToSource) {
        const psc = this.proxySourceCache;
        if (this._shouldDisableRenderCache() || this.invalidateRenderCache) {
            this.invalidateRenderCache = false;
            if (psc.renderCache.length > psc.renderCachePool.length) {
                const used = Object.values(psc.proxyCachedFBO);
                psc.proxyCachedFBO = {};
                for (let i = 0; i < used.length; ++i) {
                    const fbos = Object.values(used[i]);
                    psc.renderCachePool.push(...fbos);
                }
            }
            return;
        }
        this._clearRasterLayersFromRenderCache();
        const coords = this.proxyCoords;
        const dirty = this._tilesDirty;
        for (let i = coords.length - 1; i >= 0; i--) {
            const proxy = coords[i];
            psc.getTileByID(proxy.key);
            if (psc.proxyCachedFBO[proxy.key] !== undefined) {
                const prev = previousProxyToSource[proxy.key];
                // Reuse previous render from cache if there was no change of
                // content that was used to render proxy tile.
                const current = this.proxyToSource[proxy.key];
                let equal = 0;
                for (const source in current) {
                    const tiles = current[source];
                    const prevTiles = prev[source];
                    if (!prevTiles || prevTiles.length !== tiles.length || tiles.some((t, index) => t !== prevTiles[index] || dirty[source] && dirty[source].hasOwnProperty(t.key))) {
                        equal = -1;
                        break;
                    }
                    ++equal;
                }
                // dirty === false: doesn't need to be rendered to, just use cached render.
                for (const proxyFBO in psc.proxyCachedFBO[proxy.key]) {
                    psc.renderCache[psc.proxyCachedFBO[proxy.key][proxyFBO]].dirty = equal < 0 || equal !== Object.values(prev).length;
                }
            }
        }
        const sortedRenderBatches = [...this._drapedRenderBatches];
        sortedRenderBatches.sort((batchA, batchB) => {
            const batchASize = batchA.end - batchA.start;
            const batchBSize = batchB.end - batchB.start;
            return batchBSize - batchASize;
        });
        for (const batch of sortedRenderBatches) {
            for (const id of coords) {
                if (psc.proxyCachedFBO[id.key]) {
                    continue;
                }
                // Assign renderCache FBO if there are available FBOs in pool.
                let index = psc.renderCachePool.pop();
                if (index === undefined && psc.renderCache.length < RENDER_CACHE_MAX_SIZE) {
                    index = psc.renderCache.length;
                    psc.renderCache.push(this._createFBO());
                }
                if (index !== undefined) {
                    psc.proxyCachedFBO[id.key] = {};
                    psc.proxyCachedFBO[id.key][batch.start] = index;
                    psc.renderCache[index].dirty = true;    // needs to be rendered to.
                }
            }
        }
        this._tilesDirty = {};
    }
    _setupStencil(fbo, proxiedCoords, layer, sourceCache) {
        if (!sourceCache || !this._sourceTilesOverlap[sourceCache.id]) {
            if (this._overlapStencilType)
                this._overlapStencilType = false;
            return;
        }
        const context = this.painter.context;
        const gl = context.gl;
        // If needed, setup stencilling. Don't bother to remove when there is no
        // more need: in such case, if there is no overlap, stencilling is disabled.
        if (proxiedCoords.length <= 1) {
            this._overlapStencilType = false;
            return;
        }
        let stencilRange;
        if (layer.isTileClipped()) {
            stencilRange = proxiedCoords.length;
            this._overlapStencilMode.test = {
                func: gl.EQUAL,
                mask: 255
            };
            this._overlapStencilType = 'Clip';
        } else if (proxiedCoords[0].overscaledZ > proxiedCoords[proxiedCoords.length - 1].overscaledZ) {
            stencilRange = 1;
            this._overlapStencilMode.test = {
                func: gl.GREATER,
                mask: 255
            };
            this._overlapStencilType = 'Mask';
        } else {
            this._overlapStencilType = false;
            return;
        }
        if (this._stencilRef + stencilRange > 255) {
            context.clear({ stencil: 0 });
            this._stencilRef = 0;
        }
        this._stencilRef += stencilRange;
        this._overlapStencilMode.ref = this._stencilRef;
        if (layer.isTileClipped()) {
            this._renderTileClippingMasks(proxiedCoords, this._overlapStencilMode.ref);
        }
    }
    clipOrMaskOverlapStencilType() {
        return this._overlapStencilType === 'Clip' || this._overlapStencilType === 'Mask';
    }
    stencilModeForRTTOverlap(id) {
        if (!this.renderingToTexture || !this._overlapStencilType) {
            return StencilMode.disabled;
        }
        // All source tiles contributing to the same proxy are processed in sequence, in zoom descending order.
        // For raster / hillshade overlap masking, ref is based on zoom dif.
        // For vector layer clipping, every tile gets dedicated stencil ref.
        if (this._overlapStencilType === 'Clip') {
            // In immediate 2D mode, we render rects to mark clipping area and handle behavior on tile borders.
            // Here, there is no need for now for this:
            // 1. overlap is handled by proxy render to texture tiles (there is no overlap there)
            // 2. here we handle only brief zoom out semi-transparent color intensity flickering
            //    and that is avoided fine by stenciling primitives as part of drawing (instead of additional tile quad step).
            this._overlapStencilMode.ref = this.painter._tileClippingMaskIDs[id.key];
        }
        // else this._overlapStencilMode.ref is set to a single value used per proxy tile, in _setupStencil.
        return this._overlapStencilMode;
    }
    _renderTileClippingMasks(proxiedCoords, ref) {
        const painter = this.painter;
        const context = this.painter.context;
        const gl = context.gl;
        painter._tileClippingMaskIDs = {};
        context.setColorMode(ColorMode.disabled);
        context.setDepthMode(DepthMode.disabled);
        const program = painter.getOrCreateProgram('clippingMask');
        for (const tileID of proxiedCoords) {
            const id = painter._tileClippingMaskIDs[tileID.key] = --ref;
            program.draw(painter, gl.TRIANGLES, DepthMode.disabled, // Tests will always pass, and ref value will be written to stencil buffer.
            new StencilMode({
                func: gl.ALWAYS,
                mask: 0
            }, id, 255, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.projMatrix), '$clipping', painter.tileExtentBuffer, painter.quadTriangleIndexBuffer, painter.tileExtentSegments);
        }
    }
    // Casts a ray from a point on screen and returns the intersection point with the terrain.
    // The returned point contains the mercator coordinates in its first 3 components, and elevation
    // in meter in its 4th coordinate.
    pointCoordinate(screenPoint) {
        const transform = this.painter.transform;
        if (screenPoint.x < 0 || screenPoint.x > transform.width || screenPoint.y < 0 || screenPoint.y > transform.height) {
            return null;
        }
        const far = [
            screenPoint.x,
            screenPoint.y,
            1,
            1
        ];
        vec4_1.transformMat4(far, far, transform.pixelMatrixInverse);
        vec4_1.scale(far, far, 1 / far[3]);
        // x & y in pixel coordinates, z is altitude in meters
        far[0] /= transform.worldSize;
        far[1] /= transform.worldSize;
        const camera = transform._camera.position;
        const mercatorZScale = mercatorZfromAltitude(1, transform.center.lat);
        const p = [
            camera[0],
            camera[1],
            camera[2] / mercatorZScale,
            0
        ];
        const dir = vec3_1.subtract([], far.slice(0, 3), p);
        vec3_1.normalize(dir, dir);
        const exaggeration = this._exaggeration;
        const distanceAlongRay = this.raycast(p, dir, exaggeration);
        if (distanceAlongRay === null || !distanceAlongRay)
            return null;
        vec3_1.scaleAndAdd(p, p, dir, distanceAlongRay);
        p[3] = p[2];
        p[2] *= mercatorZScale;
        return p;
    }
    drawDepth() {
        const painter = this.painter;
        const context = painter.context;
        const psc = this.proxySourceCache;
        const width = Math.ceil(painter.width), height = Math.ceil(painter.height);
        if (this._depthFBO && (this._depthFBO.width !== width || this._depthFBO.height !== height)) {
            this._depthFBO.destroy();
            this._depthFBO = undefined;
            this._depthTexture = undefined;
        }
        if (!this._depthFBO) {
            const gl = context.gl;
            const fbo = context.createFramebuffer(width, height, true, 'renderbuffer');
            context.activeTexture.set(gl.TEXTURE0);
            const texture = new Texture(context, {
                width,
                height,
                data: null
            }, gl.RGBA);
            texture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
            fbo.colorAttachment.set(texture.texture);
            const renderbuffer = context.createRenderbuffer(context.gl.DEPTH_COMPONENT16, width, height);
            fbo.depthAttachment.set(renderbuffer);
            this._depthFBO = fbo;
            this._depthTexture = texture;
        }
        context.bindFramebuffer.set(this._depthFBO.framebuffer);
        context.viewport.set([
            0,
            0,
            width,
            height
        ]);
        drawTerrainDepth(painter, this, psc, this.proxyCoords);
    }
    _setupProxiedCoordsForOrtho(sourceCache, sourceCoords, previousProxyToSource) {
        if (sourceCache.getSource() instanceof ImageSource) {
            return this._setupProxiedCoordsForImageSource(sourceCache, sourceCoords, previousProxyToSource);
        }
        this._findCoveringTileCache[sourceCache.id] = this._findCoveringTileCache[sourceCache.id] || {};
        const coords = this.proxiedCoords[sourceCache.id] = [];
        const proxys = this.proxyCoords;
        for (let i = 0; i < proxys.length; i++) {
            const proxyTileID = proxys[i];
            const proxied = this._findTileCoveringTileID(proxyTileID, sourceCache);
            if (proxied) {
                const id = this._createProxiedId(proxyTileID, proxied, previousProxyToSource[proxyTileID.key] && previousProxyToSource[proxyTileID.key][sourceCache.id]);
                coords.push(id);
                this.proxyToSource[proxyTileID.key][sourceCache.id] = [id];
            }
        }
        let hasOverlap = false;
        for (let i = 0; i < sourceCoords.length; i++) {
            const tile = sourceCache.getTile(sourceCoords[i]);
            if (!tile || !tile.hasData())
                continue;
            const proxy = this._findTileCoveringTileID(tile.tileID, this.proxySourceCache);
            // Don't add the tile if already added in loop above.
            if (proxy && proxy.tileID.canonical.z !== tile.tileID.canonical.z) {
                const array = this.proxyToSource[proxy.tileID.key][sourceCache.id];
                const id = this._createProxiedId(proxy.tileID, tile, previousProxyToSource[proxy.tileID.key] && previousProxyToSource[proxy.tileID.key][sourceCache.id]);
                if (!array) {
                    this.proxyToSource[proxy.tileID.key][sourceCache.id] = [id];
                } else {
                    // The last element is parent added in loop above. This way we get
                    // a list in Z descending order which is needed for stencil masking.
                    array.splice(array.length - 1, 0, id);
                }
                coords.push(id);
                hasOverlap = true;
            }
        }
        this._sourceTilesOverlap[sourceCache.id] = hasOverlap;
    }
    _setupProxiedCoordsForImageSource(sourceCache, sourceCoords, previousProxyToSource) {
        if (!sourceCache.getSource().loaded())
            return;
        const coords = this.proxiedCoords[sourceCache.id] = [];
        const proxys = this.proxyCoords;
        const imageSource = sourceCache.getSource();
        // Special case where image is rendered outside of the map's bounds (eg. pole caps)
        const tileID = imageSource.tileID;
        if (!tileID)
            return;
        const anchor = new Point$2(tileID.x, tileID.y)._div(1 << tileID.z);
        // $FlowFixMe[method-unbinding]
        const aabb = imageSource.coordinates.map(MercatorCoordinate.fromLngLat).reduce((acc, coord) => {
            acc.min.x = Math.min(acc.min.x, coord.x - anchor.x);
            acc.min.y = Math.min(acc.min.y, coord.y - anchor.y);
            acc.max.x = Math.max(acc.max.x, coord.x - anchor.x);
            acc.max.y = Math.max(acc.max.y, coord.y - anchor.y);
            return acc;
        }, {
            min: new Point$2(Number.MAX_VALUE, Number.MAX_VALUE),
            max: new Point$2(-Number.MAX_VALUE, -Number.MAX_VALUE)
        });
        // Fast conservative check using aabb: content outside proxy tile gets clipped out by on render, anyway.
        const tileOutsideImage = (tileID, imageTileID) => {
            const x = tileID.wrap + tileID.canonical.x / (1 << tileID.canonical.z);
            const y = tileID.canonical.y / (1 << tileID.canonical.z);
            const d = EXTENT / (1 << tileID.canonical.z);
            const ix = imageTileID.wrap + imageTileID.canonical.x / (1 << imageTileID.canonical.z);
            const iy = imageTileID.canonical.y / (1 << imageTileID.canonical.z);
            return x + d < ix + aabb.min.x || x > ix + aabb.max.x || y + d < iy + aabb.min.y || y > iy + aabb.max.y;
        };
        for (let i = 0; i < proxys.length; i++) {
            const proxyTileID = proxys[i];
            for (let j = 0; j < sourceCoords.length; j++) {
                const tile = sourceCache.getTile(sourceCoords[j]);
                if (!tile || !tile.hasData())
                    continue;
                // Setup proxied -> proxy mapping only if image on given tile wrap intersects the proxy tile.
                if (tileOutsideImage(proxyTileID, tile.tileID))
                    continue;
                const id = this._createProxiedId(proxyTileID, tile, previousProxyToSource[proxyTileID.key] && previousProxyToSource[proxyTileID.key][sourceCache.id]);
                const array = this.proxyToSource[proxyTileID.key][sourceCache.id];
                if (!array) {
                    this.proxyToSource[proxyTileID.key][sourceCache.id] = [id];
                } else {
                    array.push(id);
                }
                coords.push(id);
            }
        }
    }
    // recycle is previous pass content that likely contains proxied ID combining proxy and source tile.
    _createProxiedId(proxyTileID, tile, recycle) {
        let matrix = this.orthoMatrix;
        if (recycle) {
            const recycled = recycle.find(proxied => proxied.key === tile.tileID.key);
            if (recycled)
                return recycled;
        }
        if (tile.tileID.key !== proxyTileID.key) {
            const scale = proxyTileID.canonical.z - tile.tileID.canonical.z;
            matrix = mat4_1.create();
            let size, xOffset, yOffset;
            const wrap = tile.tileID.wrap - proxyTileID.wrap << proxyTileID.overscaledZ;
            if (scale > 0) {
                size = EXTENT >> scale;
                xOffset = size * ((tile.tileID.canonical.x << scale) - proxyTileID.canonical.x + wrap);
                yOffset = size * ((tile.tileID.canonical.y << scale) - proxyTileID.canonical.y);
            } else {
                size = EXTENT << -scale;
                xOffset = EXTENT * (tile.tileID.canonical.x - (proxyTileID.canonical.x + wrap << -scale));
                yOffset = EXTENT * (tile.tileID.canonical.y - (proxyTileID.canonical.y << -scale));
            }
            mat4_1.ortho(matrix, 0, size, 0, size, 0, 1);
            mat4_1.translate(matrix, matrix, [
                xOffset,
                yOffset,
                0
            ]);
        }
        return new ProxiedTileID(tile.tileID, proxyTileID.key, matrix);
    }
    // A variant of SourceCache.findLoadedParent that considers only visible
    // tiles (and doesn't check SourceCache._cache). Another difference is in
    // caching "not found" results along the lookup, to leave the lookup early.
    // Not found is cached by this._findCoveringTileCache[key] = null;
    _findTileCoveringTileID(tileID, sourceCache) {
        let tile = sourceCache.getTile(tileID);
        if (tile && tile.hasData())
            return tile;
        const lookup = this._findCoveringTileCache[sourceCache.id];
        const key = lookup[tileID.key];
        tile = key ? sourceCache.getTileByID(key) : null;
        if (tile && tile.hasData() || key === null)
            return tile;
        let sourceTileID = tile ? tile.tileID : tileID;
        let z = sourceTileID.overscaledZ;
        const minzoom = sourceCache.getSource().minzoom;
        const path = [];
        if (!key) {
            const maxzoom = sourceCache.getSource().maxzoom;
            if (tileID.canonical.z >= maxzoom) {
                const downscale = tileID.canonical.z - maxzoom;
                if (sourceCache.getSource().reparseOverscaled) {
                    z = Math.max(tileID.canonical.z + 2, sourceCache.transform.tileZoom);
                    sourceTileID = new OverscaledTileID(z, tileID.wrap, maxzoom, tileID.canonical.x >> downscale, tileID.canonical.y >> downscale);
                } else if (downscale !== 0) {
                    z = maxzoom;
                    sourceTileID = new OverscaledTileID(z, tileID.wrap, maxzoom, tileID.canonical.x >> downscale, tileID.canonical.y >> downscale);
                }
            }
            if (sourceTileID.key !== tileID.key) {
                path.push(sourceTileID.key);
                tile = sourceCache.getTile(sourceTileID);
            }
        }
        const pathToLookup = key => {
            path.forEach(id => {
                lookup[id] = key;
            });
            path.length = 0;
        };
        for (z = z - 1; z >= minzoom && !(tile && tile.hasData()); z--) {
            if (tile) {
                pathToLookup(tile.tileID.key);    // Store lookup to parents not loaded (yet).
            }
            const id = sourceTileID.calculateScaledKey(z);
            tile = sourceCache.getTileByID(id);
            if (tile && tile.hasData())
                break;
            const key = lookup[id];
            if (key === null) {
                break;    // There's no tile loaded and no point searching further.
            } else if (key !== undefined) {
                tile = sourceCache.getTileByID(key);
                continue;
            }
            path.push(id);
        }
        pathToLookup(tile ? tile.tileID.key : null);
        return tile && tile.hasData() ? tile : null;
    }
    findDEMTileFor(tileID) {
        return this.enabled ? this._findTileCoveringTileID(tileID, this.sourceCache) : null;
    }
    /*
     * Bookkeeping if something gets rendered to the tile.
     */
    prepareDrawTile() {
        this.renderedToTile = true;
    }
    _clearRenderCacheForTile(sourceCacheFQID, coord) {
        let sourceTiles = this._tilesDirty[sourceCacheFQID];
        if (!sourceTiles)
            sourceTiles = this._tilesDirty[sourceCacheFQID] = {};
        sourceTiles[coord.key] = true;
    }
}
function sortByDistanceToCamera(tileIDs, painter) {
    const cameraCoordinate = painter.transform.pointCoordinate(painter.transform.getCameraPoint());
    const cameraPoint = new Point$2(cameraCoordinate.x, cameraCoordinate.y);
    tileIDs.sort((a, b) => {
        if (b.overscaledZ - a.overscaledZ)
            return b.overscaledZ - a.overscaledZ;
        const aPoint = new Point$2(a.canonical.x + (1 << a.canonical.z) * a.wrap, a.canonical.y);
        const bPoint = new Point$2(b.canonical.x + (1 << b.canonical.z) * b.wrap, b.canonical.y);
        const cameraScaled = cameraPoint.mult(1 << a.canonical.z);
        cameraScaled.x -= 0.5;
        cameraScaled.y -= 0.5;
        return cameraScaled.distSqr(aPoint) - cameraScaled.distSqr(bPoint);
    });
}
/**
 * Creates uniform grid of triangles, covering EXTENT x EXTENT square, with two
 * adjustent traigles forming a quad, so that there are |count| columns and rows
 * of these quads in EXTENT x EXTENT square.
 * e.g. for count of 2:
 *  -------------
 *  |    /|    /|
 *  |  /  |  /  |
 *  |/    |/    |
 *  -------------
 *  |    /|    /|
 *  |  /  |  /  |
 *  |/    |/    |
 *  -------------
 * @param {number} count Count of rows and columns
 * @private
 */
function createGrid(count) {
    const boundsArray = new StructArrayLayout2i4();
    // Around the grid, add one more row/column padding for "skirt".
    const indexArray = new StructArrayLayout3ui6();
    const size = count + 2;
    boundsArray.reserve(size * size);
    indexArray.reserve((size - 1) * (size - 1) * 2);
    const step = EXTENT / (count - 1);
    const gridBound = EXTENT + step / 2;
    const bound = gridBound + step;
    // Skirt offset of 0x5FFF is chosen randomly to encode boolean value (skirt
    // on/off) with x position (max value EXTENT = 4096) to 16-bit signed integer.
    const skirtOffset = 24575;
    // 0x5FFF
    for (let y = -step; y < bound; y += step) {
        for (let x = -step; x < bound; x += step) {
            const offset = x < 0 || x > gridBound || y < 0 || y > gridBound ? skirtOffset : 0;
            const xi = clamp(Math.round(x), 0, EXTENT);
            const yi = clamp(Math.round(y), 0, EXTENT);
            boundsArray.emplaceBack(xi + offset, yi);
        }
    }
    // For cases when there's no need to render "skirt", the "inner" grid indices
    // are followed by skirt indices.
    const skirtIndicesOffset = (size - 3) * (size - 3) * 2;
    const quad = (i, j) => {
        const index = j * size + i;
        indexArray.emplaceBack(index + 1, index, index + size);
        indexArray.emplaceBack(index + size, index + size + 1, index + 1);
    };
    for (let j = 1; j < size - 2; j++) {
        for (let i = 1; i < size - 2; i++) {
            quad(i, j);
        }
    }
    // Padding (skirt) indices:
    [
        0,
        size - 2
    ].forEach(j => {
        for (let i = 0; i < size - 1; i++) {
            quad(i, j);
            quad(j, i);
        }
    });
    return [
        boundsArray,
        indexArray,
        skirtIndicesOffset
    ];
}
const terrainUniforms = context => ({
    'u_dem': new Uniform1i(context),
    'u_dem_prev': new Uniform1i(context),
    'u_dem_unpack': new Uniform4f(context),
    'u_dem_tl': new Uniform2f(context),
    'u_dem_scale': new Uniform1f(context),
    'u_dem_tl_prev': new Uniform2f(context),
    'u_dem_scale_prev': new Uniform1f(context),
    'u_dem_size': new Uniform1f(context),
    'u_dem_lerp': new Uniform1f(context),
    'u_exaggeration': new Uniform1f(context),
    'u_depth': new Uniform1i(context),
    'u_depth_size_inv': new Uniform2f(context),
    'u_meter_to_dem': new Uniform1f(context),
    'u_label_plane_matrix_inv': new UniformMatrix4f(context)
});
function defaultTerrainUniforms(encoding) {
    return {
        'u_dem': 2,
        'u_dem_prev': 4,
        'u_dem_unpack': DEMData.getUnpackVector(encoding),
        'u_dem_tl': [
            0,
            0
        ],
        'u_dem_tl_prev': [
            0,
            0
        ],
        'u_dem_scale': 0,
        'u_dem_scale_prev': 0,
        'u_dem_size': 0,
        'u_dem_lerp': 1,
        'u_depth': 3,
        'u_depth_size_inv': [
            0,
            0
        ],
        'u_exaggeration': 0
    };
}
const globeUniforms = context => ({
    'u_tile_tl_up': new Uniform3f(context),
    'u_tile_tr_up': new Uniform3f(context),
    'u_tile_br_up': new Uniform3f(context),
    'u_tile_bl_up': new Uniform3f(context),
    'u_tile_up_scale': new Uniform1f(context)
});

//      
const fogUniforms = context => ({
    'u_fog_matrix': new UniformMatrix4f(context),
    'u_fog_range': new Uniform2f(context),
    'u_fog_color': new Uniform4f(context),
    'u_fog_horizon_blend': new Uniform1f(context),
    'u_fog_vertical_limit': new Uniform2f(context),
    'u_fog_temporal_offset': new Uniform1f(context),
    'u_frustum_tl': new Uniform3f(context),
    'u_frustum_tr': new Uniform3f(context),
    'u_frustum_br': new Uniform3f(context),
    'u_frustum_bl': new Uniform3f(context),
    'u_globe_pos': new Uniform3f(context),
    'u_globe_radius': new Uniform1f(context),
    'u_globe_transition': new Uniform1f(context),
    'u_is_globe': new Uniform1i(context),
    'u_viewport': new Uniform2f(context)
});
const fogUniformValues = (painter, fog, tileID, fogOpacity, frustumDirTl, frustumDirTr, frustumDirBr, frustumDirBl, globePosition, globeRadius, viewport, fogMatrix) => {
    const tr = painter.transform;
    const fogColor = fog.properties.get('color').toArray01();
    fogColor[3] = fogOpacity;
    // Update Alpha
    const temporalOffset = painter.frameCounter / 1000 % 1;
    const [verticalRangeMin, verticalRangeMax] = fog.properties.get('vertical-range');
    return {
        'u_fog_matrix': tileID ? tr.calculateFogTileMatrix(tileID) : fogMatrix ? fogMatrix : painter.identityMat,
        'u_fog_range': fog.getFovAdjustedRange(tr._fov),
        'u_fog_color': fogColor,
        'u_fog_horizon_blend': fog.properties.get('horizon-blend'),
        'u_fog_vertical_limit': [
            Math.min(verticalRangeMin, verticalRangeMax),
            verticalRangeMax
        ],
        'u_fog_temporal_offset': temporalOffset,
        'u_frustum_tl': frustumDirTl,
        'u_frustum_tr': frustumDirTr,
        'u_frustum_br': frustumDirBr,
        'u_frustum_bl': frustumDirBl,
        'u_globe_pos': globePosition,
        'u_globe_radius': globeRadius,
        'u_viewport': viewport,
        'u_globe_transition': globeToMercatorTransition(tr.zoom),
        'u_is_globe': +(tr.projection.name === 'globe')
    };
};

//      
const lightsUniforms = context => ({
    'u_lighting_ambient_color': new Uniform3f(context),
    'u_lighting_directional_dir': new Uniform3f(context),
    'u_lighting_directional_color': new Uniform3f(context),
    'u_ground_radiance': new Uniform3f(context)
});
function calculateAmbientDirectionalFactor(dir, normal, dirColor) {
    // NdotL Used only for ambient directionality
    const NdotL = vec3_1.dot(normal, dir);
    // Emulate sky being brighter close to the main light source
    const factorReductionMax = 0.3;
    const dirLuminance = vec3_1.dot(dirColor, [
        0.2126,
        0.7152,
        0.0722
    ]);
    const directionalFactorMin = 1 - factorReductionMax * Math.min(dirLuminance, 1);
    const lerp = (a, b, t) => {
        return (1 - t) * a + t * b;
    };
    // If dirColor is (1, 1, 1), then the return value range is
    // NdotL=-1: 1.0 - factorReductionMax
    // NdotL>=0: 1.0
    const ambientDirectionalFactor = lerp(directionalFactorMin, 1, Math.min(NdotL + 1, 1));
    // Emulate environmental light being blocked by other objects
    // Value moves from vertical_factor_min at z=-1 to 1.0 at z=1
    const verticalFactorMin = 0.92;
    // clamp(z, -1.0, 1.0) is required because z can be very slightly out of the acceptable input
    // range for asin, even when it has been normalized, due to limited floating point precision.
    const verticalFactor = lerp(verticalFactorMin, 1, Math.asin(clamp(normal[2], -1, 1)) / Math.PI + 0.5);
    return verticalFactor * ambientDirectionalFactor;
}
function calculateGroundRadiance(dir, dirColor, ambientColor) {
    const groundNormal = [
        0,
        0,
        1
    ];
    const ambientDirectionalFactor = calculateAmbientDirectionalFactor(dir, groundNormal, dirColor);
    const ambientContrib = [
        0,
        0,
        0
    ];
    vec3_1.scale(ambientContrib, ambientColor.slice(0, 3), ambientDirectionalFactor);
    const dirConrib = [
        0,
        0,
        0
    ];
    vec3_1.scale(dirConrib, dirColor.slice(0, 3), dir[2]);
    const radiance = [
        0,
        0,
        0
    ];
    vec3_1.add(radiance, ambientContrib, dirConrib);
    return linearVec3TosRGB(radiance);
}
const lightsUniformValues = (directional, ambient) => {
    const direction = directional.properties.get('direction');
    const directionalColor = directional.properties.get('color').toArray01();
    const directionalIntensity = directional.properties.get('intensity');
    const ambientColor = ambient.properties.get('color').toArray01();
    const ambientIntensity = ambient.properties.get('intensity');
    const dirVec = [
        direction.x,
        direction.y,
        direction.z
    ];
    const ambientColorLinear = sRGBToLinearAndScale(ambientColor, ambientIntensity);
    const directionalColorLinear = sRGBToLinearAndScale(directionalColor, directionalIntensity);
    const groundRadianceSrgb = calculateGroundRadiance(dirVec, directionalColorLinear, ambientColorLinear);
    return {
        'u_lighting_ambient_color': ambientColorLinear,
        'u_lighting_directional_dir': dirVec,
        'u_lighting_directional_color': directionalColorLinear,
        'u_ground_radiance': groundRadianceSrgb
    };
};

//      
const shadowUniforms = context => ({
    'u_light_matrix_0': new UniformMatrix4f(context),
    'u_light_matrix_1': new UniformMatrix4f(context),
    'u_fade_range': new Uniform2f(context),
    'u_shadow_normal_offset': new Uniform3f(context),
    'u_shadow_intensity': new Uniform1f(context),
    'u_shadow_texel_size': new Uniform1f(context),
    'u_shadow_map_resolution': new Uniform1f(context),
    'u_shadow_direction': new Uniform3f(context),
    'u_shadow_bias': new Uniform3f(context),
    'u_shadowmap_0': new Uniform1i(context),
    'u_shadowmap_1': new Uniform1i(context)
});
function defaultShadowUniformValues() {
    return {
        'u_light_matrix_0': new Float32Array(16),
        'u_light_matrix_1': new Float32Array(16),
        'u_shadow_intensity': 0,
        'u_fade_range': [
            0,
            0
        ],
        'u_shadow_normal_offset': [
            1,
            1,
            1
        ],
        'u_shadow_texel_size': 1,
        'u_shadow_map_resolution': 1,
        'u_shadow_direction': [
            0,
            0,
            1
        ],
        'u_shadow_bias': [
            0.00036,
            0.0012,
            0.012
        ],
        'u_shadowmap_0': 0,
        'u_shadowmap_1': 0
    };
}

//      
function getTokenizedAttributes(array) {
    const result = [];
    for (let i = 0; i < array.length; i++) {
        if (array[i] === null)
            continue;
        const token = array[i].split(' ');
        result.push(token.pop());
    }
    return result;
}
const debugWireframe2DLayerProgramNames = [
    'fill',
    'fillOutline',
    'fillPattern',
    'line',
    'linePattern',
    'background',
    'backgroundPattern',
    'hillshade',
    'raster'
];
const debugWireframe3DLayerProgramNames = [
    'stars',
    'fillExtrusion',
    'fillExtrusionGroundEffect',
    'model',
    'symbolSDF',
    'symbolIcon',
    'symbolTextAndIcon'
];
class Program {
    static cacheKey(source, name, defines, programConfiguration) {
        let key = `${ name }${ programConfiguration ? programConfiguration.cacheKey : '' }`;
        for (const define of defines) {
            if (source.usedDefines.includes(define)) {
                key += `/${ define }`;
            }
        }
        return key;
    }
    constructor(context, name, source, configuration, fixedUniforms, fixedDefines) {
        const gl = context.gl;
        this.program = gl.createProgram();
        this.configuration = configuration;
        this.name = name;
        this.fixedDefines = [...fixedDefines];
        const staticAttrInfo = getTokenizedAttributes(source.staticAttributes);
        const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];
        const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo);
        let defines = configuration ? configuration.defines() : [];
        defines = defines.concat(fixedDefines.map(define => `#define ${ define }`));
        const version = '#version 300 es\n';
        let fragmentSource = version + defines.concat(preludeFragPrecisionQualifiers, preludeCommonSource, prelude.fragmentSource).join('\n');
        for (const include of source.fragmentIncludes) {
            fragmentSource += `\n${ includeMap[include] }`;
        }
        fragmentSource += `\n${ source.fragmentSource }`;
        let vertexSource = version + defines.concat(preludeVertPrecisionQualifiers, preludeCommonSource, prelude.vertexSource).join('\n');
        for (const include of source.vertexIncludes) {
            vertexSource += `\n${ includeMap[include] }`;
        }
        vertexSource += `\n${ source.vertexSource }`;
        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        if (gl.isContextLost()) {
            this.failedToCreate = true;
            return;
        }
        gl.shaderSource(fragmentShader, fragmentSource);
        gl.compileShader(fragmentShader);
        gl.attachShader(this.program, fragmentShader);
        const vertexShader = gl.createShader(gl.VERTEX_SHADER);
        if (gl.isContextLost()) {
            this.failedToCreate = true;
            return;
        }
        gl.shaderSource(vertexShader, vertexSource);
        gl.compileShader(vertexShader);
        gl.attachShader(this.program, vertexShader);
        this.attributes = {};
        this.numAttributes = allAttrInfo.length;
        for (let i = 0; i < this.numAttributes; i++) {
            if (allAttrInfo[i]) {
                // Handle pragma defined attributes
                const attributeName = allAttrInfo[i].startsWith('a_') ? allAttrInfo[i] : `a_${ allAttrInfo[i] }`;
                gl.bindAttribLocation(this.program, i, attributeName);
                this.attributes[attributeName] = i;
            }
        }
        gl.linkProgram(this.program);
        gl.deleteShader(vertexShader);
        gl.deleteShader(fragmentShader);
        this.fixedUniforms = fixedUniforms(context);
        this.binderUniforms = configuration ? configuration.getUniforms(context) : [];
        if (fixedDefines.includes('TERRAIN')) {
            this.terrainUniforms = terrainUniforms(context);
        }
        if (fixedDefines.includes('GLOBE')) {
            this.globeUniforms = globeUniforms(context);
        }
        if (fixedDefines.includes('FOG')) {
            this.fogUniforms = fogUniforms(context);
        }
        if (fixedDefines.includes('RENDER_CUTOFF')) {
            this.cutoffUniforms = cutoffUniforms(context);
        }
        if (fixedDefines.includes('LIGHTING_3D_MODE')) {
            this.lightsUniforms = lightsUniforms(context);
        }
        if (fixedDefines.includes('RENDER_SHADOWS')) {
            this.shadowUniforms = shadowUniforms(context);
        }
    }
    setTerrainUniformValues(context, terrainUniformValues) {
        if (!this.terrainUniforms)
            return;
        const uniforms = this.terrainUniforms;
        if (this.failedToCreate)
            return;
        context.program.set(this.program);
        for (const name in terrainUniformValues) {
            if (uniforms[name]) {
                uniforms[name].set(this.program, name, terrainUniformValues[name]);
            }
        }
    }
    setGlobeUniformValues(context, globeUniformValues) {
        if (!this.globeUniforms)
            return;
        const uniforms = this.globeUniforms;
        if (this.failedToCreate)
            return;
        context.program.set(this.program);
        for (const name in globeUniformValues) {
            if (uniforms[name]) {
                uniforms[name].set(this.program, name, globeUniformValues[name]);
            }
        }
    }
    setFogUniformValues(context, fogUniformValues) {
        if (!this.fogUniforms)
            return;
        const uniforms = this.fogUniforms;
        if (this.failedToCreate)
            return;
        context.program.set(this.program);
        for (const name in fogUniformValues) {
            uniforms[name].set(this.program, name, fogUniformValues[name]);
        }
    }
    setCutoffUniformValues(context, cutoffUniformValues) {
        if (!this.cutoffUniforms)
            return;
        const uniforms = this.cutoffUniforms;
        if (this.failedToCreate)
            return;
        context.program.set(this.program);
        for (const name in cutoffUniformValues) {
            uniforms[name].set(this.program, name, cutoffUniformValues[name]);
        }
    }
    setLightsUniformValues(context, lightsUniformValues) {
        if (!this.lightsUniforms)
            return;
        const uniforms = this.lightsUniforms;
        if (this.failedToCreate)
            return;
        context.program.set(this.program);
        for (const name in lightsUniformValues) {
            uniforms[name].set(this.program, name, lightsUniformValues[name]);
        }
    }
    setShadowUniformValues(context, shadowUniformValues) {
        if (this.failedToCreate || !this.shadowUniforms)
            return;
        const uniforms = this.shadowUniforms;
        context.program.set(this.program);
        for (const name in shadowUniformValues) {
            uniforms[name].set(this.program, name, shadowUniformValues[name]);
        }
    }
    _drawDebugWireframe(painter, depthMode, stencilMode, colorMode, indexBuffer, segment, currentProperties, zoom, configuration, instanceCount) {
        const wireframe = painter.options.wireframe;
        if (wireframe.terrain === false && wireframe.layers2D === false && wireframe.layers3D === false) {
            return;
        }
        const context = painter.context;
        const subjectForWireframe = ((() => {
            // Terrain
            if (wireframe.terrain && (this.name === 'terrainRaster' || this.name === 'globeRaster')) {
                return true;
            }
            const drapingInProgress = painter._terrain && painter._terrain.renderingToTexture;
            // 2D
            if (wireframe.layers2D && !drapingInProgress) {
                if (debugWireframe2DLayerProgramNames.includes(this.name)) {
                    return true;
                }
            }
            // 3D
            if (wireframe.layers3D) {
                if (debugWireframe3DLayerProgramNames.includes(this.name)) {
                    return true;
                }
            }
            return false;
        })());
        if (!subjectForWireframe) {
            return;
        }
        const gl = context.gl;
        const linesIndexBuffer = painter.wireframeDebugCache.getLinesFromTrianglesBuffer(painter.frameCounter, indexBuffer, context);
        if (!linesIndexBuffer) {
            return;
        }
        const debugDefines = [...this.fixedDefines];
        debugDefines.push('DEBUG_WIREFRAME');
        // $FlowIgnore[incompatible-call] defines are saved as string whereas getOrCreateProgram has restrictions
        const debugProgram = painter.getOrCreateProgram(this.name, {
            config: this.configuration,
            defines: debugDefines
        });
        context.program.set(debugProgram.program);
        const copyUniformValues = (group, pSrc, pDst) => {
            if (pSrc[group] && pDst[group]) {
                for (const name in pSrc[group]) {
                    if (pDst[group][name]) {
                        pDst[group][name].set(pDst.program, name, pSrc[group][name].current);
                    }
                }
            }
        };
        if (configuration) {
            configuration.setUniforms(debugProgram.program, context, debugProgram.binderUniforms, currentProperties, { zoom: zoom });
        }
        copyUniformValues('fixedUniforms', this, debugProgram);
        copyUniformValues('terrainUniforms', this, debugProgram);
        copyUniformValues('globeUniforms', this, debugProgram);
        copyUniformValues('fogUniforms', this, debugProgram);
        copyUniformValues('lightsUniforms', this, debugProgram);
        copyUniformValues('shadowUniforms', this, debugProgram);
        linesIndexBuffer.bind();
        // Debug wireframe uses premultiplied alpha blending (alpha channel is left unchanged)
        context.setColorMode(new ColorMode([
            gl.ONE,
            gl.ONE_MINUS_SRC_ALPHA,
            gl.ZERO,
            gl.ONE
        ], Color$1.transparent, [
            true,
            true,
            true,
            false
        ]));
        context.setDepthMode(new DepthMode(depthMode.func === gl.LESS ? gl.LEQUAL : depthMode.func, DepthMode.ReadOnly, depthMode.range));
        context.setStencilMode(StencilMode.disabled);
        const count = segment.primitiveLength * 3 * 2;
        // One triangle corresponds to 3 lines (each has 2 indices)
        const offset = segment.primitiveOffset * 3 * 2 * 2;
        // One triangles corresponds to 3 lines (2 indices * 2 bytes per index)
        if (instanceCount && instanceCount > 1) {
            gl.drawElementsInstanced(gl.LINES, count, gl.UNSIGNED_SHORT, offset, instanceCount);
        } else {
            gl.drawElements(gl.LINES, count, gl.UNSIGNED_SHORT, offset);
        }
        // Revert to non-wireframe parameters
        indexBuffer.bind();
        context.program.set(this.program);
        context.setDepthMode(depthMode);
        context.setStencilMode(stencilMode);
        context.setColorMode(colorMode);
    }
    draw(painter, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, layerID, layoutVertexBuffer, indexBuffer, segments, currentProperties, zoom, configuration, dynamicLayoutBuffers, instanceCount) {
        const context = painter.context;
        const gl = context.gl;
        if (this.failedToCreate)
            return;
        context.program.set(this.program);
        context.setDepthMode(depthMode);
        context.setStencilMode(stencilMode);
        context.setColorMode(colorMode);
        context.setCullFace(cullFaceMode);
        for (const name of Object.keys(this.fixedUniforms)) {
            this.fixedUniforms[name].set(this.program, name, uniformValues[name]);
        }
        if (configuration) {
            configuration.setUniforms(this.program, context, this.binderUniforms, currentProperties, { zoom: zoom });
        }
        const primitiveSize = {
            [gl.LINES]: 2,
            [gl.TRIANGLES]: 3,
            [gl.LINE_STRIP]: 1
        }[drawMode];
        const vertexAttribDivisorValue = instanceCount && instanceCount > 0 ? 1 : undefined;
        for (const segment of segments.get()) {
            const vaos = segment.vaos || (segment.vaos = {});
            const vao = vaos[layerID] || (vaos[layerID] = new VertexArrayObject());
            vao.bind(context, this, layoutVertexBuffer, configuration ? configuration.getPaintVertexBuffers() : [], indexBuffer, segment.vertexOffset, dynamicLayoutBuffers ? dynamicLayoutBuffers : [], vertexAttribDivisorValue);
            if (instanceCount && instanceCount > 1) {
                gl.drawElementsInstanced(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2, instanceCount);
            } else {
                gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2);
            }
            if (drawMode === gl.TRIANGLES) {
                // Handle potential wireframe rendering for current draw call
                this._drawDebugWireframe(painter, depthMode, stencilMode, colorMode, indexBuffer, segment, currentProperties, zoom, configuration, instanceCount);
            }
        }
    }
}

function patternUniformValues(painter, tile) {
    const numTiles = Math.pow(2, tile.tileID.overscaledZ);
    const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;
    const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);
    const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;
    return {
        'u_image': 0,
        'u_texsize': tile.imageAtlasTexture.size,
        'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom),
        // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.
        'u_pixel_coord_upper': [
            pixelX >> 16,
            pixelY >> 16
        ],
        'u_pixel_coord_lower': [
            pixelX & 65535,
            pixelY & 65535
        ]
    };
}
function bgPatternUniformValues(image, scope, painter, tile) {
    const imagePos = painter.imageManager.getPattern(image.toString(), scope);
    const {width, height} = painter.imageManager.getPixelSize(scope);
    const numTiles = Math.pow(2, tile.tileID.overscaledZ);
    const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;
    const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);
    const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;
    return {
        'u_image': 0,
        'u_pattern_tl': imagePos.tl,
        'u_pattern_br': imagePos.br,
        'u_texsize': [
            width,
            height
        ],
        'u_pattern_size': imagePos.displaySize,
        'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom),
        // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.
        'u_pixel_coord_upper': [
            pixelX >> 16,
            pixelY >> 16
        ],
        'u_pixel_coord_lower': [
            pixelX & 65535,
            pixelY & 65535
        ]
    };
}

//      
const fillExtrusionUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_lightpos': new Uniform3f(context),
    'u_lightintensity': new Uniform1f(context),
    'u_lightcolor': new Uniform3f(context),
    'u_vertical_gradient': new Uniform1f(context),
    'u_opacity': new Uniform1f(context),
    'u_edge_radius': new Uniform1f(context),
    'u_ao': new Uniform2f(context),
    // globe uniforms:
    'u_tile_id': new Uniform3f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_inv_rot_matrix': new UniformMatrix4f(context),
    'u_merc_center': new Uniform2f(context),
    'u_up_dir': new Uniform3f(context),
    'u_height_lift': new Uniform1f(context),
    'u_flood_light_color': new Uniform3f(context),
    'u_vertical_scale': new Uniform1f(context),
    'u_flood_light_intensity': new Uniform1f(context),
    'u_ground_shadow_factor': new Uniform3f(context)
});
const fillExtrusionDepthUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_edge_radius': new Uniform1f(context),
    'u_vertical_scale': new Uniform1f(context)
});
const fillExtrusionPatternUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_lightpos': new Uniform3f(context),
    'u_lightintensity': new Uniform1f(context),
    'u_lightcolor': new Uniform3f(context),
    'u_vertical_gradient': new Uniform1f(context),
    'u_height_factor': new Uniform1f(context),
    'u_edge_radius': new Uniform1f(context),
    'u_ao': new Uniform2f(context),
    // globe uniforms:
    'u_tile_id': new Uniform3f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_inv_rot_matrix': new UniformMatrix4f(context),
    'u_merc_center': new Uniform2f(context),
    'u_up_dir': new Uniform3f(context),
    'u_height_lift': new Uniform1f(context),
    // pattern uniforms
    'u_image': new Uniform1i(context),
    'u_texsize': new Uniform2f(context),
    'u_pixel_coord_upper': new Uniform2f(context),
    'u_pixel_coord_lower': new Uniform2f(context),
    'u_tile_units_to_pixels': new Uniform1f(context),
    'u_opacity': new Uniform1f(context)
});
const fillExtrusionGroundEffectUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_opacity': new Uniform1f(context),
    'u_ao_pass': new Uniform1f(context),
    'u_meter_to_tile': new Uniform1f(context),
    'u_ao': new Uniform2f(context),
    'u_flood_light_intensity': new Uniform1f(context),
    'u_flood_light_color': new Uniform3f(context),
    'u_attenuation': new Uniform1f(context),
    'u_edge_radius': new Uniform1f(context),
    'u_fb': new Uniform1i(context),
    'u_fb_size': new Uniform1f(context)
});
const identityMatrix$2 = mat4_1.create();
const fillExtrusionUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, aoIntensityRadius, edgeRadius, coord, heightLift, zoomTransition, mercatorCenter, invMatrix, floodLightColor, verticalScale, floodLightIntensity, groundShadowFactor) => {
    const light = painter.style.light;
    const _lp = light.properties.get('position');
    const lightPos = [
        _lp.x,
        _lp.y,
        _lp.z
    ];
    const lightMat = mat3_1.create();
    const anchor = light.properties.get('anchor');
    if (anchor === 'viewport') {
        mat3_1.fromRotation(lightMat, -painter.transform.angle);
        vec3_1.transformMat3(lightPos, lightPos, lightMat);
    }
    const lightColor = light.properties.get('color');
    const tr = painter.transform;
    const uniformValues = {
        'u_matrix': matrix,
        'u_lightpos': lightPos,
        'u_lightintensity': light.properties.get('intensity'),
        'u_lightcolor': [
            lightColor.r,
            lightColor.g,
            lightColor.b
        ],
        'u_vertical_gradient': +shouldUseVerticalGradient,
        'u_opacity': opacity,
        'u_tile_id': [
            0,
            0,
            0
        ],
        'u_zoom_transition': 0,
        'u_inv_rot_matrix': identityMatrix$2,
        'u_merc_center': [
            0,
            0
        ],
        'u_up_dir': [
            0,
            0,
            0
        ],
        'u_height_lift': 0,
        'u_ao': aoIntensityRadius,
        'u_edge_radius': edgeRadius,
        'u_flood_light_color': floodLightColor,
        'u_vertical_scale': verticalScale,
        'u_flood_light_intensity': floodLightIntensity,
        'u_ground_shadow_factor': groundShadowFactor
    };
    if (tr.projection.name === 'globe') {
        uniformValues['u_tile_id'] = [
            coord.canonical.x,
            coord.canonical.y,
            1 << coord.canonical.z
        ];
        uniformValues['u_zoom_transition'] = zoomTransition;
        uniformValues['u_inv_rot_matrix'] = invMatrix;
        uniformValues['u_merc_center'] = mercatorCenter;
        uniformValues['u_up_dir'] = tr.projection.upVector(new CanonicalTileID(0, 0, 0), mercatorCenter[0] * EXTENT, mercatorCenter[1] * EXTENT);
        uniformValues['u_height_lift'] = heightLift;
    }
    return uniformValues;
};
const fillExtrusionDepthUniformValues = (matrix, edgeRadius, verticalScale) => {
    return {
        'u_matrix': matrix,
        'u_edge_radius': edgeRadius,
        'u_vertical_scale': verticalScale
    };
};
const fillExtrusionPatternUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, aoIntensityRadius, edgeRadius, coord, tile, heightLift, zoomTransition, mercatorCenter, invMatrix, floodLightColor, verticalScale) => {
    const uniformValues = fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, aoIntensityRadius, edgeRadius, coord, heightLift, zoomTransition, mercatorCenter, invMatrix, floodLightColor, verticalScale, 1, [
        0,
        0,
        0
    ]);
    const heightFactorUniform = { 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 };
    return extend$1(uniformValues, patternUniformValues(painter, tile), heightFactorUniform);
};
const fillExtrusionGroundEffectUniformValues = (painter, matrix, opacity, aoPass, meterToTile, ao, floodLightIntensity, floodLightColor, attenuation, edgeRadius, fbSize) => {
    const uniformValues = {
        'u_matrix': matrix,
        'u_opacity': opacity,
        'u_ao_pass': aoPass ? 1 : 0,
        'u_meter_to_tile': meterToTile,
        'u_ao': ao,
        'u_flood_light_intensity': floodLightIntensity,
        'u_flood_light_color': floodLightColor,
        'u_attenuation': attenuation,
        'u_edge_radius': edgeRadius,
        'u_fb': 0,
        'u_fb_size': fbSize
    };
    return uniformValues;
};

//      
const fillUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_emissive_strength': new Uniform1f(context)
});
const fillPatternUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_image': new Uniform1i(context),
    'u_texsize': new Uniform2f(context),
    'u_pixel_coord_upper': new Uniform2f(context),
    'u_pixel_coord_lower': new Uniform2f(context),
    'u_tile_units_to_pixels': new Uniform1f(context)
});
const fillOutlineUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_world': new Uniform2f(context)
});
const fillOutlinePatternUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_world': new Uniform2f(context),
    'u_image': new Uniform1i(context),
    'u_texsize': new Uniform2f(context),
    'u_pixel_coord_upper': new Uniform2f(context),
    'u_pixel_coord_lower': new Uniform2f(context),
    'u_tile_units_to_pixels': new Uniform1f(context)
});
const fillUniformValues = (matrix, emissiveStrength) => ({
    'u_matrix': matrix,
    'u_emissive_strength': emissiveStrength
});
const fillPatternUniformValues = (matrix, emissiveStrength, painter, tile) => extend$1(fillUniformValues(matrix, emissiveStrength), patternUniformValues(painter, tile));
const fillOutlineUniformValues = (matrix, emissiveStrength, drawingBufferSize) => ({
    'u_matrix': matrix,
    'u_world': drawingBufferSize,
    'u_emissive_strength': emissiveStrength
});
const fillOutlinePatternUniformValues = (matrix, emissiveStrength, painter, tile, drawingBufferSize) => extend$1(fillPatternUniformValues(matrix, emissiveStrength, painter, tile), { 'u_world': drawingBufferSize });

//      
const collisionUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_camera_to_center_distance': new Uniform1f(context),
    'u_extrude_scale': new Uniform2f(context)
});
const collisionCircleUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_inv_matrix': new UniformMatrix4f(context),
    'u_camera_to_center_distance': new Uniform1f(context),
    'u_viewport_size': new Uniform2f(context)
});
const collisionUniformValues = (matrix, transform, tile, projection) => {
    const pixelRatio = EXTENT / tile.tileSize;
    return {
        'u_matrix': matrix,
        'u_camera_to_center_distance': transform.getCameraToCenterDistance(projection),
        'u_extrude_scale': [
            transform.pixelsToGLUnits[0] / pixelRatio,
            transform.pixelsToGLUnits[1] / pixelRatio
        ]
    };
};
const collisionCircleUniformValues = (matrix, invMatrix, transform, projection) => {
    return {
        'u_matrix': matrix,
        'u_inv_matrix': invMatrix,
        'u_camera_to_center_distance': transform.getCameraToCenterDistance(projection),
        'u_viewport_size': [
            transform.width,
            transform.height
        ]
    };
};

//      
const debugUniforms = context => ({
    'u_color': new UniformColor(context),
    'u_matrix': new UniformMatrix4f(context),
    'u_overlay': new Uniform1i(context),
    'u_overlay_scale': new Uniform1f(context)
});
const debugUniformValues = (matrix, color, scaleRatio = 1) => ({
    'u_matrix': matrix,
    'u_color': color,
    'u_overlay': 0,
    'u_overlay_scale': scaleRatio
});

//      
const heatmapUniforms = context => ({
    'u_extrude_scale': new Uniform1f(context),
    'u_intensity': new Uniform1f(context),
    'u_matrix': new UniformMatrix4f(context),
    'u_inv_rot_matrix': new UniformMatrix4f(context),
    'u_merc_center': new Uniform2f(context),
    'u_tile_id': new Uniform3f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_up_dir': new Uniform3f(context)
});
const heatmapTextureUniforms = context => ({
    'u_image': new Uniform1i(context),
    'u_color_ramp': new Uniform1i(context),
    'u_opacity': new Uniform1f(context)
});
const identityMatrix$1 = mat4_1.create();
const heatmapUniformValues = (painter, coord, tile, invMatrix, mercatorCenter, zoom, intensity) => {
    const transform = painter.transform;
    const isGlobe = transform.projection.name === 'globe';
    const extrudeScale = isGlobe ? globePixelsToTileUnits(transform.zoom, coord.canonical) * transform._pixelsPerMercatorPixel : pixelsToTileUnits(tile, 1, zoom);
    const values = {
        'u_matrix': coord.projMatrix,
        'u_extrude_scale': extrudeScale,
        'u_intensity': intensity,
        'u_inv_rot_matrix': identityMatrix$1,
        'u_merc_center': [
            0,
            0
        ],
        'u_tile_id': [
            0,
            0,
            0
        ],
        'u_zoom_transition': 0,
        'u_up_dir': [
            0,
            0,
            0
        ]
    };
    if (isGlobe) {
        values['u_inv_rot_matrix'] = invMatrix;
        values['u_merc_center'] = mercatorCenter;
        values['u_tile_id'] = [
            coord.canonical.x,
            coord.canonical.y,
            1 << coord.canonical.z
        ];
        values['u_zoom_transition'] = globeToMercatorTransition(transform.zoom);
        const x = mercatorCenter[0] * EXTENT;
        const y = mercatorCenter[1] * EXTENT;
        values['u_up_dir'] = transform.projection.upVector(new CanonicalTileID(0, 0, 0), x, y);
    }
    return values;
};
const heatmapTextureUniformValues = (painter, layer, textureUnit, colorRampUnit) => {
    return {
        'u_image': textureUnit,
        'u_color_ramp': colorRampUnit,
        'u_opacity': layer.paint.get('heatmap-opacity')
    };
};

//      
const rasterUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_normalize_matrix': new UniformMatrix4f(context),
    'u_globe_matrix': new UniformMatrix4f(context),
    'u_tl_parent': new Uniform2f(context),
    'u_scale_parent': new Uniform1f(context),
    'u_fade_t': new Uniform1f(context),
    'u_opacity': new Uniform1f(context),
    'u_image0': new Uniform1i(context),
    'u_image1': new Uniform1i(context),
    'u_brightness_low': new Uniform1f(context),
    'u_brightness_high': new Uniform1f(context),
    'u_saturation_factor': new Uniform1f(context),
    'u_contrast_factor': new Uniform1f(context),
    'u_spin_weights': new Uniform3f(context),
    'u_perspective_transform': new Uniform2f(context),
    'u_colorization_mix': new Uniform4f(context),
    'u_colorization_scale': new Uniform2f(context),
    'u_color_ramp': new Uniform1i(context)
});
const rasterUniformValues = (matrix, normalizeMatrix, globeMatrix, parentTL, parentScaleBy, fade, layer, perspectiveTransform, colorRampUnit, colorMapInputMix, colorRange) => ({
    'u_matrix': matrix,
    'u_normalize_matrix': normalizeMatrix,
    'u_globe_matrix': globeMatrix,
    'u_tl_parent': parentTL,
    'u_scale_parent': parentScaleBy,
    'u_fade_t': fade.mix,
    'u_opacity': fade.opacity * layer.paint.get('raster-opacity'),
    'u_image0': 0,
    'u_image1': 1,
    'u_brightness_low': layer.paint.get('raster-brightness-min'),
    'u_brightness_high': layer.paint.get('raster-brightness-max'),
    'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')),
    'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')),
    'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate')),
    'u_perspective_transform': perspectiveTransform,
    'u_colorization_mix': colorMapInputMix,
    'u_colorization_scale': colorScaleFactors(colorRange),
    'u_color_ramp': colorRampUnit
});
function spinWeights(angle) {
    angle *= Math.PI / 180;
    const s = Math.sin(angle);
    const c = Math.cos(angle);
    return [
        (2 * c + 1) / 3,
        (-Math.sqrt(3) * s - c + 1) / 3,
        (Math.sqrt(3) * s - c + 1) / 3
    ];
}
function contrastFactor(contrast) {
    return contrast > 0 ? 1 / (1 - contrast) : 1 + contrast;
}
function saturationFactor(saturation) {
    return saturation > 0 ? 1 - 1 / (1.001 - saturation) : -saturation;
}
function colorScaleFactors([min, max]) {
    if (min === max)
        return [
            min,
            max
        ];
    // Account for tabulated color scale values which are defined at texel *centers*. Without this,
    // there is up to a half-texel misalignment between the intended value and the evaluated color.
    // This makes it much more straightforward to use precisely tabulated, categorical colors.
    const center = (max + min) / 2;
    const delta = (max - min) / 2 * COLOR_RAMP_RES / (COLOR_RAMP_RES - 1);
    min = center - delta;
    max = center + delta;
    // Precompute the offset and delta so that operations are moved out of the shader and
    // the raster value may be computed in-shader as `colorScale[0] + colorScale[1] * inputValue`
    return [
        -min / (max - min),
        1 / (max - min)
    ];
}

//      
const symbolIconUniforms = context => ({
    'u_is_size_zoom_constant': new Uniform1i(context),
    'u_is_size_feature_constant': new Uniform1i(context),
    'u_size_t': new Uniform1f(context),
    'u_size': new Uniform1f(context),
    'u_camera_to_center_distance': new Uniform1f(context),
    'u_rotate_symbol': new Uniform1i(context),
    'u_aspect_ratio': new Uniform1f(context),
    'u_fade_change': new Uniform1f(context),
    'u_matrix': new UniformMatrix4f(context),
    'u_label_plane_matrix': new UniformMatrix4f(context),
    'u_coord_matrix': new UniformMatrix4f(context),
    'u_is_text': new Uniform1i(context),
    'u_pitch_with_map': new Uniform1i(context),
    'u_texsize': new Uniform2f(context),
    'u_tile_id': new Uniform3f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_inv_rot_matrix': new UniformMatrix4f(context),
    'u_merc_center': new Uniform2f(context),
    'u_camera_forward': new Uniform3f(context),
    'u_tile_matrix': new UniformMatrix4f(context),
    'u_up_vector': new Uniform3f(context),
    'u_ecef_origin': new Uniform3f(context),
    'u_texture': new Uniform1i(context),
    'u_icon_transition': new Uniform1f(context)
});
const symbolSDFUniforms = context => ({
    'u_is_size_zoom_constant': new Uniform1i(context),
    'u_is_size_feature_constant': new Uniform1i(context),
    'u_size_t': new Uniform1f(context),
    'u_size': new Uniform1f(context),
    'u_camera_to_center_distance': new Uniform1f(context),
    'u_rotate_symbol': new Uniform1i(context),
    'u_aspect_ratio': new Uniform1f(context),
    'u_fade_change': new Uniform1f(context),
    'u_matrix': new UniformMatrix4f(context),
    'u_label_plane_matrix': new UniformMatrix4f(context),
    'u_coord_matrix': new UniformMatrix4f(context),
    'u_is_text': new Uniform1i(context),
    'u_pitch_with_map': new Uniform1i(context),
    'u_texsize': new Uniform2f(context),
    'u_texture': new Uniform1i(context),
    'u_gamma_scale': new Uniform1f(context),
    'u_device_pixel_ratio': new Uniform1f(context),
    'u_tile_id': new Uniform3f(context),
    'u_zoom_transition': new Uniform1f(context),
    'u_inv_rot_matrix': new UniformMatrix4f(context),
    'u_merc_center': new Uniform2f(context),
    'u_camera_forward': new Uniform3f(context),
    'u_tile_matrix': new UniformMatrix4f(context),
    'u_up_vector': new Uniform3f(context),
    'u_ecef_origin': new Uniform3f(context),
    'u_is_halo': new Uniform1i(context)
});
const symbolTextAndIconUniforms = context => ({
    'u_is_size_zoom_constant': new Uniform1i(context),
    'u_is_size_feature_constant': new Uniform1i(context),
    'u_size_t': new Uniform1f(context),
    'u_size': new Uniform1f(context),
    'u_camera_to_center_distance': new Uniform1f(context),
    'u_rotate_symbol': new Uniform1i(context),
    'u_aspect_ratio': new Uniform1f(context),
    'u_fade_change': new Uniform1f(context),
    'u_matrix': new UniformMatrix4f(context),
    'u_label_plane_matrix': new UniformMatrix4f(context),
    'u_coord_matrix': new UniformMatrix4f(context),
    'u_is_text': new Uniform1i(context),
    'u_pitch_with_map': new Uniform1i(context),
    'u_texsize': new Uniform2f(context),
    'u_texsize_icon': new Uniform2f(context),
    'u_texture': new Uniform1i(context),
    'u_texture_icon': new Uniform1i(context),
    'u_gamma_scale': new Uniform1f(context),
    'u_device_pixel_ratio': new Uniform1f(context),
    'u_is_halo': new Uniform1i(context)
});
const identityMatrix = mat4_1.create();
const symbolIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, isText, texSize, coord, zoomTransition, mercatorCenter, invMatrix, upVector, projection, transition) => {
    const transform = painter.transform;
    const values = {
        'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'),
        'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'),
        'u_size_t': size ? size.uSizeT : 0,
        'u_size': size ? size.uSize : 0,
        'u_camera_to_center_distance': transform.getCameraToCenterDistance(projection),
        'u_rotate_symbol': +rotateInShader,
        'u_aspect_ratio': transform.width / transform.height,
        'u_fade_change': painter.options.fadeDuration ? painter.symbolFadeChange : 1,
        'u_matrix': matrix,
        'u_label_plane_matrix': labelPlaneMatrix,
        'u_coord_matrix': glCoordMatrix,
        'u_is_text': +isText,
        'u_pitch_with_map': +pitchWithMap,
        'u_texsize': texSize,
        'u_texture': 0,
        'u_tile_id': [
            0,
            0,
            0
        ],
        'u_zoom_transition': 0,
        'u_inv_rot_matrix': identityMatrix,
        'u_merc_center': [
            0,
            0
        ],
        'u_camera_forward': [
            0,
            0,
            0
        ],
        'u_ecef_origin': [
            0,
            0,
            0
        ],
        'u_tile_matrix': identityMatrix,
        'u_up_vector': [
            0,
            -1,
            0
        ],
        'u_icon_transition': transition ? transition : 0
    };
    if (projection.name === 'globe') {
        values['u_tile_id'] = [
            coord.canonical.x,
            coord.canonical.y,
            1 << coord.canonical.z
        ];
        values['u_zoom_transition'] = zoomTransition;
        values['u_inv_rot_matrix'] = invMatrix;
        values['u_merc_center'] = mercatorCenter;
        values['u_camera_forward'] = transform._camera.forward();
        values['u_ecef_origin'] = globeECEFOrigin(transform.globeMatrix, coord.toUnwrapped());
        values['u_tile_matrix'] = Float32Array.from(transform.globeMatrix);
        values['u_up_vector'] = upVector;
    }
    return values;
};
const symbolSDFUniformValues = (functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, isText, texSize, isHalo, coord, zoomTransition, mercatorCenter, invMatrix, upVector, projection) => {
    return extend$1(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, isText, texSize, coord, zoomTransition, mercatorCenter, invMatrix, upVector, projection), {
        'u_gamma_scale': pitchWithMap ? painter.transform.getCameraToCenterDistance(projection) * Math.cos(painter.terrain ? 0 : painter.transform._pitch) : 1,
        'u_device_pixel_ratio': exported$1.devicePixelRatio,
        'u_is_halo': +isHalo,
        undefined
    });
};
const symbolTextAndIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, texSizeSDF, texSizeIcon, coord, zoomTransition, mercatorCenter, invMatrix, upVector, projection) => {
    return extend$1(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, true, texSizeSDF, true, coord, zoomTransition, mercatorCenter, invMatrix, upVector, projection), {
        'u_texsize_icon': texSizeIcon,
        'u_texture_icon': 1
    });
};

//      
const backgroundUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_opacity': new Uniform1f(context),
    'u_color': new UniformColor(context)
});
const backgroundPatternUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_opacity': new Uniform1f(context),
    'u_image': new Uniform1i(context),
    'u_pattern_tl': new Uniform2f(context),
    'u_pattern_br': new Uniform2f(context),
    'u_texsize': new Uniform2f(context),
    'u_pattern_size': new Uniform2f(context),
    'u_pixel_coord_upper': new Uniform2f(context),
    'u_pixel_coord_lower': new Uniform2f(context),
    'u_tile_units_to_pixels': new Uniform1f(context)
});
const backgroundUniformValues = (matrix, emissiveStrength, opacity, color) => ({
    'u_matrix': matrix,
    'u_emissive_strength': emissiveStrength,
    'u_opacity': opacity,
    'u_color': color
});
const backgroundPatternUniformValues = (matrix, emissiveStrength, opacity, painter, image, scope, tile) => extend$1(bgPatternUniformValues(image, scope, painter, tile), {
    'u_matrix': matrix,
    'u_emissive_strength': emissiveStrength,
    'u_opacity': opacity
});

//      
const skyboxUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_sun_direction': new Uniform3f(context),
    'u_cubemap': new Uniform1i(context),
    'u_opacity': new Uniform1f(context),
    'u_temporal_offset': new Uniform1f(context)
});
const skyboxUniformValues = (matrix, sunDirection, cubemap, opacity, temporalOffset) => ({
    'u_matrix': matrix,
    'u_sun_direction': sunDirection,
    'u_cubemap': cubemap,
    'u_opacity': opacity,
    'u_temporal_offset': temporalOffset
});
const skyboxGradientUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_color_ramp': new Uniform1i(context),
    // radial gradient uniforms
    'u_center_direction': new Uniform3f(context),
    'u_radius': new Uniform1f(context),
    'u_opacity': new Uniform1f(context),
    'u_temporal_offset': new Uniform1f(context)
});
const skyboxGradientUniformValues = (matrix, centerDirection, radius, opacity, temporalOffset) => {
    return {
        'u_matrix': matrix,
        'u_color_ramp': 0,
        'u_center_direction': centerDirection,
        'u_radius': degToRad(radius),
        'u_opacity': opacity,
        'u_temporal_offset': temporalOffset
    };
};

//      
const skyboxCaptureUniforms = context => ({
    'u_matrix_3f': new UniformMatrix3f(context),
    'u_sun_direction': new Uniform3f(context),
    'u_sun_intensity': new Uniform1f(context),
    'u_color_tint_r': new Uniform4f(context),
    'u_color_tint_m': new Uniform4f(context),
    'u_luminance': new Uniform1f(context)
});
const skyboxCaptureUniformValues = (matrix, sunDirection, sunIntensity, atmosphereColor, atmosphereHaloColor) => ({
    'u_matrix_3f': matrix,
    'u_sun_direction': sunDirection,
    'u_sun_intensity': sunIntensity,
    'u_color_tint_r': [
        atmosphereColor.r,
        atmosphereColor.g,
        atmosphereColor.b,
        atmosphereColor.a
    ],
    'u_color_tint_m': [
        atmosphereHaloColor.r,
        atmosphereHaloColor.g,
        atmosphereHaloColor.b,
        atmosphereHaloColor.a
    ],
    'u_luminance': 0.00005
});

//      
const TextureSlots = {
    BaseColor: 5,
    MetallicRoughness: 6,
    Normal: 7,
    Occlusion: 8,
    Emission: 9,
    ShadowMap0: 10
};

//      
const modelUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_lighting_matrix': new UniformMatrix4f(context),
    'u_normal_matrix': new UniformMatrix4f(context),
    'u_lightpos': new Uniform3f(context),
    'u_lightintensity': new Uniform1f(context),
    'u_lightcolor': new Uniform3f(context),
    'u_camera_pos': new Uniform3f(context),
    'u_opacity': new Uniform1f(context),
    'u_baseColorFactor': new Uniform4f(context),
    'u_emissiveFactor': new Uniform4f(context),
    'u_metallicFactor': new Uniform1f(context),
    'u_roughnessFactor': new Uniform1f(context),
    'u_baseTextureIsAlpha': new Uniform1i(context),
    'u_alphaMask': new Uniform1i(context),
    'u_alphaCutoff': new Uniform1f(context),
    'u_baseColorTexture': new Uniform1i(context),
    'u_metallicRoughnessTexture': new Uniform1i(context),
    'u_normalTexture': new Uniform1i(context),
    'u_occlusionTexture': new Uniform1i(context),
    'u_emissionTexture': new Uniform1i(context),
    'u_color_mix': new Uniform4f(context),
    'u_aoIntensity': new Uniform1f(context)
});
const modelUniformValues = (matrix, lightingMatrix, normalMatrix, painter, opacity, baseColorFactor, emissiveFactor, metallicFactor, roughnessFactor, material, layer, cameraPos = [
    0,
    0,
    0
]) => {
    const light = painter.style.light;
    const _lp = light.properties.get('position');
    const lightPos = [
        -_lp.x,
        -_lp.y,
        _lp.z
    ];
    const lightMat = mat3_1.create();
    const anchor = light.properties.get('anchor');
    if (anchor === 'viewport') {
        mat3_1.fromRotation(lightMat, -painter.transform.angle);
        vec3_1.transformMat3(lightPos, lightPos, lightMat);
    }
    const alphaMask = material.alphaMode === 'MASK';
    const lightColor = light.properties.get('color');
    const aoIntensity = layer.paint.get('model-ambient-occlusion-intensity');
    const colorMix = layer.paint.get('model-color').constantOr(Color$1.white);
    const colorMixIntensity = layer.paint.get('model-color-mix-intensity').constantOr(0);
    const uniformValues = {
        'u_matrix': matrix,
        'u_lighting_matrix': lightingMatrix,
        'u_normal_matrix': normalMatrix,
        'u_lightpos': lightPos,
        'u_lightintensity': light.properties.get('intensity'),
        'u_lightcolor': [
            lightColor.r,
            lightColor.g,
            lightColor.b
        ],
        'u_camera_pos': cameraPos,
        'u_opacity': opacity,
        'u_baseTextureIsAlpha': 0,
        'u_alphaMask': +alphaMask,
        'u_alphaCutoff': material.alphaCutoff,
        'u_baseColorFactor': [
            baseColorFactor.r,
            baseColorFactor.g,
            baseColorFactor.b,
            baseColorFactor.a
        ],
        'u_emissiveFactor': [
            emissiveFactor[0],
            emissiveFactor[1],
            emissiveFactor[2],
            1
        ],
        'u_metallicFactor': metallicFactor,
        'u_roughnessFactor': roughnessFactor,
        'u_baseColorTexture': TextureSlots.BaseColor,
        'u_metallicRoughnessTexture': TextureSlots.MetallicRoughness,
        'u_normalTexture': TextureSlots.Normal,
        'u_occlusionTexture': TextureSlots.Occlusion,
        'u_emissionTexture': TextureSlots.Emission,
        'u_color_mix': [
            colorMix.r,
            colorMix.g,
            colorMix.b,
            colorMixIntensity
        ],
        'u_aoIntensity': aoIntensity
    };
    return uniformValues;
};
const modelDepthUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_instance': new UniformMatrix4f(context),
    'u_node_matrix': new UniformMatrix4f(context)
});
const emptyMat4 = new Float32Array(16);
const modelDepthUniformValues = (matrix, instance = emptyMat4, nodeMatrix = emptyMat4) => {
    return {
        'u_matrix': matrix,
        'u_instance': instance,
        'u_node_matrix': nodeMatrix
    };
};

//      
const groundShadowUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_ground_shadow_factor': new Uniform3f(context)
});
const groundShadowUniformValues = (matrix, shadowFactor) => ({
    'u_matrix': matrix,
    'u_ground_shadow_factor': shadowFactor
});

//      
const starsUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_up': new Uniform3f(context),
    'u_right': new Uniform3f(context),
    'u_intensity_multiplier': new Uniform1f(context)
});
const starsUniformValues = (matrix, up, right, intensityMultiplier) => ({
    'u_matrix': Float32Array.from(matrix),
    'u_up': up,
    'u_right': right,
    'u_intensity_multiplier': intensityMultiplier
});

//      
const programUniforms = {
    fillExtrusion: fillExtrusionUniforms,
    fillExtrusionDepth: fillExtrusionDepthUniforms,
    fillExtrusionPattern: fillExtrusionPatternUniforms,
    fillExtrusionGroundEffect: fillExtrusionGroundEffectUniforms,
    fill: fillUniforms,
    fillPattern: fillPatternUniforms,
    fillOutline: fillOutlineUniforms,
    fillOutlinePattern: fillOutlinePatternUniforms,
    circle: circleUniforms,
    collisionBox: collisionUniforms,
    collisionCircle: collisionCircleUniforms,
    debug: debugUniforms,
    clippingMask: clippingMaskUniforms,
    heatmap: heatmapUniforms,
    heatmapTexture: heatmapTextureUniforms,
    hillshade: hillshadeUniforms,
    hillshadePrepare: hillshadePrepareUniforms,
    line: lineUniforms,
    linePattern: linePatternUniforms,
    raster: rasterUniforms,
    symbolIcon: symbolIconUniforms,
    symbolSDF: symbolSDFUniforms,
    symbolTextAndIcon: symbolTextAndIconUniforms,
    background: backgroundUniforms,
    backgroundPattern: backgroundPatternUniforms,
    terrainRaster: terrainRasterUniforms,
    terrainDepth: terrainRasterUniforms,
    skybox: skyboxUniforms,
    skyboxGradient: skyboxGradientUniforms,
    skyboxCapture: skyboxCaptureUniforms,
    globeRaster: globeRasterUniforms,
    globeAtmosphere: atmosphereUniforms,
    model: modelUniforms,
    modelDepth: modelDepthUniforms,
    groundShadow: groundShadowUniforms,
    stars: starsUniforms
};

//      
let quadTriangles;
function drawCollisionDebug(painter, sourceCache, layer, coords, translate, translateAnchor, isText) {
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const program = painter.getOrCreateProgram('collisionBox');
    const tileBatches = [];
    let circleCount = 0;
    let circleOffset = 0;
    for (let i = 0; i < coords.length; i++) {
        const coord = coords[i];
        const tile = sourceCache.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        const tileMatrix = getCollisionDebugTileProjectionMatrix(coord, bucket, tr);
        let posMatrix = tileMatrix;
        if (translate[0] !== 0 || translate[1] !== 0) {
            posMatrix = painter.translatePosMatrix(tileMatrix, tile, translate, translateAnchor);
        }
        const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox;
        // Get collision circle data of this bucket
        const circleArray = bucket.collisionCircleArray;
        if (circleArray.length > 0) {
            // We need to know the projection matrix that was used for projecting collision circles to the screen.
            // This might vary between buckets as the symbol placement is a continous process. This matrix is
            // required for transforming points from previous screen space to the current one
            const invTransform = mat4_1.create();
            const transform = posMatrix;
            mat4_1.mul(invTransform, bucket.placementInvProjMatrix, tr.glCoordMatrix);
            mat4_1.mul(invTransform, invTransform, bucket.placementViewportMatrix);
            tileBatches.push({
                circleArray,
                circleOffset,
                transform,
                invTransform,
                projection: bucket.getProjection()
            });
            circleCount += circleArray.length / 4;
            // 4 values per circle
            circleOffset = circleCount;
        }
        if (!buffers)
            continue;
        if (painter.terrain)
            painter.terrain.setupElevationDraw(tile, program);
        program.draw(painter, gl.LINES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, collisionUniformValues(posMatrix, tr, tile, bucket.getProjection()), layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, buffers.segments, null, tr.zoom, null, [
            buffers.collisionVertexBuffer,
            buffers.collisionVertexBufferExt
        ]);
    }
    if (!isText || !tileBatches.length) {
        return;
    }
    // Render collision circles
    const circleProgram = painter.getOrCreateProgram('collisionCircle');
    // Construct vertex data
    const vertexData = new StructArrayLayout2f1f2i16();
    vertexData.resize(circleCount * 4);
    vertexData._trim();
    let vertexOffset = 0;
    for (const batch of tileBatches) {
        for (let i = 0; i < batch.circleArray.length / 4; i++) {
            const circleIdx = i * 4;
            const x = batch.circleArray[circleIdx + 0];
            const y = batch.circleArray[circleIdx + 1];
            const radius = batch.circleArray[circleIdx + 2];
            const collision = batch.circleArray[circleIdx + 3];
            // 4 floats per vertex, 4 vertices per quad
            vertexData.emplace(vertexOffset++, x, y, radius, collision, 0);
            vertexData.emplace(vertexOffset++, x, y, radius, collision, 1);
            vertexData.emplace(vertexOffset++, x, y, radius, collision, 2);
            vertexData.emplace(vertexOffset++, x, y, radius, collision, 3);
        }
    }
    if (!quadTriangles || quadTriangles.length < circleCount * 2) {
        quadTriangles = createQuadTriangles(circleCount);
    }
    const indexBuffer = context.createIndexBuffer(quadTriangles, true);
    const vertexBuffer = context.createVertexBuffer(vertexData, collisionCircleLayout.members, true);
    // Render batches
    for (const batch of tileBatches) {
        const uniforms = collisionCircleUniformValues(batch.transform, batch.invTransform, tr, batch.projection);
        circleProgram.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, layer.id, vertexBuffer, indexBuffer, SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2), null, tr.zoom);
    }
    vertexBuffer.destroy();
    indexBuffer.destroy();
}
function createQuadTriangles(quadCount) {
    const triCount = quadCount * 2;
    const array = new StructArrayLayout3ui6();
    array.resize(triCount);
    array._trim();
    // Two triangles and 4 vertices per quad.
    for (let i = 0; i < triCount; i++) {
        const idx = i * 6;
        array.uint16[idx + 0] = i * 4 + 0;
        array.uint16[idx + 1] = i * 4 + 1;
        array.uint16[idx + 2] = i * 4 + 2;
        array.uint16[idx + 3] = i * 4 + 2;
        array.uint16[idx + 4] = i * 4 + 3;
        array.uint16[idx + 5] = i * 4 + 0;
    }
    return array;
}

//      
const identityMat4 = mat4_1.create();
function drawSymbols(painter, sourceCache, layer, coords, variableOffsets) {
    if (painter.renderPass !== 'translucent')
        return;
    // Disable the stencil test so that labels aren't clipped to tile boundaries.
    const stencilMode = StencilMode.disabled;
    const colorMode = painter.colorModeForRenderPass();
    const variablePlacement = layer.layout.get('text-variable-anchor');
    //Compute variable-offsets before painting since icons and text data positioning
    //depend on each other in this case.
    if (variablePlacement) {
        updateVariableAnchors(coords, painter, layer, sourceCache, layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), variableOffsets);
    }
    if (layer.paint.get('icon-opacity').constantOr(1) !== 0) {
        drawLayerSymbols(painter, sourceCache, layer, coords, false, layer.paint.get('icon-translate'), layer.paint.get('icon-translate-anchor'), layer.layout.get('icon-rotation-alignment'), layer.layout.get('icon-pitch-alignment'), layer.layout.get('icon-keep-upright'), stencilMode, colorMode);
    }
    if (layer.paint.get('text-opacity').constantOr(1) !== 0) {
        drawLayerSymbols(painter, sourceCache, layer, coords, true, layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.layout.get('text-keep-upright'), stencilMode, colorMode);
    }
    if (sourceCache.map.showCollisionBoxes) {
        drawCollisionDebug(painter, sourceCache, layer, coords, layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), true);
        drawCollisionDebug(painter, sourceCache, layer, coords, layer.paint.get('icon-translate'), layer.paint.get('icon-translate-anchor'), false);
    }
}
function computeGlobeCameraUp(transform) {
    const viewMatrix = transform._camera.getWorldToCamera(transform.worldSize, 1);
    const viewToEcef = mat4_1.multiply([], viewMatrix, transform.globeMatrix);
    mat4_1.invert(viewToEcef, viewToEcef);
    const cameraUpVector = [
        0,
        0,
        0
    ];
    const up = [
        0,
        1,
        0,
        0
    ];
    vec4_1.transformMat4(up, up, viewToEcef);
    cameraUpVector[0] = up[0];
    cameraUpVector[1] = up[1];
    cameraUpVector[2] = up[2];
    vec3_1.normalize(cameraUpVector, cameraUpVector);
    return cameraUpVector;
}
function calculateVariableRenderShift({width, height, anchor, textOffset, textScale}, renderTextSize) {
    const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);
    const shiftX = -(horizontalAlign - 0.5) * width;
    const shiftY = -(verticalAlign - 0.5) * height;
    const variableOffset = evaluateVariableOffset(anchor, textOffset);
    return new Point$2((shiftX / textScale + variableOffset[0]) * renderTextSize, (shiftY / textScale + variableOffset[1]) * renderTextSize);
}
function updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, variableOffsets) {
    const tr = painter.transform;
    const rotateWithMap = rotationAlignment === 'map';
    const pitchWithMap = pitchAlignment === 'map';
    for (const coord of coords) {
        const tile = sourceCache.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket || !bucket.text || !bucket.text.segments.get().length) {
            continue;
        }
        const sizeData = bucket.textSizeData;
        const size = evaluateSizeForZoom(sizeData, tr.zoom);
        const tileMatrix = getSymbolTileProjectionMatrix(coord, bucket.getProjection(), tr);
        const pixelsToTileUnits = tr.calculatePixelsToTileUnitsMatrix(tile);
        const labelPlaneMatrix = getLabelPlaneMatrixForRendering(tileMatrix, tile.tileID.canonical, pitchWithMap, rotateWithMap, tr, bucket.getProjection(), pixelsToTileUnits);
        const updateTextFitIcon = bucket.hasIconTextFit() && bucket.hasIconData();
        if (size) {
            const tileScale = Math.pow(2, tr.zoom - tile.tileID.overscaledZ);
            updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize, tr, labelPlaneMatrix, coord, tileScale, size, updateTextFitIcon);
        }
    }
}
function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize, transform, labelPlaneMatrix, coord, tileScale, size, updateTextFitIcon) {
    const placedSymbols = bucket.text.placedSymbolArray;
    const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;
    const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray;
    const placedTextShifts = {};
    const projection = bucket.getProjection();
    const tileMatrix = getSymbolTileProjectionMatrix(coord, projection, transform);
    const elevation = transform.elevation;
    const metersToTile = projection.upVectorScale(coord.canonical, transform.center.lat, transform.worldSize).metersToTile;
    dynamicTextLayoutVertexArray.clear();
    for (let s = 0; s < placedSymbols.length; s++) {
        const symbol = placedSymbols.get(s);
        const {tileAnchorX, tileAnchorY, numGlyphs} = symbol;
        const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;
        const variableOffset = !symbol.hidden && symbol.crossTileID && !skipOrientation ? variableOffsets[symbol.crossTileID] : null;
        if (!variableOffset) {
            // These symbols are from a justification that is not being used, or a label that wasn't placed
            // so we don't need to do the extra math to figure out what incremental shift to apply.
            hideGlyphs(numGlyphs, dynamicTextLayoutVertexArray);
        } else {
            let dx = 0, dy = 0, dz = 0;
            if (elevation) {
                const h = elevation ? elevation.getAtTileOffset(coord, tileAnchorX, tileAnchorY) : 0;
                const [ux, uy, uz] = projection.upVector(coord.canonical, tileAnchorX, tileAnchorY);
                dx = h * ux * metersToTile;
                dy = h * uy * metersToTile;
                dz = h * uz * metersToTile;
            }
            let [x, y, z, w] = project(symbol.projectedAnchorX + dx, symbol.projectedAnchorY + dy, symbol.projectedAnchorZ + dz, pitchWithMap ? tileMatrix : labelPlaneMatrix);
            const perspectiveRatio = getPerspectiveRatio(transform.getCameraToCenterDistance(projection), w);
            let renderTextSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / ONE_EM;
            if (pitchWithMap) {
                // Go from size in pixels to equivalent size in tile units
                renderTextSize *= bucket.tilePixelRatio / tileScale;
            }
            const shift = calculateVariableRenderShift(variableOffset, renderTextSize);
            // Usual case is that we take the projected anchor and add the pixel-based shift
            // calculated above. In the (somewhat weird) case of pitch-aligned text, we add an equivalent
            // tile-unit based shift to the anchor before projecting to the label plane.
            if (pitchWithMap) {
                ({x, y, z} = projection.projectTilePoint(tileAnchorX + shift.x, tileAnchorY + shift.y, coord.canonical));
                [x, y, z] = project(x + dx, y + dy, z + dz, labelPlaneMatrix);
            } else {
                if (rotateWithMap)
                    shift._rotate(-transform.angle);
                x += shift.x;
                y += shift.y;
                z = 0;
            }
            const angle = bucket.allowVerticalPlacement && symbol.placedOrientation === WritingMode.vertical ? Math.PI / 2 : 0;
            for (let g = 0; g < numGlyphs; g++) {
                addDynamicAttributes(dynamicTextLayoutVertexArray, x, y, z, angle);
            }
            //Only offset horizontal text icons
            if (updateTextFitIcon && symbol.associatedIconIndex >= 0) {
                placedTextShifts[symbol.associatedIconIndex] = {
                    x,
                    y,
                    z,
                    angle
                };
            }
        }
    }
    if (updateTextFitIcon) {
        dynamicIconLayoutVertexArray.clear();
        const placedIcons = bucket.icon.placedSymbolArray;
        for (let i = 0; i < placedIcons.length; i++) {
            const placedIcon = placedIcons.get(i);
            const {numGlyphs} = placedIcon;
            const shift = placedTextShifts[i];
            if (placedIcon.hidden || !shift) {
                hideGlyphs(numGlyphs, dynamicIconLayoutVertexArray);
            } else {
                const {x, y, z, angle} = shift;
                for (let g = 0; g < numGlyphs; g++) {
                    addDynamicAttributes(dynamicIconLayoutVertexArray, x, y, z, angle);
                }
            }
        }
        bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);
    }
    bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);
}
function getSymbolProgramName(isSDF, isText, bucket) {
    if (bucket.iconsInText && isText) {
        return 'symbolTextAndIcon';
    } else if (isSDF) {
        return 'symbolSDF';
    } else {
        return 'symbolIcon';
    }
}
function drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode) {
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const rotateWithMap = rotationAlignment === 'map';
    const pitchWithMap = pitchAlignment === 'map';
    const alongLine = rotateWithMap && layer.layout.get('symbol-placement') !== 'point';
    // Line label rotation happens in `updateLineLabels`
    // Pitched point labels are automatically rotated by the labelPlaneMatrix projection
    // Unpitched point labels need to have their rotation applied after projection
    const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;
    const hasSortKey = layer.layout.get('symbol-sort-key').constantOr(1) !== undefined;
    let sortFeaturesByKey = false;
    const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
    const mercatorCenter = [
        mercatorXfromLng(tr.center.lng),
        mercatorYfromLat(tr.center.lat)
    ];
    const variablePlacement = layer.layout.get('text-variable-anchor');
    const isGlobeProjection = tr.projection.name === 'globe';
    const tileRenderState = [];
    const mercatorCameraUp = [
        0,
        -1,
        0
    ];
    let globeCameraUp = mercatorCameraUp;
    if ((isGlobeProjection || tr.mercatorFromTransition) && !rotateWithMap) {
        // Each symbol rotating with the viewport requires per-instance information about
        // how to align with the viewport. In 2D case rotation is shared between all of the symbols and
        // hence embedded in the label plane matrix but in globe view this needs to be computed at runtime.
        // Camera up vector together with surface normals can be used to find the correct orientation for each symbol.
        globeCameraUp = computeGlobeCameraUp(tr);
    }
    for (const coord of coords) {
        const tile = sourceCache.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        // Allow rendering of buckets built for globe projection in mercator mode
        // until the substitute tile has been loaded
        if (bucket.projection.name === 'mercator' && isGlobeProjection) {
            continue;
        }
        const buffers = isText ? bucket.text : bucket.icon;
        if (!buffers || bucket.fullyClipped || !buffers.segments.get().length)
            continue;
        const programConfiguration = buffers.programConfigurations.get(layer.id);
        const isSDF = isText || bucket.sdfIcons;
        const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
        const transformed = pitchWithMap || tr.pitch !== 0;
        const size = evaluateSizeForZoom(sizeData, tr.zoom);
        let texSize;
        let texSizeIcon = [
            0,
            0
        ];
        let atlasTexture;
        let atlasInterpolation;
        let atlasTextureIcon = null;
        let atlasInterpolationIcon;
        if (isText) {
            atlasTexture = tile.glyphAtlasTexture;
            atlasInterpolation = gl.LINEAR;
            texSize = tile.glyphAtlasTexture.size;
            if (bucket.iconsInText) {
                texSizeIcon = tile.imageAtlasTexture.size;
                atlasTextureIcon = tile.imageAtlasTexture;
                const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera';
                atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST;
            }
        } else {
            const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear;
            atlasTexture = tile.imageAtlasTexture;
            atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? gl.LINEAR : gl.NEAREST;
            texSize = tile.imageAtlasTexture.size;
        }
        const bucketIsGlobeProjection = bucket.projection.name === 'globe';
        const cameraUpVector = bucketIsGlobeProjection ? globeCameraUp : mercatorCameraUp;
        const globeToMercator = bucketIsGlobeProjection ? globeToMercatorTransition(tr.zoom) : 0;
        const tileMatrix = getSymbolTileProjectionMatrix(coord, bucket.getProjection(), tr);
        const s = tr.calculatePixelsToTileUnitsMatrix(tile);
        const labelPlaneMatrixRendering = getLabelPlaneMatrixForRendering(tileMatrix, tile.tileID.canonical, pitchWithMap, rotateWithMap, tr, bucket.getProjection(), s);
        // labelPlaneMatrixInv is used for converting vertex pos to tile coordinates needed for sampling elevation.
        const labelPlaneMatrixInv = painter.terrain && pitchWithMap && alongLine ? mat4_1.invert(mat4_1.create(), labelPlaneMatrixRendering) : identityMat4;
        const glCoordMatrix = getGlCoordMatrix(tileMatrix, tile.tileID.canonical, pitchWithMap, rotateWithMap, tr, bucket.getProjection(), s);
        const hasVariableAnchors = variablePlacement && bucket.hasTextData();
        const updateTextFitIcon = bucket.hasIconTextFit() && hasVariableAnchors && bucket.hasIconData();
        if (alongLine) {
            const elevation = tr.elevation;
            const getElevation = elevation ? elevation.getAtTileOffsetFunc(coord, tr.center.lat, tr.worldSize, bucket.getProjection()) : null;
            const labelPlaneMatrixPlacement = getLabelPlaneMatrixForPlacement(tileMatrix, tile.tileID.canonical, pitchWithMap, rotateWithMap, tr, bucket.getProjection(), s);
            updateLineLabels(bucket, tileMatrix, painter, isText, labelPlaneMatrixPlacement, glCoordMatrix, pitchWithMap, keepUpright, getElevation, coord);
        }
        const projectedPosOnLabelSpace = alongLine || isText && variablePlacement || updateTextFitIcon;
        const matrix = painter.translatePosMatrix(tileMatrix, tile, translate, translateAnchor);
        const uLabelPlaneMatrix = projectedPosOnLabelSpace ? identityMat4 : labelPlaneMatrixRendering;
        const uglCoordMatrix = painter.translatePosMatrix(glCoordMatrix, tile, translate, translateAnchor, true);
        const invMatrix = bucket.getProjection().createInversionMatrix(tr, coord.canonical);
        const transitionProgress = layer.paint.get('icon-image-cross-fade').constantOr(0);
        const baseDefines = [];
        if (painter.terrainRenderModeElevated() && pitchWithMap) {
            baseDefines.push('PITCH_WITH_MAP_TERRAIN');
        }
        if (bucketIsGlobeProjection) {
            baseDefines.push('PROJECTION_GLOBE_VIEW');
            if (projectedPosOnLabelSpace) {
                baseDefines.push('PROJECTED_POS_ON_VIEWPORT');
            }
        }
        if (transitionProgress > 0) {
            baseDefines.push('ICON_TRANSITION');
        }
        if (buffers.zOffsetVertexBuffer) {
            baseDefines.push('Z_OFFSET');
        }
        const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0;
        let uniformValues;
        if (isSDF) {
            if (!bucket.iconsInText) {
                uniformValues = symbolSDFUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, isText, texSize, true, coord, globeToMercator, mercatorCenter, invMatrix, cameraUpVector, bucket.getProjection());
            } else {
                uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, texSize, texSizeIcon, coord, globeToMercator, mercatorCenter, invMatrix, cameraUpVector, bucket.getProjection());
            }
        } else {
            uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, isText, texSize, coord, globeToMercator, mercatorCenter, invMatrix, cameraUpVector, bucket.getProjection(), transitionProgress);
        }
        const program = painter.getOrCreateProgram(getSymbolProgramName(isSDF, isText, bucket), {
            config: programConfiguration,
            defines: baseDefines
        });
        const state = {
            program,
            buffers,
            uniformValues,
            atlasTexture,
            atlasTextureIcon,
            atlasInterpolation,
            atlasInterpolationIcon,
            isSDF,
            hasHalo,
            tile,
            labelPlaneMatrixInv
        };
        if (hasSortKey && bucket.canOverlap) {
            sortFeaturesByKey = true;
            const oldSegments = buffers.segments.get();
            for (const segment of oldSegments) {
                tileRenderState.push({
                    segments: new SegmentVector([segment]),
                    sortKey: segment.sortKey,
                    state
                });
            }
        } else {
            tileRenderState.push({
                segments: buffers.segments,
                sortKey: 0,
                state
            });
        }
    }
    if (sortFeaturesByKey) {
        tileRenderState.sort((a, b) => a.sortKey - b.sortKey);
    }
    for (const segmentState of tileRenderState) {
        const state = segmentState.state;
        if (painter.terrain) {
            const options = {
                useDepthForOcclusion: tr.depthOcclusionForSymbolsAndCircles,
                labelPlaneMatrixInv: state.labelPlaneMatrixInv
            };
            painter.terrain.setupElevationDraw(state.tile, state.program, options);
        }
        context.activeTexture.set(gl.TEXTURE0);
        state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE);
        if (state.atlasTextureIcon) {
            context.activeTexture.set(gl.TEXTURE1);
            if (state.atlasTextureIcon) {
                state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE);
            }
        }
        painter.uploadCommonLightUniforms(painter.context, state.program);
        if (state.hasHalo) {
            const uniformValues = state.uniformValues;
            uniformValues['u_is_halo'] = 1;
            drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, 2);
            uniformValues['u_is_halo'] = 0;
        } else {
            if (state.isSDF) {
                const uniformValues = state.uniformValues;
                if (state.hasHalo) {
                    uniformValues['u_is_halo'] = 1;
                    drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, 1);
                }
                uniformValues['u_is_halo'] = 0;
            }
            drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, 1);
        }
    }
}
function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues, instanceCount) {
    const context = painter.context;
    const gl = context.gl;
    const dynamicBuffers = [
        buffers.dynamicLayoutVertexBuffer,
        buffers.opacityVertexBuffer,
        buffers.iconTransitioningVertexBuffer,
        buffers.globeExtVertexBuffer,
        buffers.zOffsetVertexBuffer
    ];
    program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), dynamicBuffers, instanceCount);
}

//      
function drawCircles(painter, sourceCache, layer, coords) {
    if (painter.renderPass !== 'translucent')
        return;
    const opacity = layer.paint.get('circle-opacity');
    const strokeWidth = layer.paint.get('circle-stroke-width');
    const strokeOpacity = layer.paint.get('circle-stroke-opacity');
    const sortFeaturesByKey = layer.layout.get('circle-sort-key').constantOr(1) !== undefined;
    const emissiveStrength = layer.paint.get('circle-emissive-strength');
    if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) {
        return;
    }
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
    // Turn off stencil testing to allow circles to be drawn across boundaries,
    // so that large circles are not clipped to tiles
    const stencilMode = StencilMode.disabled;
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const isGlobeProjection = tr.projection.name === 'globe';
    const mercatorCenter = [
        mercatorXfromLng(tr.center.lng),
        mercatorYfromLat(tr.center.lat)
    ];
    const segmentsRenderStates = [];
    for (let i = 0; i < coords.length; i++) {
        const coord = coords[i];
        const tile = sourceCache.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket || bucket.projection.name !== tr.projection.name)
            continue;
        const programConfiguration = bucket.programConfigurations.get(layer.id);
        const definesValues = circleDefinesValues(layer);
        const affectedByFog = painter.isTileAffectedByFog(coord);
        if (isGlobeProjection) {
            definesValues.push('PROJECTION_GLOBE_VIEW');
        }
        const program = painter.getOrCreateProgram('circle', {
            config: programConfiguration,
            defines: definesValues,
            overrideFog: affectedByFog
        });
        const layoutVertexBuffer = bucket.layoutVertexBuffer;
        const globeExtVertexBuffer = bucket.globeExtVertexBuffer;
        const indexBuffer = bucket.indexBuffer;
        const invMatrix = tr.projection.createInversionMatrix(tr, coord.canonical);
        const uniformValues = circleUniformValues(painter, coord, tile, invMatrix, mercatorCenter, layer);
        const state = {
            programConfiguration,
            program,
            layoutVertexBuffer,
            globeExtVertexBuffer,
            indexBuffer,
            uniformValues,
            tile
        };
        if (sortFeaturesByKey) {
            const oldSegments = bucket.segments.get();
            for (const segment of oldSegments) {
                segmentsRenderStates.push({
                    segments: new SegmentVector([segment]),
                    sortKey: segment.sortKey,
                    state
                });
            }
        } else {
            segmentsRenderStates.push({
                segments: bucket.segments,
                sortKey: 0,
                state
            });
        }
    }
    if (sortFeaturesByKey) {
        segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey);
    }
    const terrainOptions = { useDepthForOcclusion: tr.depthOcclusionForSymbolsAndCircles };
    for (const segmentsState of segmentsRenderStates) {
        const {programConfiguration, program, layoutVertexBuffer, globeExtVertexBuffer, indexBuffer, uniformValues, tile} = segmentsState.state;
        const segments = segmentsState.segments;
        if (painter.terrain)
            painter.terrain.setupElevationDraw(tile, program, terrainOptions);
        painter.uploadCommonUniforms(context, program, tile.tileID.toUnwrapped());
        program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, layoutVertexBuffer, indexBuffer, segments, layer.paint, tr.zoom, programConfiguration, [globeExtVertexBuffer]);
    }
}

//      
function drawHeatmap(painter, sourceCache, layer, coords) {
    if (layer.paint.get('heatmap-opacity') === 0) {
        return;
    }
    if (painter.renderPass === 'offscreen') {
        const context = painter.context;
        const gl = context.gl;
        // Allow kernels to be drawn across boundaries, so that
        // large kernels are not clipped to tiles
        const stencilMode = StencilMode.disabled;
        // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula
        const colorMode = new ColorMode([
            gl.ONE,
            gl.ONE,
            gl.ONE,
            gl.ONE
        ], Color$1.transparent, [
            true,
            true,
            true,
            true
        ]);
        const resolutionScaling = painter.transform.projection.name === 'globe' ? 0.5 : 0.25;
        bindFramebuffer(context, painter, layer, resolutionScaling);
        context.clear({ color: Color$1.transparent });
        const tr = painter.transform;
        const isGlobeProjection = tr.projection.name === 'globe';
        const definesValues = isGlobeProjection ? ['PROJECTION_GLOBE_VIEW'] : [];
        const cullMode = isGlobeProjection ? CullFaceMode.frontCCW : CullFaceMode.disabled;
        const mercatorCenter = [
            mercatorXfromLng(tr.center.lng),
            mercatorYfromLat(tr.center.lat)
        ];
        for (let i = 0; i < coords.length; i++) {
            const coord = coords[i];
            // Skip tiles that have uncovered parents to avoid flickering; we don't need
            // to use complex tile masking here because the change between zoom levels is subtle,
            // so it's fine to simply render the parent until all its 4 children are loaded
            if (sourceCache.hasRenderableParent(coord))
                continue;
            const tile = sourceCache.getTile(coord);
            const bucket = tile.getBucket(layer);
            if (!bucket || bucket.projection.name !== tr.projection.name)
                continue;
            const affectedByFog = painter.isTileAffectedByFog(coord);
            const programConfiguration = bucket.programConfigurations.get(layer.id);
            const program = painter.getOrCreateProgram('heatmap', {
                config: programConfiguration,
                defines: definesValues,
                overrideFog: affectedByFog
            });
            const {zoom} = painter.transform;
            if (painter.terrain)
                painter.terrain.setupElevationDraw(tile, program);
            painter.uploadCommonUniforms(context, program, coord.toUnwrapped());
            const invMatrix = tr.projection.createInversionMatrix(tr, coord.canonical);
            program.draw(painter, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, cullMode, heatmapUniformValues(painter, coord, tile, invMatrix, mercatorCenter, zoom, layer.paint.get('heatmap-intensity')), layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, isGlobeProjection ? [bucket.globeExtVertexBuffer] : null);
        }
        context.viewport.set([
            0,
            0,
            painter.width,
            painter.height
        ]);
    } else if (painter.renderPass === 'translucent') {
        painter.context.setColorMode(painter.colorModeForRenderPass());
        renderTextureToMap(painter, layer);
    }
}
function bindFramebuffer(context, painter, layer, scaling) {
    const gl = context.gl;
    const width = painter.width * scaling;
    const height = painter.height * scaling;
    context.activeTexture.set(gl.TEXTURE1);
    context.viewport.set([
        0,
        0,
        width,
        height
    ]);
    let fbo = layer.heatmapFbo;
    if (!fbo || fbo && (fbo.width !== width || fbo.height !== height)) {
        if (fbo) {
            fbo.destroy();
        }
        const texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        fbo = layer.heatmapFbo = context.createFramebuffer(width, height, true, null);
        bindTextureToFramebuffer(context, painter, texture, fbo, width, height);
    } else {
        gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
        context.bindFramebuffer.set(fbo.framebuffer);
    }
}
function bindTextureToFramebuffer(context, painter, texture, fbo, width, height) {
    const gl = context.gl;
    // Use the higher precision half-float texture where available (producing much smoother looking heatmaps);
    // Otherwise, fall back to a low precision texture
    const type = context.extRenderToTextureHalfFloat ? gl.HALF_FLOAT : gl.UNSIGNED_BYTE;
    gl.texImage2D(gl.TEXTURE_2D, 0, context.extRenderToTextureHalfFloat ? gl.RGBA16F : gl.RGBA, width, height, 0, gl.RGBA, type, null);
    fbo.colorAttachment.set(texture);
}
function renderTextureToMap(painter, layer) {
    const context = painter.context;
    const gl = context.gl;
    // Here we bind two different textures from which we'll sample in drawing
    // heatmaps: the kernel texture, prepared in the offscreen pass, and a
    // color ramp texture.
    const fbo = layer.heatmapFbo;
    if (!fbo)
        return;
    context.activeTexture.set(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
    context.activeTexture.set(gl.TEXTURE1);
    let colorRampTexture = layer.colorRampTexture;
    if (!colorRampTexture) {
        colorRampTexture = layer.colorRampTexture = new Texture(context, layer.colorRamp, gl.RGBA);
    }
    colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    painter.getOrCreateProgram('heatmapTexture').draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom);
}

//      
function drawLine(painter, sourceCache, layer, coords) {
    if (painter.renderPass !== 'translucent')
        return;
    const opacity = layer.paint.get('line-opacity');
    const width = layer.paint.get('line-width');
    if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0)
        return;
    const emissiveStrength = layer.paint.get('line-emissive-strength');
    const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const pixelRatio = painter.terrain && painter.terrain.renderingToTexture ? 1 : exported$1.devicePixelRatio;
    const dasharrayProperty = layer.paint.get('line-dasharray');
    const dasharray = dasharrayProperty.constantOr(1);
    const capProperty = layer.layout.get('line-cap');
    const patternProperty = layer.paint.get('line-pattern');
    const image = patternProperty.constantOr(1);
    const hasPattern = layer.paint.get('line-pattern').constantOr(1);
    const hasOpacity = layer.paint.get('line-opacity').constantOr(1) !== 1;
    let useStencilMaskRenderPass = !hasPattern && hasOpacity;
    const gradient = layer.paint.get('line-gradient');
    const programId = image ? 'linePattern' : 'line';
    const context = painter.context;
    const gl = context.gl;
    const definesValues = lineDefinesValues(layer);
    if (painter.terrain && painter.terrain.clipOrMaskOverlapStencilType()) {
        useStencilMaskRenderPass = false;
    }
    for (const coord of coords) {
        const tile = sourceCache.getTile(coord);
        if (image && !tile.patternsLoaded())
            continue;
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        painter.prepareDrawTile();
        const programConfiguration = bucket.programConfigurations.get(layer.id);
        const affectedByFog = painter.isTileAffectedByFog(coord);
        const program = painter.getOrCreateProgram(programId, {
            config: programConfiguration,
            defines: definesValues,
            overrideFog: affectedByFog
        });
        const constantPattern = patternProperty.constantOr(null);
        if (constantPattern && tile.imageAtlas) {
            const posTo = tile.imageAtlas.patternPositions[constantPattern.toString()];
            if (posTo)
                programConfiguration.setConstantPatternPositions(posTo);
        }
        const constantDash = dasharrayProperty.constantOr(null);
        const constantCap = capProperty.constantOr(null);
        if (!image && constantDash && constantCap && tile.lineAtlas) {
            const posTo = tile.lineAtlas.getDash(constantDash, constantCap);
            if (posTo)
                programConfiguration.setConstantPatternPositions(posTo);
        }
        let [trimStart, trimEnd] = layer.paint.get('line-trim-offset');
        // When line cap is 'round' or 'square', the whole line progress will beyond 1.0 or less than 0.0.
        // If trim_offset begin is line begin (0.0), or trim_offset end is line end (1.0), adjust the trim
        // offset with fake offset shift so that the line_progress < 0.0 or line_progress > 1.0 part will be
        // correctly covered.
        if (constantCap === 'round' || constantCap === 'square') {
            // Fake the percentage so that it will cover the round/square cap that is beyond whole line
            const fakeOffsetShift = 1;
            // To make sure that the trim offset range is effecive
            if (trimStart !== trimEnd) {
                if (trimStart === 0) {
                    trimStart -= fakeOffsetShift;
                }
                if (trimEnd === 1) {
                    trimEnd += fakeOffsetShift;
                }
            }
        }
        const matrix = painter.terrain ? coord.projMatrix : null;
        const uniformValues = image ? linePatternUniformValues(painter, tile, layer, matrix, pixelRatio) : lineUniformValues(painter, tile, layer, matrix, bucket.lineClipsArray.length, pixelRatio, [
            trimStart,
            trimEnd
        ]);
        if (gradient) {
            const layerGradient = bucket.gradients[layer.id];
            let gradientTexture = layerGradient.texture;
            if (layer.gradientVersion !== layerGradient.version) {
                let textureResolution = 256;
                if (layer.stepInterpolant) {
                    const sourceMaxZoom = sourceCache.getSource().maxzoom;
                    const potentialOverzoom = coord.canonical.z === sourceMaxZoom ? Math.ceil(1 << painter.transform.maxZoom - coord.canonical.z) : 1;
                    const lineLength = bucket.maxLineLength / EXTENT;
                    // Logical pixel tile size is 512px, and 1024px right before current zoom + 1
                    const maxTilePixelSize = 1024;
                    // Maximum possible texture coverage heuristic, bound by hardware max texture size
                    const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom;
                    textureResolution = clamp(nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);
                }
                layerGradient.gradient = renderColorRamp({
                    expression: layer.gradientExpression(),
                    evaluationKey: 'lineProgress',
                    resolution: textureResolution,
                    image: layerGradient.gradient || undefined,
                    clips: bucket.lineClipsArray
                });
                if (layerGradient.texture) {
                    layerGradient.texture.update(layerGradient.gradient);
                } else {
                    layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA);
                }
                layerGradient.version = layer.gradientVersion;
                gradientTexture = layerGradient.texture;
            }
            context.activeTexture.set(gl.TEXTURE1);
            gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);
        }
        if (dasharray) {
            context.activeTexture.set(gl.TEXTURE0);
            tile.lineAtlasTexture.bind(gl.LINEAR, gl.REPEAT);
            programConfiguration.updatePaintBuffers();
        }
        if (image) {
            context.activeTexture.set(gl.TEXTURE0);
            tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            programConfiguration.updatePaintBuffers();
        }
        painter.uploadCommonUniforms(context, program, coord.toUnwrapped());
        const renderLine = stencilMode => {
            program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, [bucket.layoutVertexBuffer2]);
        };
        if (useStencilMaskRenderPass) {
            const stencilId = painter.stencilModeForClipping(coord).ref;
            // When terrain is on, ensure that the stencil buffer has 0 values.
            // As stencil may be disabled when it is not in overlapping stencil
            // mode. Refer to stencilModeForRTTOverlap logic.
            if (stencilId === 0 && painter.terrain) {
                context.clear({ stencil: 0 });
            }
            const stencilFunc = {
                func: gl.EQUAL,
                mask: 255
            };
            // Allow line geometry fragment to be drawn only once:
            // - Invert the stencil identifier left by stencil clipping, this
            // ensures that we are not conflicting with neighborhing tiles.
            // - Draw Anti-Aliased pixels with a threshold set to 0.8, this
            // may draw Anti-Aliased pixels more than once, but due to their
            // low opacity, these pixels are usually invisible and potential
            // overlapping pixel artifacts locally minimized.
            uniformValues['u_alpha_discard_threshold'] = 0.8;
            renderLine(new StencilMode(stencilFunc, stencilId, 255, gl.KEEP, gl.KEEP, gl.INVERT));
            uniformValues['u_alpha_discard_threshold'] = 0;
            renderLine(new StencilMode(stencilFunc, stencilId, 255, gl.KEEP, gl.KEEP, gl.KEEP));
        } else {
            renderLine(painter.stencilModeForClipping(coord));
        }
    }
    // When rendering to stencil, reset the mask to make sure that the tile
    // clipping reverts the stencil mask we may have drawn in the buffer.
    // The stamp could be reverted by an extra draw call of line geometry,
    // but tile clipping drawing is usually faster to draw than lines.
    if (useStencilMaskRenderPass) {
        painter.resetStencilClippingMasks();
        if (painter.terrain) {
            context.clear({ stencil: 0 });
        }
    }
}

//      
function drawFill(painter, sourceCache, layer, coords) {
    const color = layer.paint.get('fill-color');
    const opacity = layer.paint.get('fill-opacity');
    if (opacity.constantOr(1) === 0) {
        return;
    }
    const emissiveStrength = layer.paint.get('fill-emissive-strength');
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const pattern = layer.paint.get('fill-pattern');
    const pass = painter.opaquePassEnabledForLayer() && (!pattern.constantOr(1) && color.constantOr(Color$1.transparent).a === 1 && opacity.constantOr(0) === 1) ? 'opaque' : 'translucent';
    // Draw fill
    if (painter.renderPass === pass) {
        const depthMode = painter.depthModeForSublayer(1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);
        drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false);
    }
    // Draw stroke
    if (painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) {
        // If we defined a different color for the fill outline, we are
        // going to ignore the bits in 0x07 and just care about the global
        // clipping mask.
        // Otherwise, we only want to drawFill the antialiased parts that are
        // *outside* the current shape. This is important in case the fill
        // or stroke color is translucent. If we wouldn't clip to outside
        // the current shape, some pixels from the outline stroke overlapped
        // the (non-antialiased) fill.
        const depthMode = painter.depthModeForSublayer(layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly);
        drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, true);
    }
}
function drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) {
    const gl = painter.context.gl;
    const patternProperty = layer.paint.get('fill-pattern');
    const image = patternProperty && patternProperty.constantOr(1);
    let drawMode, programName, uniformValues, indexBuffer, segments;
    if (!isOutline) {
        programName = image ? 'fillPattern' : 'fill';
        drawMode = gl.TRIANGLES;
    } else {
        programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline';
        drawMode = gl.LINES;
    }
    for (const coord of coords) {
        const tile = sourceCache.getTile(coord);
        if (image && !tile.patternsLoaded())
            continue;
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        painter.prepareDrawTile();
        const programConfiguration = bucket.programConfigurations.get(layer.id);
        const affectedByFog = painter.isTileAffectedByFog(coord);
        const program = painter.getOrCreateProgram(programName, {
            config: programConfiguration,
            overrideFog: affectedByFog
        });
        if (image) {
            painter.context.activeTexture.set(gl.TEXTURE0);
            tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            programConfiguration.updatePaintBuffers();
        }
        const constantPattern = patternProperty.constantOr(null);
        if (constantPattern && tile.imageAtlas) {
            const atlas = tile.imageAtlas;
            const posTo = atlas.patternPositions[constantPattern.toString()];
            if (posTo)
                programConfiguration.setConstantPatternPositions(posTo);
        }
        const tileMatrix = painter.translatePosMatrix(coord.projMatrix, tile, layer.paint.get('fill-translate'), layer.paint.get('fill-translate-anchor'));
        const emissiveStrength = layer.paint.get('fill-emissive-strength');
        if (!isOutline) {
            indexBuffer = bucket.indexBuffer;
            segments = bucket.segments;
            uniformValues = image ? fillPatternUniformValues(tileMatrix, emissiveStrength, painter, tile) : fillUniformValues(tileMatrix, emissiveStrength);
        } else {
            indexBuffer = bucket.indexBuffer2;
            segments = bucket.segments2;
            const drawingBufferSize = painter.terrain && painter.terrain.renderingToTexture ? painter.terrain.drapeBufferSize : [
                gl.drawingBufferWidth,
                gl.drawingBufferHeight
            ];
            uniformValues = programName === 'fillOutlinePattern' && image ? fillOutlinePatternUniformValues(tileMatrix, emissiveStrength, painter, tile, drawingBufferSize) : fillOutlineUniformValues(tileMatrix, emissiveStrength, drawingBufferSize);
        }
        painter.uploadCommonUniforms(painter.context, program, coord.toUnwrapped());
        program.draw(painter, drawMode, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration, undefined);
    }
}

//      
function draw$1(painter, source, layer, coords) {
    const opacity = layer.paint.get('fill-extrusion-opacity');
    const context = painter.context;
    const gl = context.gl;
    const terrain = painter.terrain;
    const rtt = terrain && terrain.renderingToTexture;
    const cutoffFadeRange = layer.paint.get('fill-extrusion-cutoff-fade-range');
    if (opacity === 0) {
        return;
    }
    // Update replacement used with model layer conflation
    const conflateLayer = painter.conflationActive && painter.layerUsedInConflation(layer, source.getSource());
    if (conflateLayer) {
        updateReplacement(painter, source, layer, coords);
    }
    if (terrain || conflateLayer) {
        for (const coord of coords) {
            const tile = source.getTile(coord);
            const bucket = tile.getBucket(layer);
            if (!bucket) {
                continue;
            }
            updateBorders(painter.context, source, coord, bucket, layer, terrain, conflateLayer);
        }
    }
    if (painter.renderPass === 'shadow' && painter.shadowRenderer) {
        const shadowRenderer = painter.shadowRenderer;
        if (terrain) {
            const noShadowCutoff = 0.65;
            if (opacity < noShadowCutoff) {
                const expression = layer._transitionablePaint._values['fill-extrusion-opacity'].value.expression;
                if (expression instanceof ZoomDependentExpression) {
                    // avoid rendering shadows during fade in / fade out on terrain
                    return;
                }
            }
        }
        const depthMode = shadowRenderer.getShadowPassDepthMode();
        const colorMode = shadowRenderer.getShadowPassColorMode();
        drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode, conflateLayer);
    } else if (painter.renderPass === 'translucent') {
        const noPattern = !layer.paint.get('fill-extrusion-pattern').constantOr(1);
        if (!rtt) {
            const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
            if (cutoffFadeRange === 0 && opacity === 1 && noPattern) {
                drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.unblended, conflateLayer);
            } else {
                // Draw transparent buildings in two passes so that only the closest surface is drawn.
                // First draw all the extrusions into only the depth buffer. No colors are drawn.
                drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled, conflateLayer);
                // Then draw all the extrusions a second type, only coloring fragments if they have the
                // same depth value as the closest fragment in the previous pass. Use the stencil buffer
                // to prevent the second draw in cases where we have coincident polygons.
                drawExtrusionTiles(painter, source, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass(), conflateLayer);
                painter.resetStencilClippingMasks();
            }
        }
        // Note that when rendering ground effects in immediate mode the implementation below assumes that the alpha channel of the main framebuffer is unused and set to 1.
        // In draped mode this assumption no longer holds (since layer emissiveness is also encoded in the alpha channel) and therefore few more steps are required to implement the ground flood light and AO correctly.
        const lighting3DMode = painter.style.enable3dLights();
        const noTerrain = !terrain;
        const noGlobe = painter.transform.projection.name !== 'globe';
        const immediateMode = noTerrain && noGlobe;
        if (lighting3DMode && noPattern && (immediateMode || rtt)) {
            const opacity = layer.paint.get('fill-extrusion-opacity');
            const aoIntensity = layer.paint.get('fill-extrusion-ambient-occlusion-intensity');
            const aoRadius = layer.paint.get('fill-extrusion-ambient-occlusion-ground-radius');
            const floodLightIntensity = layer.paint.get('fill-extrusion-flood-light-intensity');
            const floodLightColor = layer.paint.get('fill-extrusion-flood-light-color').toArray01().slice(0, 3);
            const aoEnabled = aoIntensity > 0 && aoRadius > 0;
            const floodLightEnabled = floodLightIntensity > 0;
            const lerp = (a, b, t) => {
                return (1 - t) * a + t * b;
            };
            const passImmediate = aoPass => {
                const depthMode = painter.depthModeForSublayer(1, DepthMode.ReadOnly, gl.LEQUAL, true);
                const t = aoPass ? layer.paint.get('fill-extrusion-ambient-occlusion-ground-attenuation') : layer.paint.get('fill-extrusion-flood-light-ground-attenuation');
                const attenuation = lerp(0.1, 3, t);
                const showOverdraw = painter._showOverdrawInspector;
                if (!showOverdraw) {
                    // Mark the alpha channel with the DF values (that determine the intensity of the effects). No color is written.
                    /* $FlowFixMe[incompatible-call] */
                    const stencilSdfPass = new StencilMode({
                        func: gl.ALWAYS,
                        mask: 255
                    }, 255, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
                    /* $FlowFixMe[prop-missing] */
                    const colorSdfPass = new ColorMode([
                        gl.ONE,
                        gl.ONE,
                        gl.ONE,
                        gl.ONE
                    ], Color$1.transparent, [
                        false,
                        false,
                        false,
                        true
                    ], gl.MIN);
                    drawGroundEffect(painter, source, layer, coords, depthMode, stencilSdfPass, colorSdfPass, CullFaceMode.disabled, aoPass, 'sdf', opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, false);
                }
                {
                    // Draw the effects.
                    const stencilColorPass = showOverdraw ? StencilMode.disabled : new StencilMode({
                        func: gl.EQUAL,
                        mask: 255
                    }, 255, 255, gl.KEEP, gl.DECR, gl.DECR);
                    const colorColorPass = showOverdraw ? painter.colorModeForRenderPass() : new ColorMode([
                        gl.ONE_MINUS_DST_ALPHA,
                        gl.DST_ALPHA,
                        gl.ONE,
                        gl.ONE
                    ], Color$1.transparent, [
                        true,
                        true,
                        true,
                        true
                    ]);
                    drawGroundEffect(painter, source, layer, coords, depthMode, stencilColorPass, colorColorPass, CullFaceMode.disabled, aoPass, 'color', opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, false);
                }
            };
            if (rtt) {
                const passDraped = (aoPass, renderNeighbors, framebufferCopyTexture) => {
                    const depthMode = painter.depthModeForSublayer(1, DepthMode.ReadOnly, gl.LEQUAL, false);
                    const t = aoPass ? layer.paint.get('fill-extrusion-ambient-occlusion-ground-attenuation') : layer.paint.get('fill-extrusion-flood-light-ground-attenuation');
                    const attenuation = lerp(0.1, 3, t);
                    {
                        // Clear framebuffer's alpha channel to 1 since we're using gl.MIN blend operation in the subsequent steps.
                        const colorMode = new ColorMode([
                            gl.ONE,
                            gl.ONE,
                            gl.ONE,
                            gl.ONE
                        ], Color$1.transparent, [
                            false,
                            false,
                            false,
                            true
                        ]);
                        drawGroundEffect(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, aoPass, 'clear', opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors);
                    }
                    {
                        // Mark the alpha channel with the DF values (that determine the intensity of the effects). No color is written.
                        /* $FlowFixMe[incompatible-call] */
                        const stencilSdfPass = new StencilMode({
                            func: gl.ALWAYS,
                            mask: 255
                        }, 255, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
                        /* $FlowFixMe[prop-missing] */
                        const colorSdfPass = new ColorMode([
                            gl.ONE,
                            gl.ONE,
                            gl.ONE,
                            gl.ONE
                        ], Color$1.transparent, [
                            false,
                            false,
                            false,
                            true
                        ], gl.MIN);
                        drawGroundEffect(painter, source, layer, coords, depthMode, stencilSdfPass, colorSdfPass, CullFaceMode.disabled, aoPass, 'sdf', opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors);
                    }
                    {
                        // Draw the effects. The inverse of the alpha channel is used so that in the next pass we can correctly incorporate it with the emissive strength values that are also encoded in the alpha channel (now present in the texture).
                        const srcColorFactor = aoPass ? gl.ZERO : gl.ONE_MINUS_DST_ALPHA;
                        // For AO, it's enough to multiply the color with the intensity.
                        const stencilColorPass = new StencilMode({
                            func: gl.EQUAL,
                            mask: 255
                        }, 255, 255, gl.KEEP, gl.DECR, gl.DECR);
                        const colorColorPass = new ColorMode([
                            srcColorFactor,
                            gl.DST_ALPHA,
                            gl.ONE_MINUS_DST_ALPHA,
                            gl.ZERO
                        ], Color$1.transparent, [
                            true,
                            true,
                            true,
                            true
                        ]);
                        drawGroundEffect(painter, source, layer, coords, depthMode, stencilColorPass, colorColorPass, CullFaceMode.disabled, aoPass, 'color', opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors);
                    }
                    {
                        // Re-write to the alpha channel of the framebuffer based on existing values (of ground effects) and emissive values (saved to texture in earlier step).
                        // Note that in draped mode an alpha value of 1 indicates fully emissiveness for a fragment and a value of 0 means fully lit (3d lighting).
                        // We don't really need to encode the alpha values for AO as the layers have already been multiplied by its intensity. The gl.FUNC_ADD (as blending equation) and gl.ZERO (as dest alpha factor) would ensure this.
                        const dstAlphaFactor = aoPass ? gl.ZERO : gl.ONE;
                        /* $FlowFixMe[prop-missing] */
                        const blendEquation = aoPass ? gl.FUNC_ADD : gl.MAX;
                        const colorMode = new ColorMode([
                            gl.ONE,
                            gl.ONE,
                            gl.ONE,
                            dstAlphaFactor
                        ], Color$1.transparent, [
                            false,
                            false,
                            false,
                            true
                        ], blendEquation);
                        drawGroundEffect(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, aoPass, 'clear', opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors, framebufferCopyTexture);
                    }
                };
                if (aoEnabled || floodLightEnabled) {
                    painter.prepareDrawTile();
                    let framebufferCopyTexture;
                    // Save the alpha channel of the framebuffer used by emissive layers.
                    if (terrain) {
                        // Condition is anywyas guaranteed by rtt variable. Used only to suppress flow errors.
                        const width = terrain.drapeBufferSize[0];
                        const height = terrain.drapeBufferSize[1];
                        framebufferCopyTexture = terrain.framebufferCopyTexture;
                        if (!framebufferCopyTexture || framebufferCopyTexture && (framebufferCopyTexture.size[0] !== width || framebufferCopyTexture.size[1] !== height)) {
                            if (framebufferCopyTexture)
                                framebufferCopyTexture.destroy();
                            framebufferCopyTexture = terrain.framebufferCopyTexture = new Texture(context, new RGBAImage({
                                width,
                                height
                            }), gl.RGBA);
                        }
                        framebufferCopyTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
                        gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, width, height, 0);
                    }
                    // Render ground AO.
                    if (aoEnabled) {
                        passDraped(true, false, framebufferCopyTexture);
                    }
                    // Render ground flood light.
                    if (floodLightEnabled) {
                        passDraped(false, true, framebufferCopyTexture);
                    }
                }
            } else {
                // immediate mode
                // Render ground AO.
                if (aoEnabled) {
                    passImmediate(true);
                }
                // Render ground flood light.
                if (floodLightEnabled) {
                    passImmediate(false);
                }
            }
        }
    }
}
function drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode, replacementActive) {
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const patternProperty = layer.paint.get('fill-extrusion-pattern');
    const image = patternProperty.constantOr(1);
    const opacity = layer.paint.get('fill-extrusion-opacity');
    const lighting3DMode = painter.style.enable3dLights();
    const aoRadius = lighting3DMode && !image ? layer.paint.get('fill-extrusion-ambient-occlusion-wall-radius') : layer.paint.get('fill-extrusion-ambient-occlusion-radius');
    const ao = [
        layer.paint.get('fill-extrusion-ambient-occlusion-intensity'),
        aoRadius
    ];
    const edgeRadius = layer.layout.get('fill-extrusion-edge-radius');
    const zeroRoofRadius = edgeRadius > 0 && !layer.paint.get('fill-extrusion-rounded-roof');
    const roofEdgeRadius = zeroRoofRadius ? 0 : edgeRadius;
    const heightLift = tr.projection.name === 'globe' ? fillExtrusionHeightLift() : 0;
    const isGlobeProjection = tr.projection.name === 'globe';
    const globeToMercator = isGlobeProjection ? globeToMercatorTransition(tr.zoom) : 0;
    const mercatorCenter = [
        mercatorXfromLng(tr.center.lng),
        mercatorYfromLat(tr.center.lat)
    ];
    const floodLightColor = layer.paint.get('fill-extrusion-flood-light-color').toArray01().slice(0, 3);
    const floodLightIntensity = layer.paint.get('fill-extrusion-flood-light-intensity');
    const verticalScale = layer.paint.get('fill-extrusion-vertical-scale');
    const cutoffParams = getCutoffParams(painter, layer.paint.get('fill-extrusion-cutoff-fade-range'));
    const baseDefines = [];
    if (isGlobeProjection) {
        baseDefines.push('PROJECTION_GLOBE_VIEW');
    }
    if (ao[0] > 0) {
        // intensity
        baseDefines.push('FAUX_AO');
    }
    if (zeroRoofRadius) {
        baseDefines.push('ZERO_ROOF_RADIUS');
    }
    if (replacementActive) {
        baseDefines.push('HAS_CENTROID');
    }
    if (floodLightIntensity > 0) {
        baseDefines.push('FLOOD_LIGHT');
    }
    if (cutoffParams.shouldRenderCutoff) {
        baseDefines.push('RENDER_CUTOFF');
    }
    let singleCascadeDefines;
    const isShadowPass = painter.renderPass === 'shadow';
    const shadowRenderer = painter.shadowRenderer;
    const drawDepth = isShadowPass && !!shadowRenderer;
    if (painter.shadowRenderer)
        painter.shadowRenderer.useNormalOffset = true;
    let groundShadowFactor = [
        0,
        0,
        0
    ];
    if (shadowRenderer) {
        const directionalLight = painter.style.directionalLight;
        const ambientLight = painter.style.ambientLight;
        if (directionalLight && ambientLight) {
            groundShadowFactor = calculateGroundShadowFactor(directionalLight, ambientLight);
        }
        singleCascadeDefines = baseDefines.concat(['SHADOWS_SINGLE_CASCADE']);
    }
    const programName = drawDepth ? 'fillExtrusionDepth' : image ? 'fillExtrusionPattern' : 'fillExtrusion';
    for (const coord of coords) {
        const tile = source.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket || bucket.projection.name !== tr.projection.name)
            continue;
        let singleCascade = false;
        if (shadowRenderer) {
            singleCascade = shadowRenderer.getMaxCascadeForTile(coord.toUnwrapped()) === 0;
        }
        const affectedByFog = painter.isTileAffectedByFog(coord);
        const programConfiguration = bucket.programConfigurations.get(layer.id);
        const program = painter.getOrCreateProgram(programName, {
            config: programConfiguration,
            defines: singleCascade ? singleCascadeDefines : baseDefines,
            overrideFog: affectedByFog
        });
        if (painter.terrain) {
            const terrain = painter.terrain;
            if (painter.style.terrainSetForDrapingOnly()) {
                terrain.setupElevationDraw(tile, program, { useMeterToDem: true });
            } else {
                terrain.setupElevationDraw(tile, program, { useMeterToDem: true });
            }
        }
        if (!bucket.centroidVertexBuffer) {
            const attrIndex = program.attributes['a_centroid_pos'];
            if (attrIndex !== undefined)
                gl.vertexAttrib2f(attrIndex, 0, 0);
        }
        if (!isShadowPass && shadowRenderer) {
            shadowRenderer.setupShadows(tile.tileID.toUnwrapped(), program, 'vector-tile', tile.tileID.overscaledZ);
        }
        if (image) {
            painter.context.activeTexture.set(gl.TEXTURE0);
            tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            programConfiguration.updatePaintBuffers();
        }
        const constantPattern = patternProperty.constantOr(null);
        if (constantPattern && tile.imageAtlas) {
            const atlas = tile.imageAtlas;
            const posTo = atlas.patternPositions[constantPattern.toString()];
            if (posTo)
                programConfiguration.setConstantPatternPositions(posTo);
        }
        const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient');
        let uniformValues;
        if (isShadowPass && shadowRenderer) {
            if (frustumCullShadowCaster(tile.tileID, bucket, painter)) {
                continue;
            }
            const tileMatrix = shadowRenderer.calculateShadowPassMatrixFromTile(tile.tileID.toUnwrapped());
            uniformValues = fillExtrusionDepthUniformValues(tileMatrix, roofEdgeRadius, verticalScale);
        } else {
            const matrix = painter.translatePosMatrix(coord.projMatrix, tile, layer.paint.get('fill-extrusion-translate'), layer.paint.get('fill-extrusion-translate-anchor'));
            const invMatrix = tr.projection.createInversionMatrix(tr, coord.canonical);
            if (image) {
                uniformValues = fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, ao, roofEdgeRadius, coord, tile, heightLift, globeToMercator, mercatorCenter, invMatrix, floodLightColor, verticalScale);
            } else {
                uniformValues = fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, ao, roofEdgeRadius, coord, heightLift, globeToMercator, mercatorCenter, invMatrix, floodLightColor, verticalScale, floodLightIntensity, groundShadowFactor);
            }
        }
        painter.uploadCommonUniforms(context, program, coord.toUnwrapped(), null, cutoffParams);
        const dynamicBuffers = [];
        if (painter.terrain || replacementActive)
            dynamicBuffers.push(bucket.centroidVertexBuffer);
        if (isGlobeProjection)
            dynamicBuffers.push(bucket.layoutVertexExtBuffer);
        program.draw(painter, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, dynamicBuffers);
    }
    if (painter.shadowRenderer)
        painter.shadowRenderer.useNormalOffset = false;
}
function updateReplacement(painter, source, layer, coords) {
    for (const coord of coords) {
        const tile = source.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket) {
            continue;
        }
        bucket.updateReplacement(coord, painter.replacementSource);
        bucket.uploadCentroid(painter.context);
    }
}
function drawGroundEffect(painter, source, layer, coords, depthMode, stencilMode, colorMode, cullFaceMode, aoPass, subpass, opacity, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, replacementActive, renderNeighbors, framebufferCopyTexture) {
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const zoom = painter.transform.zoom;
    const defines = [];
    const cutoffParams = getCutoffParams(painter, layer.paint.get('fill-extrusion-cutoff-fade-range'));
    if (subpass === 'clear') {
        defines.push('CLEAR_SUBPASS');
        if (framebufferCopyTexture) {
            defines.push('CLEAR_FROM_TEXTURE');
            context.activeTexture.set(gl.TEXTURE0);
            framebufferCopyTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        }
    } else if (subpass === 'sdf') {
        defines.push('SDF_SUBPASS');
    }
    if (replacementActive) {
        defines.push('HAS_CENTROID');
    }
    if (cutoffParams.shouldRenderCutoff) {
        defines.push('RENDER_CUTOFF');
    }
    const edgeRadius = layer.layout.get('fill-extrusion-edge-radius');
    const renderGroundEffectTile = (coord, groundEffect, segments, matrix, meterToTile) => {
        const programConfiguration = groundEffect.programConfigurations.get(layer.id);
        const affectedByFog = painter.isTileAffectedByFog(coord);
        const program = painter.getOrCreateProgram('fillExtrusionGroundEffect', {
            config: programConfiguration,
            defines,
            overrideFog: affectedByFog
        });
        const ao = [
            aoIntensity,
            aoRadius * meterToTile
        ];
        const edgeRadiusTile = zoom >= 17 ? 0 : edgeRadius * meterToTile;
        const fbSize = framebufferCopyTexture ? framebufferCopyTexture.size[0] : 0;
        const uniformValues = fillExtrusionGroundEffectUniformValues(painter, matrix, opacity, aoPass, meterToTile, ao, floodLightIntensity, floodLightColor, attenuation, edgeRadiusTile, fbSize);
        const dynamicBuffers = [];
        if (replacementActive)
            dynamicBuffers.push(groundEffect.hiddenByLandmarkVertexBuffer);
        painter.uploadCommonUniforms(context, program, coord.toUnwrapped(), null, cutoffParams);
        program.draw(painter, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, layer.id, groundEffect.vertexBuffer, groundEffect.indexBuffer, segments, layer.paint, zoom, programConfiguration, dynamicBuffers);
    };
    for (const coord of coords) {
        const tile = source.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket || bucket.projection.name !== tr.projection.name || !bucket.groundEffect || bucket.groundEffect && !bucket.groundEffect.hasData())
            continue;
        const groundEffect = bucket.groundEffect;
        const meterToTile = 1 / bucket.tileToMeter;
        {
            const matrix = painter.translatePosMatrix(coord.projMatrix, tile, layer.paint.get('fill-extrusion-translate'), layer.paint.get('fill-extrusion-translate-anchor'));
            const segments = groundEffect.getDefaultSegment();
            renderGroundEffectTile(coord, groundEffect, segments, matrix, meterToTile);
        }
        if (renderNeighbors) {
            for (let i = 0; i < 4; i++) {
                const nCoord = neighborCoord[i](coord);
                const nTile = source.getTile(nCoord);
                if (!nTile)
                    continue;
                const nBucket = nTile.getBucket(layer);
                if (!nBucket || nBucket.projection.name !== tr.projection.name || !nBucket.groundEffect || nBucket.groundEffect && !nBucket.groundEffect.hasData())
                    continue;
                const nGroundEffect = nBucket.groundEffect;
                let translation, regionId;
                if (i === 0) {
                    // left
                    translation = [
                        -EXTENT,
                        0,
                        0
                    ];
                    regionId = 1;
                } else if (i === 1) {
                    // right
                    translation = [
                        EXTENT,
                        0,
                        0
                    ];
                    regionId = 0;
                } else if (i === 2) {
                    // top
                    translation = [
                        0,
                        -EXTENT,
                        0
                    ];
                    regionId = 3;
                } else {
                    // bottom
                    translation = [
                        0,
                        EXTENT,
                        0
                    ];
                    regionId = 2;
                }
                const segments = nGroundEffect.regionSegments[regionId];
                // No geometry from the neighbour tile intersects the current tile.
                if (!segments)
                    continue;
                const proj = new Float32Array(16);
                mat4_1.translate(proj, coord.projMatrix, translation);
                const matrix = painter.translatePosMatrix(proj, tile, layer.paint.get('fill-extrusion-translate'), layer.paint.get('fill-extrusion-translate-anchor'));
                renderGroundEffectTile(coord, nGroundEffect, segments, matrix, meterToTile);
            }
        }
    }
}
// Flat roofs array is prepared in the bucket, except for buildings that are on tile borders.
// For them, join pieces, calculate joined size here, and then upload data.
function updateBorders(context, source, coord, bucket, layer, terrain, reconcileReplacementState) {
    if (bucket.centroidVertexArray.length === 0) {
        bucket.createCentroidsBuffer();
    }
    const demTile = terrain ? terrain.findDEMTileFor(coord) : null;
    if ((!demTile || !demTile.dem) && !reconcileReplacementState) {
        return;    // defer update until an elevation tile is available.
    }
    const reconcileReplacement = (centroid1, centroid2) => {
        const hiddenFlag = (centroid1.flags | centroid2.flags) & HIDDEN_BY_REPLACEMENT;
        if (hiddenFlag) {
            centroid1.flags |= HIDDEN_BY_REPLACEMENT;
            centroid2.flags |= HIDDEN_BY_REPLACEMENT;
        } else {
            centroid1.flags &= ~HIDDEN_BY_REPLACEMENT;
            centroid2.flags &= ~HIDDEN_BY_REPLACEMENT;
        }
    };
    const encodeHeightAsCentroid = height => {
        return new Point$2(Math.ceil((height + ELEVATION_OFFSET) * ELEVATION_SCALE), 0);
    };
    const getLoadedBucket = nid => {
        const minzoom = source.getSource().minzoom;
        const getBucket = key => {
            const n = source.getTileByID(key);
            if (n && n.hasData()) {
                return n.getBucket(layer);
            }
        };
        // Look one tile zoom above and under. We do this to avoid flickering and
        // use the content in Z-1 and Z+1 buckets until Z bucket is loaded or handle
        // behavior on borders between different zooms.
        const zoomLevels = [
            0,
            -1,
            1
        ];
        for (const i of zoomLevels) {
            const z = nid.overscaledZ + i;
            if (z < minzoom)
                continue;
            const key = nid.calculateScaledKey(nid.overscaledZ + i);
            const b = getBucket(key);
            if (b) {
                return b;
            }
        }
    };
    const projectedToBorder = [
        0,
        0,
        0
    ];
    // [min, max, maxOffsetFromBorder]
    const xjoin = (a, b) => {
        projectedToBorder[0] = Math.min(a.min.y, b.min.y);
        projectedToBorder[1] = Math.max(a.max.y, b.max.y);
        projectedToBorder[2] = EXTENT - b.min.x > a.max.x ? b.min.x - EXTENT : a.max.x;
        return projectedToBorder;
    };
    const yjoin = (a, b) => {
        projectedToBorder[0] = Math.min(a.min.x, b.min.x);
        projectedToBorder[1] = Math.max(a.max.x, b.max.x);
        projectedToBorder[2] = EXTENT - b.min.y > a.max.y ? b.min.y - EXTENT : a.max.y;
        return projectedToBorder;
    };
    const projectCombinedSpanToBorder = [
        (a, b) => xjoin(a, b),
        (a, b) => xjoin(b, a),
        (a, b) => yjoin(a, b),
        (a, b) => yjoin(b, a)
    ];
    const error = 3;
    // Allow intrusion of a building to the building with adjacent wall.
    const flatBase = (min, max, edge, neighborDEMTile, neighborTileID, verticalEdge, maxOffsetFromBorder) => {
        if (!terrain) {
            return 0;
        }
        const points = [
            [
                verticalEdge ? edge : min,
                verticalEdge ? min : edge,
                0
            ],
            [
                verticalEdge ? edge : max,
                verticalEdge ? max : edge,
                0
            ]
        ];
        const coord3 = maxOffsetFromBorder < 0 ? EXTENT + maxOffsetFromBorder : maxOffsetFromBorder;
        const thirdPoint = [
            verticalEdge ? coord3 : (min + max) / 2,
            verticalEdge ? (min + max) / 2 : coord3,
            0
        ];
        if (edge === 0 && maxOffsetFromBorder < 0 || edge !== 0 && maxOffsetFromBorder > 0) {
            // Third point is inside neighbor tile, not in the |coord| tile.
            terrain.getForTilePoints(neighborTileID, [thirdPoint], true, neighborDEMTile);
        } else {
            points.push(thirdPoint);
        }
        terrain.getForTilePoints(coord, points, true, demTile);
        return Math.max(points[0][2], points[1][2], thirdPoint[2]) / terrain.exaggeration();
    };
    // Process all four borders: get neighboring tile
    for (let i = 0; i < 4; i++) {
        // sorted by border intersection area minimums, ascending.
        const a = bucket.borderFeatureIndices[i];
        if (a.length === 0) {
            continue;
        }
        // Look up the neighbor tile's bucket
        const nid = neighborCoord[i](coord);
        const nBucket = getLoadedBucket(nid);
        if (!nBucket || !(nBucket instanceof FillExtrusionBucket)) {
            continue;
        }
        if (bucket.borderDoneWithNeighborZ[i] === nBucket.canonical.z) {
            continue;
        }
        if (nBucket.centroidVertexArray.length === 0) {
            nBucket.createCentroidsBuffer();
        }
        // Look up the neighbor DEM tile
        const neighborDEMTile = terrain ? terrain.findDEMTileFor(nid) : null;
        if ((!neighborDEMTile || !neighborDEMTile.dem) && !reconcileReplacementState) {
            continue;
        }
        const j = (i < 2 ? 1 : 5) - i;
        const updateNeighbor = nBucket.borderDoneWithNeighborZ[j] !== bucket.canonical.z;
        const b = nBucket.borderFeatureIndices[j];
        let ib = 0;
        // If neighbors are of different canonical z, we cannot join parts but show
        // all without flat roofs.
        if (bucket.canonical.z !== nBucket.canonical.z) {
            for (const index of a) {
                bucket.showCentroid(bucket.featuresOnBorder[index]);
            }
            if (updateNeighbor) {
                for (const index of b) {
                    nBucket.showCentroid(nBucket.featuresOnBorder[index]);
                }
            }
            bucket.borderDoneWithNeighborZ[i] = nBucket.canonical.z;
            nBucket.borderDoneWithNeighborZ[j] = bucket.canonical.z;
        }
        for (const ia of a) {
            const partA = bucket.featuresOnBorder[ia];
            const centroidA = bucket.centroidData[partA.centroidDataIndex];
            const partABorderRange = partA.borders[i];
            // Find all nBucket parts that share the border overlap
            let partB;
            while (ib < b.length) {
                // Pass all that are before the overlap
                partB = nBucket.featuresOnBorder[b[ib]];
                const partBBorderRange = partB.borders[j];
                if (partBBorderRange[1] > partABorderRange[0] + error || partBBorderRange[0] > partABorderRange[0] - error) {
                    break;
                }
                nBucket.showCentroid(partB);
                ib++;
            }
            if (partB && ib < b.length) {
                const saveIb = ib;
                let count = 0;
                while (true) {
                    const partBBorderRange = partB.borders[j];
                    if (partBBorderRange[0] > partABorderRange[1] - error) {
                        break;
                    }
                    count++;
                    if (++ib === b.length) {
                        break;
                    }
                    partB = nBucket.featuresOnBorder[b[ib]];
                }
                partB = nBucket.featuresOnBorder[b[saveIb]];
                if (count > 1) {
                    const partBBorderRange = partB.borders[j];
                    if (Math.abs(partABorderRange[0] - partBBorderRange[0]) < error && Math.abs(partABorderRange[1] - partBBorderRange[1]) < error) {
                        count = 1;
                        ib = saveIb + 1;
                    }
                } else if (count === 0) {
                    // No B for A, show it, no flat roofs.
                    bucket.showCentroid(partA);
                    continue;
                }
                const centroidB = nBucket.centroidData[partB.centroidDataIndex];
                if (reconcileReplacementState && count === 1) {
                    reconcileReplacement(centroidA, centroidB);
                }
                let centroidXY = new Point$2(0, 0);
                if (count > 1) {
                    ib = saveIb;    // rewind unprocessed ib so that it is processed again for the next ia.
                } else if (neighborDEMTile && neighborDEMTile.dem && !(partA.intersectsCount() > 1 || partB.intersectsCount() > 1)) {
                    // If any of a or b crosses more than one tile edge, don't support flat roof.
                    // Now we have 1-1 matching of parts in both tiles that share the edge. Calculate flat base
                    // elevation as average of three points: 2 are edge points (combined span projected to border) and
                    // one is point of span that has maximum offset to border.
                    const span = projectCombinedSpanToBorder[i](centroidA, centroidB);
                    const edge = i % 2 ? EXTENT - 1 : 0;
                    const height = flatBase(span[0], Math.min(EXTENT - 1, span[1]), edge, neighborDEMTile, nid, i < 2, span[2]);
                    centroidXY = encodeHeightAsCentroid(height);
                }
                centroidA.centroidXY = centroidB.centroidXY = centroidXY;
                bucket.writeCentroidToBuffer(centroidA);
                nBucket.writeCentroidToBuffer(centroidB);
            } else {
                bucket.showCentroid(partA);
            }
        }
        bucket.borderDoneWithNeighborZ[i] = nBucket.canonical.z;
        nBucket.borderDoneWithNeighborZ[j] = bucket.canonical.z;
    }
    if (bucket.needsCentroidUpdate || !bucket.centroidVertexBuffer && bucket.centroidVertexArray.length !== 0) {
        bucket.uploadCentroid(context);
    }
}
const XAxis = [
    1,
    0,
    0
];
const YAxis = [
    0,
    1,
    0
];
const ZAxis = [
    0,
    0,
    1
];
function frustumCullShadowCaster(id, bucket, painter) {
    const transform = painter.transform;
    const shadowRenderer = painter.shadowRenderer;
    if (!shadowRenderer) {
        return true;
    }
    const unwrappedId = id.toUnwrapped();
    const ws = transform.tileSize * shadowRenderer._cascades[painter.currentShadowCascade].scale;
    let height = bucket.maxHeight;
    if (transform.elevation) {
        const minmax = transform.elevation.getMinMaxForTile(id);
        if (minmax) {
            height += minmax.max;
        }
    }
    const shadowDir = [...shadowRenderer.shadowDirection];
    shadowDir[2] = -shadowDir[2];
    const tileShadowVolume = shadowRenderer.computeSimplifiedTileShadowVolume(unwrappedId, height, ws, shadowDir);
    if (!tileShadowVolume) {
        return false;
    }
    // Projected shadow volume has 3-6 unique edge direction vectors.
    // These are used for computing remaining separating axes for the intersection test
    const edges = [
        XAxis,
        YAxis,
        ZAxis,
        shadowDir,
        [
            shadowDir[0],
            0,
            shadowDir[2]
        ],
        [
            0,
            shadowDir[1],
            shadowDir[2]
        ]
    ];
    const isGlobe = transform.projection.name === 'globe';
    const zoom = transform.scaleZoom(ws);
    const cameraFrustum = Frustum.fromInvProjectionMatrix(transform.invProjMatrix, transform.worldSize, zoom, !isGlobe);
    const cascadeFrustum = shadowRenderer.getCurrentCascadeFrustum();
    if (cameraFrustum.intersectsPrecise(tileShadowVolume.vertices, tileShadowVolume.planes, edges) === 0) {
        return true;
    }
    if (cascadeFrustum.intersectsPrecise(tileShadowVolume.vertices, tileShadowVolume.planes, edges) === 0) {
        return true;
    }
    return false;
}

//      
const RASTER_COLOR_TEXTURE_UNIT = 2;
function drawRaster(painter, sourceCache, layer, tileIDs, variableOffsets, isInitialLoad) {
    if (painter.renderPass !== 'translucent')
        return;
    if (layer.paint.get('raster-opacity') === 0)
        return;
    const context = painter.context;
    const gl = context.gl;
    const source = sourceCache.getSource();
    const rasterColor = configureRasterColor(layer, context, gl);
    const defines = rasterColor.defines;
    let drawAsGlobePole = false;
    if (source instanceof ImageSource && !tileIDs.length) {
        if (painter.transform.projection.name !== 'globe') {
            return;
        }
        if (source.onNorthPole) {
            drawAsGlobePole = true;
            defines.push('PROJECTION_GLOBE_VIEW');
        } else if (source.onSouthPole) {
            drawAsGlobePole = true;
            defines.push('PROJECTION_GLOBE_VIEW');
        } else {
            // Image source without tile ID can only be rendered on the poles
            return;
        }
    }
    const colorMode = painter.colorModeForDrapableLayerRenderPass();
    // When rendering to texture, coordinates are already sorted: primary by
    // proxy id and secondary sort is by Z.
    const renderingToTexture = painter.terrain && painter.terrain.renderingToTexture;
    const align = !painter.options.moving;
    const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR;
    if (drawAsGlobePole) {
        const source = sourceCache.getSource();
        if (!(source instanceof ImageSource))
            return;
        const texture = source.texture;
        if (!texture)
            return;
        const sharedBuffers = painter.globeSharedBuffers;
        if (!sharedBuffers)
            return;
        const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
        const projMatrix = Float32Array.from(painter.transform.projMatrix);
        let globeMatrix = globePoleMatrixForTile(0, 0, painter.transform);
        const normalizeMatrix = Float32Array.from(globeNormalizeECEF(globeTileBounds(new CanonicalTileID(0, 0, 0))));
        const fade = {
            opacity: 1,
            mix: 0
        };
        if (painter.terrain)
            painter.terrain.prepareDrawTile();
        context.activeTexture.set(gl.TEXTURE0);
        texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
        context.activeTexture.set(gl.TEXTURE1);
        texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
        // Enable trilinear filtering on tiles only beyond 20 degrees pitch,
        // to prevent it from compromising image crispness on flat or low tilted maps.
        if (texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) {
            gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
        }
        const [northPoleBuffer, southPoleBuffer, indexBuffer, segment] = sharedBuffers.getPoleBuffers(0, true);
        let vertexBuffer;
        if (source.onNorthPole) {
            vertexBuffer = northPoleBuffer;
            painter.renderDefaultNorthPole = false;
        } else {
            globeMatrix = mat4_1.scale(mat4_1.create(), globeMatrix, [
                1,
                -1,
                1
            ]);
            vertexBuffer = southPoleBuffer;
            painter.renderDefaultSouthPole = false;
        }
        const perspectiveTransform = source.perspectiveTransform;
        const uniformValues = rasterUniformValues(projMatrix, normalizeMatrix, globeMatrix, [
            0,
            0
        ], 1, fade, layer, perspectiveTransform || [
            0,
            0
        ], RASTER_COLOR_TEXTURE_UNIT, rasterColor.mix || [
            0,
            0,
            0,
            0
        ], rasterColor.range || [
            0,
            0
        ]);
        const program = painter.getOrCreateProgram('raster', { defines: rasterColor.defines });
        painter.uploadCommonUniforms(context, program, null);
        program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, uniformValues, layer.id, vertexBuffer, indexBuffer, segment);
        return;
    }
    if (!tileIDs.length) {
        return;
    }
    const [stencilModes, coords] = source instanceof ImageSource || renderingToTexture ? [
        {},
        tileIDs
    ] : painter.stencilConfigForOverlap(tileIDs);
    const minTileZ = coords[coords.length - 1].overscaledZ;
    for (const coord of coords) {
        // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers
        // Use gl.LESS to prevent double drawing in areas where tiles overlap.
        const depthMode = renderingToTexture ? DepthMode.disabled : painter.depthModeForSublayer(coord.overscaledZ - minTileZ, layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);
        const unwrappedTileID = coord.toUnwrapped();
        const tile = sourceCache.getTile(coord);
        if (renderingToTexture && !(tile && tile.hasData()))
            continue;
        if (!tile.texture)
            continue;
        const projMatrix = renderingToTexture ? coord.projMatrix : painter.transform.calculateProjMatrix(unwrappedTileID, align);
        const stencilMode = painter.terrain && renderingToTexture ? painter.terrain.stencilModeForRTTOverlap(coord) : stencilModes[coord.overscaledZ];
        const rasterFadeDuration = isInitialLoad ? 0 : layer.paint.get('raster-fade-duration');
        tile.registerFadeDuration(rasterFadeDuration);
        const parentTile = sourceCache.findLoadedParent(coord, 0);
        const fade = rasterFade(tile, parentTile, sourceCache, painter.transform, rasterFadeDuration);
        if (painter.terrain)
            painter.terrain.prepareDrawTile();
        let parentScaleBy, parentTL;
        context.activeTexture.set(gl.TEXTURE0);
        tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
        context.activeTexture.set(gl.TEXTURE1);
        if (parentTile) {
            parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
            parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);
            parentTL = [
                tile.tileID.canonical.x * parentScaleBy % 1,
                tile.tileID.canonical.y * parentScaleBy % 1
            ];
        } else {
            tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
        }
        // Enable trilinear filtering on tiles only beyond 20 degrees pitch,
        // to prevent it from compromising image crispness on flat or low tilted maps.
        if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) {
            gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
        }
        const perspectiveTransform = source instanceof ImageSource ? source.perspectiveTransform : [
            0,
            0
        ];
        const emptyMatrix = new Float32Array(16);
        const uniformValues = rasterUniformValues(projMatrix, emptyMatrix, emptyMatrix, parentTL || [
            0,
            0
        ], parentScaleBy || 1, fade, layer, perspectiveTransform, RASTER_COLOR_TEXTURE_UNIT, rasterColor.mix || [
            0,
            0,
            0,
            0
        ], rasterColor.range || [
            0,
            0
        ]);
        const affectedByFog = painter.isTileAffectedByFog(coord);
        const program = painter.getOrCreateProgram('raster', {
            defines: rasterColor.defines,
            overrideFog: affectedByFog
        });
        painter.uploadCommonUniforms(context, program, unwrappedTileID);
        if (source instanceof ImageSource) {
            if (source.boundsBuffer && source.boundsSegments)
                program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, uniformValues, layer.id, source.boundsBuffer, painter.quadTriangleIndexBuffer, source.boundsSegments);
        } else {
            const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = painter.getTileBoundsBuffers(tile);
            program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
        }
    }
    painter.resetStencilClippingMasks();
}
function configureRasterColor(layer, context, gl) {
    const defines = [];
    let mix;
    let range;
    if (layer.paint.get('raster-color')) {
        defines.push('RASTER_COLOR');
        mix = layer.paint.get('raster-color-mix');
        range = layer.paint.get('raster-color-range');
        // Allocate a texture if not allocated
        context.activeTexture.set(gl.TEXTURE2);
        let tex = layer.colorRampTexture;
        if (!tex)
            tex = layer.colorRampTexture = new Texture(context, layer.colorRamp, gl.RGBA);
        tex.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    }
    return {
        mix,
        range,
        defines
    };
}

//      
function drawBackground(painter, sourceCache, layer, coords) {
    const color = layer.paint.get('background-color');
    const opacity = layer.paint.get('background-opacity');
    const emissiveStrength = layer.paint.get('background-emissive-strength');
    if (opacity === 0)
        return;
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    const tileSize = transform.tileSize;
    const image = layer.paint.get('background-pattern');
    if (painter.isPatternMissing(image, layer.scope))
        return;
    const pass = !image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer() ? 'opaque' : 'translucent';
    if (painter.renderPass !== pass)
        return;
    const stencilMode = StencilMode.disabled;
    const depthMode = painter.depthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const programName = image ? 'backgroundPattern' : 'background';
    let tileIDs = coords;
    let backgroundTiles;
    if (!tileIDs) {
        backgroundTiles = painter.getBackgroundTiles();
        tileIDs = Object.values(backgroundTiles).map(tile => tile.tileID);
    }
    if (image) {
        context.activeTexture.set(gl.TEXTURE0);
        painter.imageManager.bind(painter.context, layer.scope);
    }
    for (const tileID of tileIDs) {
        const affectedByFog = painter.isTileAffectedByFog(tileID);
        const program = painter.getOrCreateProgram(programName, { overrideFog: affectedByFog });
        const unwrappedTileID = tileID.toUnwrapped();
        const matrix = coords ? tileID.projMatrix : painter.transform.calculateProjMatrix(unwrappedTileID);
        painter.prepareDrawTile();
        const tile = sourceCache ? sourceCache.getTile(tileID) : backgroundTiles ? backgroundTiles[tileID.key] : new Tile(tileID, tileSize, transform.zoom, painter);
        const uniformValues = image ? backgroundPatternUniformValues(matrix, emissiveStrength, opacity, painter, image, layer.scope, {
            tileID,
            tileSize
        }) : backgroundUniformValues(matrix, emissiveStrength, opacity, color);
        painter.uploadCommonUniforms(context, program, unwrappedTileID);
        const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = painter.getTileBoundsBuffers(tile);
        program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
    }
}

//      
const topColor = new Color$1(1, 0, 0, 1);
const btmColor = new Color$1(0, 1, 0, 1);
const leftColor = new Color$1(0, 0, 1, 1);
const rightColor = new Color$1(1, 0, 1, 1);
const centerColor = new Color$1(0, 1, 1, 1);
function drawDebug(painter, sourceCache, coords) {
    for (let i = 0; i < coords.length; i++) {
        drawDebugTile(painter, sourceCache, coords[i]);
    }
}
function drawDebugPadding(painter) {
    const padding = painter.transform.padding;
    const lineWidth = 3;
    // Top
    drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor);
    // Bottom
    drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor);
    // Left
    drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor);
    // Right
    drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor);
    // Center
    const center = painter.transform.centerPoint;
    drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor);
}
function drawDebugTile(painter, sourceCache, coord) {
    const context = painter.context;
    const tr = painter.transform;
    const gl = context.gl;
    const isGlobeProjection = tr.projection.name === 'globe';
    const definesValues = isGlobeProjection ? ['PROJECTION_GLOBE_VIEW'] : [];
    let posMatrix = coord.projMatrix;
    if (isGlobeProjection && globeToMercatorTransition(tr.zoom) > 0) {
        // We use a custom tile matrix here in order to handle the globe-to-mercator transition
        // the following is equivalent to transform.calculatePosMatrix,
        // except we use transitionTileAABBinECEF instead of globeTileBounds to account for the transition.
        const bounds = transitionTileAABBinECEF(coord.canonical, tr);
        const decode = globeDenormalizeECEF(bounds);
        posMatrix = mat4_1.multiply(new Float32Array(16), tr.globeMatrix, decode);
        mat4_1.multiply(posMatrix, tr.projMatrix, posMatrix);
    }
    const program = painter.getOrCreateProgram('debug', { defines: definesValues });
    const tile = sourceCache.getTileByID(coord.key);
    if (painter.terrain)
        painter.terrain.setupElevationDraw(tile, program);
    const depthMode = DepthMode.disabled;
    const stencilMode = StencilMode.disabled;
    const colorMode = painter.colorModeForRenderPass();
    const id = '$debug';
    context.activeTexture.set(gl.TEXTURE0);
    // Bind the empty texture for drawing outlines
    painter.emptyTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    if (isGlobeProjection) {
        tile._makeGlobeTileDebugBuffers(painter.context, tr);
    } else {
        tile._makeDebugTileBoundsBuffers(painter.context, tr.projection);
    }
    const debugBuffer = tile._tileDebugBuffer || painter.debugBuffer;
    const debugIndexBuffer = tile._tileDebugIndexBuffer || painter.debugIndexBuffer;
    const debugSegments = tile._tileDebugSegments || painter.debugSegments;
    program.draw(painter, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(posMatrix, Color$1.red), id, debugBuffer, debugIndexBuffer, debugSegments, null, null, null, [tile._globeTileDebugBorderBuffer]);
    const tileRawData = tile.latestRawTileData;
    const tileByteLength = tileRawData && tileRawData.byteLength || 0;
    const tileSizeKb = Math.floor(tileByteLength / 1024);
    const tileSize = sourceCache.getTile(coord).tileSize;
    const scaleRatio = 512 / Math.min(tileSize, 512) * (coord.overscaledZ / tr.zoom) * 0.5;
    let tileLabel = coord.canonical.toString();
    if (coord.overscaledZ !== coord.canonical.z) {
        tileLabel += ` => ${ coord.overscaledZ }`;
    }
    tileLabel += ` ${ tileSizeKb }kb`;
    drawTextToOverlay(painter, tileLabel);
    const debugTextBuffer = tile._tileDebugTextBuffer || painter.debugBuffer;
    const debugTextIndexBuffer = tile._tileDebugTextIndexBuffer || painter.quadTriangleIndexBuffer;
    const debugTextSegments = tile._tileDebugTextSegments || painter.debugSegments;
    program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(posMatrix, Color$1.transparent, scaleRatio), id, debugTextBuffer, debugTextIndexBuffer, debugTextSegments, null, null, null, [tile._globeTileDebugTextBuffer]);
}
function drawCrosshair(painter, x, y, color) {
    const size = 20;
    const lineWidth = 2;
    //Vertical line
    drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color);
    //Horizontal line
    drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color);
}
function drawHorizontalLine(painter, y, lineWidth, color) {
    drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color);
}
function drawVerticalLine(painter, x, lineWidth, color) {
    drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color);
}
function drawDebugSSRect(painter, x, y, width, height, color) {
    const context = painter.context;
    const gl = context.gl;
    gl.enable(gl.SCISSOR_TEST);
    gl.scissor(x * exported$1.devicePixelRatio, y * exported$1.devicePixelRatio, width * exported$1.devicePixelRatio, height * exported$1.devicePixelRatio);
    context.clear({ color });
    gl.disable(gl.SCISSOR_TEST);
}
function drawTextToOverlay(painter, text) {
    painter.initDebugOverlayCanvas();
    const canvas = painter.debugOverlayCanvas;
    const gl = painter.context.gl;
    const ctx2d = painter.debugOverlayCanvas.getContext('2d');
    ctx2d.clearRect(0, 0, canvas.width, canvas.height);
    ctx2d.shadowColor = 'white';
    ctx2d.shadowBlur = 2;
    ctx2d.lineWidth = 1.5;
    ctx2d.strokeStyle = 'white';
    ctx2d.textBaseline = 'top';
    ctx2d.font = `bold ${ 36 }px Open Sans, sans-serif`;
    ctx2d.fillText(text, 5, 5);
    ctx2d.strokeText(text, 5, 5);
    painter.debugOverlayTexture.update(canvas);
    painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
}

//      
function drawCustom(painter, sourceCache, layer, coords) {
    const context = painter.context;
    const implementation = layer.implementation;
    if (painter.transform.projection.unsupportedLayers && painter.transform.projection.unsupportedLayers.includes('custom') && !(painter.terrain && (painter.terrain.renderingToTexture || painter.renderPass === 'offscreen') && layer.isLayerDraped(sourceCache))) {
        warnOnce('Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.');
        return;
    }
    if (painter.renderPass === 'offscreen') {
        const prerender = implementation.prerender;
        if (prerender) {
            painter.setCustomLayerDefaults();
            context.setColorMode(painter.colorModeForRenderPass());
            if (painter.transform.projection.name === 'globe') {
                const center = painter.transform.pointMerc;
                prerender.call(implementation, context.gl, painter.transform.customLayerMatrix(), painter.transform.getProjection(), painter.transform.globeToMercatorMatrix(), globeToMercatorTransition(painter.transform.zoom), [
                    center.x,
                    center.y
                ], painter.transform.pixelsPerMeterRatio);
            } else {
                prerender.call(implementation, context.gl, painter.transform.customLayerMatrix());
            }
            context.setDirty();
            painter.setBaseState();
        }
    } else if (painter.renderPass === 'translucent') {
        if (painter.terrain && painter.terrain.renderingToTexture) {
            const renderToTile = implementation.renderToTile;
            if (renderToTile) {
                const c = coords[0].canonical;
                const unwrapped = new MercatorCoordinate(c.x + coords[0].wrap * (1 << c.z), c.y, c.z);
                context.setDepthMode(DepthMode.disabled);
                context.setStencilMode(StencilMode.disabled);
                context.setColorMode(painter.colorModeForRenderPass());
                painter.setCustomLayerDefaults();
                renderToTile.call(implementation, context.gl, unwrapped);
                context.setDirty();
                painter.setBaseState();
            }
            return;
        }
        painter.setCustomLayerDefaults();
        context.setColorMode(painter.colorModeForRenderPass());
        context.setStencilMode(StencilMode.disabled);
        const depthMode = implementation.renderingMode === '3d' ? new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) : painter.depthModeForSublayer(0, DepthMode.ReadOnly);
        context.setDepthMode(depthMode);
        if (painter.transform.projection.name === 'globe') {
            const center = painter.transform.pointMerc;
            implementation.render(context.gl, painter.transform.customLayerMatrix(), painter.transform.getProjection(), painter.transform.globeToMercatorMatrix(), globeToMercatorTransition(painter.transform.zoom), [
                center.x,
                center.y
            ], painter.transform.pixelsPerMeterRatio);
        } else {
            implementation.render(context.gl, painter.transform.customLayerMatrix());
        }
        context.setDirty();
        painter.setBaseState();
        context.bindFramebuffer.set(null);
    }
}

//      
const skyboxAttributes = createLayout([{
        name: 'a_pos_3f',
        components: 3,
        type: 'Float32'
    }]);
const {members, size, alignment} = skyboxAttributes;

//      
function addVertex(vertexArray, x, y, z) {
    vertexArray.emplaceBack(// a_pos
    x, y, z);
}
class SkyboxGeometry {
    constructor(context) {
        this.vertexArray = new StructArrayLayout3f12();
        this.indices = new StructArrayLayout3ui6();
        addVertex(this.vertexArray, -1, -1, 1);
        addVertex(this.vertexArray, 1, -1, 1);
        addVertex(this.vertexArray, -1, 1, 1);
        addVertex(this.vertexArray, 1, 1, 1);
        addVertex(this.vertexArray, -1, -1, -1);
        addVertex(this.vertexArray, 1, -1, -1);
        addVertex(this.vertexArray, -1, 1, -1);
        addVertex(this.vertexArray, 1, 1, -1);
        // +x
        this.indices.emplaceBack(5, 1, 3);
        this.indices.emplaceBack(3, 7, 5);
        // -x
        this.indices.emplaceBack(6, 2, 0);
        this.indices.emplaceBack(0, 4, 6);
        // +y
        this.indices.emplaceBack(2, 6, 7);
        this.indices.emplaceBack(7, 3, 2);
        // -y
        this.indices.emplaceBack(5, 4, 0);
        this.indices.emplaceBack(0, 1, 5);
        // +z
        this.indices.emplaceBack(0, 2, 3);
        this.indices.emplaceBack(3, 1, 0);
        // -z
        this.indices.emplaceBack(7, 6, 4);
        this.indices.emplaceBack(4, 5, 7);
        this.vertexBuffer = context.createVertexBuffer(this.vertexArray, members);
        this.indexBuffer = context.createIndexBuffer(this.indices);
        this.segment = SegmentVector.simpleSegment(0, 0, 36, 12);
    }
}

//      
function drawSky(painter, sourceCache, layer) {
    const tr = painter.transform;
    // Note: we render sky for globe projection during the transition to mercator or if atmosphere is disabled.
    const transitionOpacity = !painter._atmosphere ? 1 : globeToMercatorTransition(tr.zoom);
    const opacity = layer.paint.get('sky-opacity') * transitionOpacity;
    if (opacity === 0) {
        return;
    }
    const context = painter.context;
    const type = layer.paint.get('sky-type');
    const depthMode = new DepthMode(context.gl.LEQUAL, DepthMode.ReadOnly, [
        0,
        1
    ]);
    const temporalOffset = painter.frameCounter / 1000 % 1;
    if (type === 'atmosphere') {
        if (painter.renderPass === 'offscreen') {
            if (layer.needsSkyboxCapture(painter)) {
                captureSkybox(painter, layer, 32, 32);
                layer.markSkyboxValid(painter);
            }
        } else if (painter.renderPass === 'sky') {
            drawSkyboxFromCapture(painter, layer, depthMode, opacity, temporalOffset);
        }
    } else if (type === 'gradient') {
        if (painter.renderPass === 'sky') {
            drawSkyboxGradient(painter, layer, depthMode, opacity, temporalOffset);
        }
    } else ;
}
function drawSkyboxGradient(painter, layer, depthMode, opacity, temporalOffset) {
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    const program = painter.getOrCreateProgram('skyboxGradient');
    // Lazily initialize geometry and texture if they havent been created yet.
    if (!layer.skyboxGeometry) {
        layer.skyboxGeometry = new SkyboxGeometry(context);
    }
    context.activeTexture.set(gl.TEXTURE0);
    let colorRampTexture = layer.colorRampTexture;
    if (!colorRampTexture) {
        colorRampTexture = layer.colorRampTexture = new Texture(context, layer.colorRamp, gl.RGBA);
    }
    colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    const uniformValues = skyboxGradientUniformValues(transform.skyboxMatrix, layer.getCenter(painter, false), layer.paint.get('sky-gradient-radius'), opacity, temporalOffset);
    painter.uploadCommonUniforms(context, program);
    program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.backCW, uniformValues, 'skyboxGradient', layer.skyboxGeometry.vertexBuffer, layer.skyboxGeometry.indexBuffer, layer.skyboxGeometry.segment);
}
function drawSkyboxFromCapture(painter, layer, depthMode, opacity, temporalOffset) {
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    const program = painter.getOrCreateProgram('skybox');
    context.activeTexture.set(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_CUBE_MAP, layer.skyboxTexture);
    const uniformValues = skyboxUniformValues(transform.skyboxMatrix, layer.getCenter(painter, false), 0, opacity, temporalOffset);
    painter.uploadCommonUniforms(context, program);
    program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.backCW, uniformValues, 'skybox', layer.skyboxGeometry.vertexBuffer, layer.skyboxGeometry.indexBuffer, layer.skyboxGeometry.segment);
}
function drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, i) {
    const context = painter.context;
    const gl = context.gl;
    const atmosphereColor = layer.paint.get('sky-atmosphere-color');
    const atmosphereHaloColor = layer.paint.get('sky-atmosphere-halo-color');
    const sunIntensity = layer.paint.get('sky-atmosphere-sun-intensity');
    const uniformValues = skyboxCaptureUniformValues(mat3_1.fromMat4(mat3_1.create(), faceRotate), sunDirection, sunIntensity, atmosphereColor, atmosphereHaloColor);
    const glFace = gl.TEXTURE_CUBE_MAP_POSITIVE_X + i;
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glFace, layer.skyboxTexture, 0);
    program.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.unblended, CullFaceMode.frontCW, uniformValues, 'skyboxCapture', layer.skyboxGeometry.vertexBuffer, layer.skyboxGeometry.indexBuffer, layer.skyboxGeometry.segment);
}
function captureSkybox(painter, layer, width, height) {
    const context = painter.context;
    const gl = context.gl;
    let fbo = layer.skyboxFbo;
    // Using absence of fbo as a signal for lazy initialization of all resources, cache resources in layer object
    if (!fbo) {
        fbo = layer.skyboxFbo = context.createFramebuffer(width, height, true, null);
        layer.skyboxGeometry = new SkyboxGeometry(context);
        layer.skyboxTexture = context.gl.createTexture();
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, layer.skyboxTexture);
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        for (let i = 0; i < 6; ++i) {
            const glFace = gl.TEXTURE_CUBE_MAP_POSITIVE_X + i;
            // The format here could be RGB, but render tests are not happy with rendering to such a format
            gl.texImage2D(glFace, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
        }
    }
    context.bindFramebuffer.set(fbo.framebuffer);
    context.viewport.set([
        0,
        0,
        width,
        height
    ]);
    const sunDirection = layer.getCenter(painter, true);
    const program = painter.getOrCreateProgram('skyboxCapture');
    const faceRotate = new Float64Array(16);
    // +x;
    mat4_1.identity(faceRotate);
    mat4_1.rotateY(faceRotate, faceRotate, -Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 0);
    // -x
    mat4_1.identity(faceRotate);
    mat4_1.rotateY(faceRotate, faceRotate, Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 1);
    // +y
    mat4_1.identity(faceRotate);
    mat4_1.rotateX(faceRotate, faceRotate, -Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 2);
    // -y
    mat4_1.identity(faceRotate);
    mat4_1.rotateX(faceRotate, faceRotate, Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 3);
    // +z
    mat4_1.identity(faceRotate);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 4);
    // -z
    mat4_1.identity(faceRotate);
    mat4_1.rotateY(faceRotate, faceRotate, Math.PI);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 5);
    context.viewport.set([
        0,
        0,
        painter.width,
        painter.height
    ]);
}

//      
const atmosphereLayout = createLayout([
    {
        type: 'Float32',
        name: 'a_pos',
        components: 3
    },
    {
        type: 'Float32',
        name: 'a_uv',
        components: 2
    }
]);

//      
class AtmosphereBuffer {
    constructor(context) {
        const vertices = new StructArrayLayout5f20();
        vertices.emplaceBack(-1, 1, 1, 0, 0);
        vertices.emplaceBack(1, 1, 1, 1, 0);
        vertices.emplaceBack(1, -1, 1, 1, 1);
        vertices.emplaceBack(-1, -1, 1, 0, 1);
        const triangles = new StructArrayLayout3ui6();
        triangles.emplaceBack(0, 1, 2);
        triangles.emplaceBack(2, 3, 0);
        this.vertexBuffer = context.createVertexBuffer(vertices, atmosphereLayout.members);
        this.indexBuffer = context.createIndexBuffer(triangles);
        this.segments = SegmentVector.simpleSegment(0, 0, 4, 2);
    }
    destroy() {
        this.vertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.segments.destroy();
    }
}

//      
const starsLayout = createLayout([
    {
        type: 'Float32',
        name: 'a_pos_3f',
        components: 3
    },
    {
        type: 'Float32',
        name: 'a_uv',
        components: 2
    },
    {
        type: 'Float32',
        name: 'a_size_scale',
        components: 1
    },
    {
        type: 'Float32',
        name: 'a_fade_opacity',
        components: 1
    }
]);

//      
function generateUniformDistributedPointsOnSphere(pointsCount) {
    const sRand = mulberry32(30);
    const points = [];
    for (let i = 0; i < pointsCount; ++i) {
        const lon = 2 * Math.PI * sRand();
        const lat = Math.acos(1 - 2 * sRand()) - Math.PI * 0.5;
        points.push(vec3_1.fromValues(Math.cos(lat) * Math.cos(lon), Math.cos(lat) * Math.sin(lon), Math.sin(lat)));
    }
    return points;
}
class Atmosphere {
    constructor() {
        this.colorModeAlphaBlendedWriteRGB = new ColorMode([
            ONE,
            ONE_MINUS_SRC_ALPHA,
            ONE,
            ONE_MINUS_SRC_ALPHA
        ], Color$1.transparent, [
            true,
            true,
            true,
            false
        ]);
        this.colorModeWriteAlpha = new ColorMode([
            ONE,
            ZERO,
            ONE,
            ZERO
        ], Color$1.transparent, [
            false,
            false,
            false,
            true
        ]);
    }
    update(painter) {
        const context = painter.context;
        if (!this.atmosphereBuffer) {
            this.atmosphereBuffer = new AtmosphereBuffer(context);
            // Part of internal stlye spec, not exposed to gl-js
            const starsCount = 16000;
            const sizeRange = 100;
            const intensityRange = 200;
            const stars = generateUniformDistributedPointsOnSphere(starsCount);
            const sRand = mulberry32(300);
            const vertices = new StructArrayLayout7f28();
            const triangles = new StructArrayLayout3ui6();
            let base = 0;
            for (let i = 0; i < stars.length; ++i) {
                const star = vec3_1.scale([], stars[i], 200);
                const size = Math.max(0, 1 + 0.01 * sizeRange * (-0.5 + 1 * sRand()));
                const intensity = Math.max(0, 1 + 0.01 * intensityRange * (-0.5 + 1 * sRand()));
                vertices.emplaceBack(star[0], star[1], star[2], -1, -1, size, intensity);
                vertices.emplaceBack(star[0], star[1], star[2], 1, -1, size, intensity);
                vertices.emplaceBack(star[0], star[1], star[2], 1, 1, size, intensity);
                vertices.emplaceBack(star[0], star[1], star[2], -1, 1, size, intensity);
                triangles.emplaceBack(base + 0, base + 1, base + 2);
                triangles.emplaceBack(base + 0, base + 2, base + 3);
                base += 4;
            }
            this.starsVx = context.createVertexBuffer(vertices, starsLayout.members);
            this.starsIdx = context.createIndexBuffer(triangles);
            this.starsSegments = SegmentVector.simpleSegment(0, 0, vertices.length, triangles.length);
        }
    }
    destroy() {
        if (this.atmosphereBuffer) {
            this.atmosphereBuffer.destroy();
        }
        if (this.starsVx) {
            this.starsVx.destroy();
        }
        if (this.starsIdx) {
            this.starsIdx.destroy();
        }
    }
    drawAtmosphereGlow(painter, fog) {
        const context = painter.context;
        const gl = context.gl;
        const tr = painter.transform;
        const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadOnly, [
            0,
            1
        ]);
        const transitionT = globeToMercatorTransition(tr.zoom);
        const fogColor = fog.properties.get('color').toArray01();
        const highColor = fog.properties.get('high-color').toArray01();
        const spaceColor = fog.properties.get('space-color').toArray01PremultipliedAlpha();
        // https://www.desmos.com/calculator/oanvvpr36d
        // Ensure horizon blend is 0-exclusive to prevent division by 0 in the shader
        const minHorizonBlend = 0.0005;
        const horizonBlend = mapValue(fog.properties.get('horizon-blend'), 0, 1, minHorizonBlend, 0.25);
        // Use a slightly smaller size of the globe to account for custom
        // antialiasing that reduces the size of the globe of two pixels
        // https://www.desmos.com/calculator/xpgmzghc37
        const globeRadius = globeUseCustomAntiAliasing(painter, context, tr) && horizonBlend === minHorizonBlend ? tr.worldSize / (2 * Math.PI * 1.025) - 1 : tr.globeRadius;
        const temporalOffset = painter.frameCounter / 1000 % 1;
        const globeCenterInViewSpace = tr.globeCenterInViewSpace;
        const globeCenterDistance = vec3_1.length(globeCenterInViewSpace);
        const distanceToHorizon = Math.sqrt(Math.pow(globeCenterDistance, 2) - Math.pow(globeRadius, 2));
        const horizonAngle = Math.acos(distanceToHorizon / globeCenterDistance);
        const draw = alphaPass => {
            const defines = tr.projection.name === 'globe' ? [
                'PROJECTION_GLOBE_VIEW',
                'FOG'
            ] : ['FOG'];
            if (alphaPass) {
                defines.push('ALPHA_PASS');
            }
            const program = painter.getOrCreateProgram('globeAtmosphere', { defines: defines });
            const uniforms = atmosphereUniformValues(tr.frustumCorners.TL, tr.frustumCorners.TR, tr.frustumCorners.BR, tr.frustumCorners.BL, tr.frustumCorners.horizon, transitionT, horizonBlend, fogColor, highColor, spaceColor, temporalOffset, horizonAngle);
            painter.uploadCommonUniforms(context, program);
            const buffer = this.atmosphereBuffer;
            const colorMode = alphaPass ? this.colorModeWriteAlpha : this.colorModeAlphaBlendedWriteRGB;
            const name = alphaPass ? 'atmosphere_glow_alpha' : 'atmosphere_glow';
            if (buffer) {
                program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCW, uniforms, name, buffer.vertexBuffer, buffer.indexBuffer, buffer.segments);
            }
        };
        // Write atmosphere color
        draw(false);
        // Write atmosphere alpha - transparent areas need to be explicitly marked in a separate pass
        draw(true);
    }
    drawStars(painter, fog) {
        const starIntensity = clamp(fog.properties.get('star-intensity'), 0, 1);
        if (starIntensity === 0) {
            return;
        }
        const context = painter.context;
        const gl = context.gl;
        const tr = painter.transform;
        const program = painter.getOrCreateProgram('stars');
        // Exposed in internal style spec for mobile
        const sizeMultiplier = 0.15;
        const orientation = quat_1.identity([]);
        quat_1.rotateX(orientation, orientation, -tr._pitch);
        quat_1.rotateZ(orientation, orientation, -tr.angle);
        quat_1.rotateX(orientation, orientation, degToRad(tr._center.lat));
        quat_1.rotateY(orientation, orientation, -degToRad(tr._center.lng));
        const rotationMatrix = mat4_1.fromQuat(new Float32Array(16), orientation);
        const mvp = mat4_1.multiply([], tr.starsProjMatrix, rotationMatrix);
        const modelView3 = mat3_1.fromMat4([], rotationMatrix);
        const modelviewInv = mat3_1.invert([], modelView3);
        const camUp = [
            0,
            1,
            0
        ];
        vec3_1.transformMat3(camUp, camUp, modelviewInv);
        vec3_1.scale(camUp, camUp, sizeMultiplier);
        const camRight = [
            1,
            0,
            0
        ];
        vec3_1.transformMat3(camRight, camRight, modelviewInv);
        vec3_1.scale(camRight, camRight, sizeMultiplier);
        const uniforms = starsUniformValues(mvp, camUp, camRight, starIntensity);
        painter.uploadCommonUniforms(context, program);
        if (this.starsVx && this.starsIdx) {
            program.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, this.colorModeAlphaBlendedWriteRGB, CullFaceMode.disabled, uniforms, 'atmosphere_stars', this.starsVx, this.starsIdx, this.starsSegments);
        }
    }
}

//      
function fogMatrixForModel(modelMatrix, transform) {
    // convert model matrix from the default world size to the one used by the fog
    const fogMatrix = [...modelMatrix];
    const scale = transform.cameraWorldSizeForFog / transform.worldSize;
    const scaleMatrix = mat4_1.identity([]);
    mat4_1.scale(scaleMatrix, scaleMatrix, [
        scale,
        scale,
        1
    ]);
    mat4_1.multiply(fogMatrix, scaleMatrix, fogMatrix);
    mat4_1.multiply(fogMatrix, transform.worldToFogMatrix, fogMatrix);
    return fogMatrix;
}
// Collect defines and dynamic buffers (colors, normals, uv) and bind textures. Used for single mesh and instanced draw.
function setupMeshDraw(definesValues, dynamicBuffers, mesh, painter) {
    const material = mesh.material;
    const context = painter.context;
    const {baseColorTexture, metallicRoughnessTexture} = material.pbrMetallicRoughness;
    const {normalTexture, occlusionTexture, emissionTexture} = material;
    function setupTexture(texture, define, slot) {
        if (!texture)
            return;
        definesValues.push(define);
        context.activeTexture.set(context.gl.TEXTURE0 + slot);
        if (texture.gfxTexture) {
            const {minFilter, magFilter, wrapS, wrapT} = texture.sampler;
            texture.gfxTexture.bindExtraParam(minFilter, magFilter, wrapS, wrapT);
        }
    }
    // Textures
    setupTexture(baseColorTexture, 'HAS_TEXTURE_u_baseColorTexture', TextureSlots.BaseColor);
    setupTexture(metallicRoughnessTexture, 'HAS_TEXTURE_u_metallicRoughnessTexture', TextureSlots.MetallicRoughness);
    setupTexture(normalTexture, 'HAS_TEXTURE_u_normalTexture', TextureSlots.Normal);
    setupTexture(occlusionTexture, 'HAS_TEXTURE_u_occlusionTexture', TextureSlots.Occlusion);
    setupTexture(emissionTexture, 'HAS_TEXTURE_u_emissionTexture', TextureSlots.Emission);
    if (mesh.texcoordBuffer) {
        definesValues.push('HAS_ATTRIBUTE_a_uv_2f');
        dynamicBuffers.push(mesh.texcoordBuffer);
    }
    if (mesh.colorBuffer) {
        const colorDefine = mesh.colorBuffer.itemSize === 12 ? 'HAS_ATTRIBUTE_a_color_3f' : 'HAS_ATTRIBUTE_a_color_4f';
        definesValues.push(colorDefine);
        dynamicBuffers.push(mesh.colorBuffer);
    }
    if (mesh.normalBuffer) {
        definesValues.push('HAS_ATTRIBUTE_a_normal_3f');
        dynamicBuffers.push(mesh.normalBuffer);
    }
    if (mesh.pbrBuffer) {
        definesValues.push('HAS_ATTRIBUTE_a_pbr');
        definesValues.push('HAS_ATTRIBUTE_a_heightBasedEmissiveStrength');
        dynamicBuffers.push(mesh.pbrBuffer);
    }
    if (material.alphaMode === 'OPAQUE' || material.alphaMode === 'MASK') {
        definesValues.push('UNPREMULT_TEXTURE_IN_SHADER');
    }
    // just to make the rendertests the same than native
    if (!material.defined) {
        definesValues.push('DIFFUSE_SHADED');
    }
    definesValues.push('USE_STANDARD_DERIVATIVES');
}
function drawMesh(sortedMesh, painter, layer, modelParameters, stencilMode, colorMode) {
    const opacity = layer.paint.get('model-opacity');
    const context = painter.context;
    const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    const tr = painter.transform;
    const mesh = sortedMesh.mesh;
    const material = mesh.material;
    const pbr = material.pbrMetallicRoughness;
    const fog = painter.style.fog;
    let lightingMatrix;
    if (painter.transform.projection.zAxisUnit === 'pixels') {
        lightingMatrix = [...sortedMesh.nodeModelMatrix];
    } else {
        lightingMatrix = mat4_1.multiply([], modelParameters.zScaleMatrix, sortedMesh.nodeModelMatrix);
    }
    mat4_1.multiply(lightingMatrix, modelParameters.negCameraPosMatrix, lightingMatrix);
    const normalMatrix = mat4_1.invert([], lightingMatrix);
    mat4_1.transpose(normalMatrix, normalMatrix);
    const uniformValues = modelUniformValues(new Float32Array(sortedMesh.worldViewProjection), new Float32Array(lightingMatrix), new Float32Array(normalMatrix), painter, opacity, pbr.baseColorFactor, material.emissiveFactor, pbr.metallicFactor, pbr.roughnessFactor, material, layer);
    const programOptions = { defines: [] };
    // Extra buffers (colors, normals, texCoords)
    const dynamicBuffers = [];
    setupMeshDraw(programOptions.defines, dynamicBuffers, mesh, painter);
    const shadowRenderer = painter.shadowRenderer;
    if (shadowRenderer) {
        shadowRenderer.useNormalOffset = false;
    }
    let fogMatrixArray = null;
    if (fog) {
        const fogMatrix = fogMatrixForModel(sortedMesh.nodeModelMatrix, painter.transform);
        fogMatrixArray = new Float32Array(fogMatrix);
        if (tr.projection.name !== 'globe') {
            const min = mesh.aabb.min;
            const max = mesh.aabb.max;
            const [minOpacity, maxOpacity] = fog.getOpacityForBounds(fogMatrix, min[0], min[1], max[0], max[1]);
            programOptions.overrideFog = minOpacity >= FOG_OPACITY_THRESHOLD || maxOpacity >= FOG_OPACITY_THRESHOLD;
        }
    }
    const cutoffParams = getCutoffParams(painter, layer.paint.get('model-cutoff-fade-range'));
    if (cutoffParams.shouldRenderCutoff) {
        programOptions.defines.push('RENDER_CUTOFF');
    }
    const program = painter.getOrCreateProgram('model', programOptions);
    painter.uploadCommonUniforms(context, program, null, fogMatrixArray, cutoffParams);
    const isShadowPass = painter.renderPass === 'shadow';
    if (!isShadowPass && shadowRenderer) {
        shadowRenderer.setupShadowsFromMatrix(sortedMesh.nodeModelMatrix, program);
    }
    const cullFaceMode = mesh.material.doubleSided ? CullFaceMode.disabled : CullFaceMode.backCCW;
    program.draw(painter, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments, layer.paint, painter.transform.zoom, undefined, dynamicBuffers);
}
function upload$1(painter, sourceCache, scope) {
    const modelSource = sourceCache.getSource();
    if (!modelSource.loaded())
        return;
    if (modelSource.type === 'vector' || modelSource.type === 'geojson') {
        if (painter.modelManager) {
            // Do it here, to prevent modelManager handling in Painter.
            painter.modelManager.upload(painter, scope);
        }
        return;
    }
    if (modelSource.type === 'batched-model') {
        // batched models uploads happen in tile_3d_bucket
        return;
    }
    const models = modelSource.getModels();
    // Upload models
    for (const model of models) {
        model.upload(painter.context);
    }
}
function prepareMeshes(transform, node, modelMatrix, projectionMatrix, modelIndex, transparentMeshes, opaqueMeshes) {
    let nodeModelMatrix;
    if (transform.projection.name === 'globe') {
        nodeModelMatrix = convertModelMatrixForGlobe(modelMatrix, transform);
    } else {
        nodeModelMatrix = [...modelMatrix];
    }
    mat4_1.multiply(nodeModelMatrix, nodeModelMatrix, node.matrix);
    const worldViewProjection = mat4_1.multiply([], projectionMatrix, nodeModelMatrix);
    if (node.meshes) {
        for (const mesh of node.meshes) {
            if (mesh.material.alphaMode !== 'BLEND') {
                const opaqueMesh = {
                    mesh,
                    depth: 0,
                    modelIndex,
                    worldViewProjection,
                    nodeModelMatrix
                };
                opaqueMeshes.push(opaqueMesh);
                continue;
            }
            const centroidPos = vec3_1.transformMat4([], mesh.centroid, worldViewProjection);
            // Filter meshes behind the camera
            if (centroidPos[2] > 0) {
                const transparentMesh = {
                    mesh,
                    depth: centroidPos[2],
                    modelIndex,
                    worldViewProjection,
                    nodeModelMatrix
                };
                transparentMeshes.push(transparentMesh);
            }
        }
    }
    if (node.children) {
        for (const child of node.children) {
            prepareMeshes(transform, child, modelMatrix, projectionMatrix, modelIndex, transparentMeshes, opaqueMeshes);
        }
    }
}
function drawShadowCaster(mesh, matrix, painter, layer) {
    const shadowRenderer = painter.shadowRenderer;
    if (!shadowRenderer)
        return;
    const depthMode = shadowRenderer.getShadowPassDepthMode();
    const colorMode = shadowRenderer.getShadowPassColorMode();
    const shadowMatrix = shadowRenderer.calculateShadowPassMatrixFromMatrix(matrix);
    const uniformValues = modelDepthUniformValues(shadowMatrix);
    const definesValues = ['DEPTH_TEXTURE'];
    const program = painter.getOrCreateProgram('modelDepth', { defines: definesValues });
    const context = painter.context;
    program.draw(painter, context.gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments, layer.paint, painter.transform.zoom, undefined, undefined);
}
function drawModels(painter, sourceCache, layer, coords) {
    if (painter.renderPass === 'opaque') {
        return;
    }
    // early return if totally transparent
    const opacity = layer.paint.get('model-opacity');
    if (opacity === 0) {
        return;
    }
    const castShadows = layer.paint.get('model-cast-shadows');
    if (painter.renderPass === 'shadow') {
        if (!castShadows) {
            return;
        }
        if (painter.terrain) {
            const noShadowCutoff = 0.65;
            if (opacity < noShadowCutoff) {
                const expression = layer._transitionablePaint._values['model-opacity'].value.expression;
                if (expression instanceof ZoomDependentExpression) {
                    // avoid rendering shadows during fade in / fade out on terrain
                    return;
                }
            }
        }
    }
    const shadowRenderer = painter.shadowRenderer;
    const receiveShadows = layer.paint.get('model-receive-shadows');
    if (shadowRenderer) {
        shadowRenderer.useNormalOffset = true;
        if (!receiveShadows) {
            shadowRenderer.enabled = false;
        }
    }
    const cleanup = () => {
        if (shadowRenderer) {
            shadowRenderer.useNormalOffset = true;
            if (!receiveShadows) {
                shadowRenderer.enabled = true;
            }
        }
    };
    const modelSource = sourceCache.getSource();
    if (painter.renderPass === 'light-beam' && modelSource.type !== 'batched-model') {
        return;
    }
    if (modelSource.type === 'vector' || modelSource.type === 'geojson') {
        drawInstancedModels(painter, sourceCache, layer, coords);
        cleanup();
        return;
    }
    if (!modelSource.loaded())
        return;
    if (modelSource.type === 'batched-model') {
        drawBatchedModels(painter, sourceCache, layer, coords);
        cleanup();
        return;
    }
    const models = modelSource.getModels();
    const modelParametersVector = [];
    const mercCameraPos = painter.transform.getFreeCameraOptions().position;
    const cameraPos = vec3_1.scale([], [
        mercCameraPos.x,
        mercCameraPos.y,
        mercCameraPos.z
    ], painter.transform.worldSize);
    vec3_1.negate(cameraPos, cameraPos);
    const transparentMeshes = [];
    const opaqueMeshes = [];
    let modelIndex = 0;
    // Draw models
    for (const model of models) {
        const rotation = layer.paint.get('model-rotation').constantOr(null);
        const scale = layer.paint.get('model-scale').constantOr(null);
        const translation = layer.paint.get('model-translation').constantOr(null);
        // update model matrices
        model.computeModelMatrix(painter, rotation, scale, translation, true, true, false);
        // compute model parameters matrices
        const negCameraPosMatrix = mat4_1.identity([]);
        const modelMetersPerPixel = getMetersPerPixelAtLatitude(model.position.lat, painter.transform.zoom);
        const modelPixelsPerMeter = 1 / modelMetersPerPixel;
        const zScaleMatrix = mat4_1.fromScaling([], [
            1,
            1,
            modelPixelsPerMeter
        ]);
        mat4_1.translate(negCameraPosMatrix, negCameraPosMatrix, cameraPos);
        const modelParameters = {
            zScaleMatrix,
            negCameraPosMatrix
        };
        modelParametersVector.push(modelParameters);
        for (const node of model.nodes) {
            prepareMeshes(painter.transform, node, model.matrix, painter.transform.projMatrix, modelIndex, transparentMeshes, opaqueMeshes);
        }
        modelIndex++;
    }
    // Sort the transparent meshes by depth
    transparentMeshes.sort((a, b) => {
        return b.depth - a.depth;
    });
    if (painter.renderPass === 'shadow') {
        for (const opaqueMesh of opaqueMeshes) {
            drawShadowCaster(opaqueMesh.mesh, opaqueMesh.nodeModelMatrix, painter, layer);
        }
        // Draw transparent sorted meshes
        for (const transparentMesh of transparentMeshes) {
            drawShadowCaster(transparentMesh.mesh, transparentMesh.nodeModelMatrix, painter, layer);
        }
        // Finish the render pass
        cleanup();
        return;
    }
    // Draw opaque meshes
    if (opacity === 1) {
        for (const opaqueMesh of opaqueMeshes) {
            drawMesh(opaqueMesh, painter, layer, modelParametersVector[opaqueMesh.modelIndex], StencilMode.disabled, painter.colorModeForRenderPass());
        }
    } else {
        for (const opaqueMesh of opaqueMeshes) {
            // If we have layer opacity draw with two passes opaque meshes
            drawMesh(opaqueMesh, painter, layer, modelParametersVector[opaqueMesh.modelIndex], StencilMode.disabled, ColorMode.disabled);
        }
        for (const opaqueMesh of opaqueMeshes) {
            drawMesh(opaqueMesh, painter, layer, modelParametersVector[opaqueMesh.modelIndex], painter.stencilModeFor3D(), painter.colorModeForRenderPass());
        }
        painter.resetStencilClippingMasks();
    }
    // Draw transparent sorted meshes
    for (const transparentMesh of transparentMeshes) {
        drawMesh(transparentMesh, painter, layer, modelParametersVector[transparentMesh.modelIndex], StencilMode.disabled, painter.colorModeForRenderPass());
    }
    cleanup();
}
// If terrain changes, update elevations (baked in translation).
function updateModelBucketsElevation(painter, bucket, bucketTileID) {
    let exaggeration = painter.terrain ? painter.terrain.exaggeration() : 0;
    let dem;
    if (painter.terrain && exaggeration > 0) {
        const terrain = painter.terrain;
        const demTile = terrain.findDEMTileFor(bucketTileID);
        if (demTile && demTile.dem) {
            dem = DEMSampler.create(terrain, bucketTileID, demTile);
        } else {
            exaggeration = 0;
        }
    }
    if (exaggeration === 0) {
        bucket.terrainElevationMin = 0;
        bucket.terrainElevationMax = 0;
    }
    if (exaggeration === bucket.validForExaggeration && (exaggeration === 0 || dem && dem._demTile && dem._demTile.tileID === bucket.validForDEMTile.id && dem._dem._timestamp === bucket.validForDEMTile.timestamp)) {
        return false;
    }
    let elevationMin;
    let elevationMax;
    for (const modelId in bucket.instancesPerModel) {
        const instances = bucket.instancesPerModel[modelId];
        for (let i = 0; i < instances.instancedDataArray.length; ++i) {
            const x = instances.instancedDataArray.float32[i * 16] | 0;
            const y = instances.instancedDataArray.float32[i * 16 + 1] | 0;
            const elevation = (dem ? exaggeration * dem.getElevationAt(x, y, true, true) : 0) + instances.instancesEvaluatedElevation[i];
            instances.instancedDataArray.float32[i * 16 + 6] = elevation;
            elevationMin = elevationMin ? Math.min(bucket.terrainElevationMin, elevation) : elevation;
            elevationMax = elevationMax ? Math.max(bucket.terrainElevationMax, elevation) : elevation;
        }
    }
    bucket.terrainElevationMin = elevationMin ? elevationMin : 0;
    bucket.terrainElevationMax = elevationMax ? elevationMax : 0;
    bucket.validForExaggeration = exaggeration;
    bucket.validForDEMTile = dem && dem._demTile ? {
        id: dem._demTile.tileID,
        timestamp: dem._dem._timestamp
    } : {
        id: undefined,
        timestamp: 0
    };
    return true;
}
function updateModelBucketData(painter, bucket, bucketTileID) {
    const bucketContentsUpdatedByZoom = bucket.updateZoomBasedPaintProperties();
    const bucketContentsUpdatedByElevation = updateModelBucketsElevation(painter, bucket, bucketTileID);
    if (bucketContentsUpdatedByZoom || bucketContentsUpdatedByElevation) {
        bucket.uploaded = false;
        bucket.upload(painter.context);
    }
}
// preallocate structure used to reduce re-allocation during rendering and flow checks
const renderData = {
    shadowUniformsInitialized: false,
    useSingleShadowCascade: false,
    tileMatrix: new Float64Array(16),
    shadowTileMatrix: new Float32Array(16),
    aabb: new Aabb([
        0,
        0,
        0
    ], [
        EXTENT,
        EXTENT,
        0
    ])
};
function calculateTileZoom(id, tr) {
    const tiles = 1 << id.canonical.z;
    const cameraPos = tr.getFreeCameraOptions().position;
    const elevation = tr.elevation;
    // Compute tile zoom from the distance between the camera and
    // the closest point on either tile's bottom plane or on a plane
    // elevated to center altitude, whichever is higher. Using center altitude
    // allows us to compensate tall tiles that have high variance in
    // instance placement on z-axis.
    const minx = id.canonical.x / tiles;
    const maxx = (id.canonical.x + 1) / tiles;
    const miny = id.canonical.y / tiles;
    const maxy = (id.canonical.y + 1) / tiles;
    let height = tr._centerAltitude;
    if (elevation) {
        const minmax = elevation.getMinMaxForTile(id);
        if (minmax && minmax.max > height) {
            height = minmax.max;
        }
    }
    const distx = clamp(cameraPos.x, minx, maxx) - cameraPos.x;
    const disty = clamp(cameraPos.y, miny, maxy) - cameraPos.y;
    const distz = mercatorZfromAltitude(height, tr.center.lat) - cameraPos.z;
    return tr._zoomFromMercatorZ(Math.sqrt(distx * distx + disty * disty + distz * distz));
}
function drawInstancedModels(painter, source, layer, coords) {
    const tr = painter.transform;
    if (tr.projection.name !== 'mercator') {
        warnOnce(`Drawing 3D models for ${ tr.projection.name } projection is not yet implemented`);
        return;
    }
    const mercCameraPos = tr.getFreeCameraOptions().position;
    if (!painter.modelManager)
        return;
    const modelManager = painter.modelManager;
    const shadowRenderer = painter.shadowRenderer;
    if (!layer._unevaluatedLayout._values.hasOwnProperty('model-id'))
        return;
    const modelIdUnevaluatedProperty = layer._unevaluatedLayout._values['model-id'];
    const evaluationParameters = { ...layer.layout.get('model-id').parameters };
    for (const coord of coords) {
        const tile = source.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket || bucket.projection.name !== tr.projection.name)
            continue;
        const tileZoom = calculateTileZoom(coord, tr);
        evaluationParameters.zoom = tileZoom;
        const modelIdProperty = modelIdUnevaluatedProperty.possiblyEvaluate(evaluationParameters);
        updateModelBucketData(painter, bucket, coord);
        renderData.shadowUniformsInitialized = false;
        renderData.useSingleShadowCascade = !!shadowRenderer && shadowRenderer.getMaxCascadeForTile(coord.toUnwrapped()) === 0;
        if (painter.renderPass === 'shadow' && shadowRenderer) {
            if (painter.currentShadowCascade === 1 && bucket.isInsideFirstShadowMapFrustum)
                continue;
            const tileMatrix = tr.calculatePosMatrix(coord.toUnwrapped(), tr.worldSize);
            renderData.tileMatrix.set(tileMatrix);
            renderData.shadowTileMatrix = Float32Array.from(shadowRenderer.calculateShadowPassMatrixFromMatrix(tileMatrix));
            renderData.aabb.min.fill(0);
            renderData.aabb.max[0] = renderData.aabb.max[1] = EXTENT;
            renderData.aabb.max[2] = 0;
            if (calculateTileShadowPassCulling(bucket, renderData, painter, layer.scope))
                continue;
        }
        // camera position in the tile coordinates
        const tiles = 1 << coord.canonical.z;
        const cameraPos = [
            ((mercCameraPos.x - coord.wrap) * tiles - coord.canonical.x) * EXTENT,
            (mercCameraPos.y * tiles - coord.canonical.y) * EXTENT,
            mercCameraPos.z * tiles * EXTENT
        ];
        for (let modelId in bucket.instancesPerModel) {
            // From effective tile zoom (distance to camera) and calculate model to use.
            const modelInstances = bucket.instancesPerModel[modelId];
            if (modelInstances.features.length > 0) {
                modelId = modelIdProperty.evaluate(modelInstances.features[0].feature, {});
            }
            const model = modelManager.getModel(modelId, layer.scope);
            if (!model || !model.uploaded)
                continue;
            for (const node of model.nodes) {
                drawInstancedNode(painter, layer, node, modelInstances, cameraPos, coord, renderData);
            }
        }
    }
}
const minimumInstanceCount = 20;
function drawInstancedNode(painter, layer, node, modelInstances, cameraPos, coord, renderData) {
    // console.log(`LAYER: ${JSON.stringify(layer.paint.get('model-scale'))}`);
    const context = painter.context;
    const isShadowPass = painter.renderPass === 'shadow';
    const shadowRenderer = painter.shadowRenderer;
    const depthMode = isShadowPass && shadowRenderer ? shadowRenderer.getShadowPassDepthMode() : new DepthMode(context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    const affectedByFog = painter.isTileAffectedByFog(coord);
    if (node.meshes) {
        for (const mesh of node.meshes) {
            const definesValues = ['MODEL_POSITION_ON_GPU'];
            const dynamicBuffers = [];
            let program;
            let uniformValues;
            let colorMode;
            if (modelInstances.instancedDataArray.length > minimumInstanceCount) {
                definesValues.push('INSTANCED_ARRAYS');
            }
            const cutoffParams = getCutoffParams(painter, layer.paint.get('model-cutoff-fade-range'));
            if (cutoffParams.shouldRenderCutoff) {
                definesValues.push('RENDER_CUTOFF');
            }
            if (isShadowPass && shadowRenderer) {
                program = painter.getOrCreateProgram('modelDepth', { defines: definesValues });
                uniformValues = modelDepthUniformValues(renderData.shadowTileMatrix, renderData.shadowTileMatrix, Float32Array.from(node.matrix));
                colorMode = shadowRenderer.getShadowPassColorMode();
            } else {
                setupMeshDraw(definesValues, dynamicBuffers, mesh, painter);
                program = painter.getOrCreateProgram('model', {
                    defines: definesValues,
                    overrideFog: affectedByFog
                });
                const material = mesh.material;
                const pbr = material.pbrMetallicRoughness;
                const layerOpacity = layer.paint.get('model-opacity');
                uniformValues = modelUniformValues(coord.projMatrix, Float32Array.from(node.matrix), new Float32Array(16), painter, layerOpacity, pbr.baseColorFactor, material.emissiveFactor, pbr.metallicFactor, pbr.roughnessFactor, material, layer, cameraPos);
                if (shadowRenderer) {
                    if (!renderData.shadowUniformsInitialized) {
                        shadowRenderer.setupShadows(coord.toUnwrapped(), program, 'model-tile', coord.overscaledZ);
                        renderData.shadowUniformsInitialized = true;
                    } else {
                        program.setShadowUniformValues(context, shadowRenderer.getShadowUniformValues());
                    }
                }
                const needsBlending = cutoffParams.shouldRenderCutoff || layerOpacity < 1 || material.alphaMode !== 'OPAQUE';
                colorMode = needsBlending ? ColorMode.alphaBlended : ColorMode.unblended;
            }
            painter.uploadCommonUniforms(context, program, coord.toUnwrapped(), null, cutoffParams);
            const cullFaceMode = mesh.material.doubleSided ? CullFaceMode.disabled : CullFaceMode.backCCW;
            if (modelInstances.instancedDataArray.length > minimumInstanceCount) {
                dynamicBuffers.push(modelInstances.instancedDataBuffer);
                program.draw(painter, context.gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, cullFaceMode, uniformValues, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments, layer.paint, painter.transform.zoom, undefined, dynamicBuffers, modelInstances.instancedDataArray.length);
            } else {
                const instanceUniform = isShadowPass ? 'u_instance' : 'u_normal_matrix';
                for (let i = 0; i < modelInstances.instancedDataArray.length; ++i) {
                    /* $FlowIgnore[prop-missing] modelDepth uses u_instance and model uses u_normal_matrix for packing instance data */
                    uniformValues[instanceUniform] = new Float32Array(modelInstances.instancedDataArray.arrayBuffer, i * 64, 16);
                    program.draw(painter, context.gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, cullFaceMode, uniformValues, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments, layer.paint, painter.transform.zoom, undefined, dynamicBuffers);
                }
            }
        }
    }
    if (node.children) {
        for (const child of node.children) {
            drawInstancedNode(painter, layer, child, modelInstances, cameraPos, coord, renderData);
        }
    }
}
const normalScale = [
    1,
    -1,
    1
];
function prepareBatched(painter, source, layer, coords) {
    const exaggeration = painter.terrain ? painter.terrain.exaggeration() : 0;
    const zoom = painter.transform.zoom;
    for (const coord of coords) {
        const tile = source.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        // Conflation
        if (painter.conflationActive)
            bucket.updateReplacement(coord, painter.replacementSource);
        // evaluate scale
        bucket.evaluateScale(painter, layer);
        // Compute elevation
        if (painter.terrain && exaggeration > 0) {
            bucket.elevationUpdate(painter.terrain, exaggeration, coord, layer.source);
        }
        if (bucket.needsReEvaluation(painter, zoom, layer)) {
            bucket.evaluate(layer);
        }
    }
}
function drawBatchedModels(painter, source, layer, coords) {
    const context = painter.context;
    const tr = painter.transform;
    const fog = painter.style.fog;
    const shadowRenderer = painter.shadowRenderer;
    if (tr.projection.name !== 'mercator') {
        warnOnce(`Drawing 3D landmark models for ${ tr.projection.name } projection is not yet implemented`);
        return;
    }
    const mercCameraPos = painter.transform.getFreeCameraOptions().position;
    const cameraPos = vec3_1.scale([], [
        mercCameraPos.x,
        mercCameraPos.y,
        mercCameraPos.z
    ], painter.transform.worldSize);
    vec3_1.negate(cameraPos, cameraPos);
    // compute model parameters matrices
    const negCameraPosMatrix = mat4_1.identity([]);
    const metersPerPixel = getMetersPerPixelAtLatitude(tr.center.lat, tr.zoom);
    const pixelsPerMeter = 1 / metersPerPixel;
    const zScaleMatrix = mat4_1.fromScaling([], [
        1,
        1,
        pixelsPerMeter
    ]);
    mat4_1.translate(negCameraPosMatrix, negCameraPosMatrix, cameraPos);
    const layerOpacity = layer.paint.get('model-opacity');
    const depthModeRW = new DepthMode(context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    const depthModeRO = new DepthMode(context.gl.LEQUAL, DepthMode.ReadOnly, painter.depthRangeFor3D);
    const drawTiles = function (enableColor, depthWrite) {
        for (const coord of coords) {
            const tile = source.getTile(coord);
            const bucket = tile.getBucket(layer);
            if (!bucket || !bucket.uploaded)
                continue;
            let singleCascade = false;
            if (shadowRenderer) {
                singleCascade = shadowRenderer.getMaxCascadeForTile(coord.toUnwrapped()) === 0;
            }
            const tileMatrix = tr.calculatePosMatrix(coord.toUnwrapped(), tr.worldSize);
            const modelTraits = bucket.modelTraits;
            for (const nodeInfo of bucket.getNodesInfo()) {
                if (nodeInfo.hiddenByReplacement)
                    continue;
                if (!nodeInfo.node.meshes)
                    continue;
                const node = nodeInfo.node;
                const isLightBeamPass = painter.renderPass === 'light-beam';
                const modelMatrix = [...tileMatrix];
                const scale = nodeInfo.evaluatedScale;
                let elevation = 0;
                if (painter.terrain && node.elevation) {
                    elevation = node.elevation * painter.terrain.exaggeration();
                }
                const anchorX = node.anchor ? node.anchor[0] : 0;
                const anchorY = node.anchor ? node.anchor[1] : 0;
                mat4_1.translate(modelMatrix, modelMatrix, [
                    anchorX * (scale[0] - 1),
                    anchorY * (scale[1] - 1),
                    elevation
                ]);
                if (scale !== DefaultModelScale) {
                    /* $FlowIgnore[incompatible-call] scale should always be an array */
                    mat4_1.scale(modelMatrix, modelMatrix, scale);
                }
                mat4_1.multiply(modelMatrix, modelMatrix, node.matrix);
                const lightingMatrix = mat4_1.multiply([], zScaleMatrix, modelMatrix);
                mat4_1.multiply(lightingMatrix, negCameraPosMatrix, lightingMatrix);
                const normalMatrix = mat4_1.invert([], lightingMatrix);
                mat4_1.transpose(normalMatrix, normalMatrix);
                mat4_1.scale(normalMatrix, normalMatrix, normalScale);
                const worldViewProjection = mat4_1.multiply([], tr.projMatrix, modelMatrix);
                for (let i = 0; i < node.meshes.length; ++i) {
                    const mesh = node.meshes[i];
                    const isLight = i === node.lightMeshIndex;
                    if (isLight) {
                        if (!isLightBeamPass && !painter.terrain && painter.shadowRenderer) {
                            if (painter.currentLayer < painter.firstLightBeamLayer) {
                                painter.firstLightBeamLayer = painter.currentLayer;
                            }
                            continue;
                        }
                    } else if (isLightBeamPass) {
                        continue;
                    }
                    const programOptions = { defines: [] };
                    const dynamicBuffers = [];
                    setupMeshDraw(programOptions.defines, dynamicBuffers, mesh, painter);
                    if (!(modelTraits & ModelTraits.HasMapboxMeshFeatures)) {
                        programOptions.defines.push('DIFFUSE_SHADED');
                    }
                    if (singleCascade) {
                        programOptions.defines.push('SHADOWS_SINGLE_CASCADE');
                    }
                    const isShadowPass = painter.renderPass === 'shadow';
                    if (isShadowPass) {
                        drawShadowCaster(mesh, modelMatrix, painter, layer);
                        continue;
                    }
                    let fogMatrixArray = null;
                    if (fog) {
                        const fogMatrix = fogMatrixForModel(modelMatrix, painter.transform);
                        fogMatrixArray = new Float32Array(fogMatrix);
                        if (tr.projection.name !== 'globe') {
                            const min = mesh.aabb.min;
                            const max = mesh.aabb.max;
                            const [minOpacity, maxOpacity] = fog.getOpacityForBounds(fogMatrix, min[0], min[1], max[0], max[1]);
                            programOptions.overrideFog = minOpacity >= FOG_OPACITY_THRESHOLD || maxOpacity >= FOG_OPACITY_THRESHOLD;
                        }
                    }
                    const program = painter.getOrCreateProgram('model', programOptions);
                    if (!isShadowPass && shadowRenderer) {
                        shadowRenderer.useNormalOffset = !!mesh.normalBuffer;
                        shadowRenderer.setupShadowsFromMatrix(modelMatrix, program, shadowRenderer.useNormalOffset);
                    }
                    painter.uploadCommonUniforms(context, program, coord.toUnwrapped(), fogMatrixArray);
                    const material = mesh.material;
                    const pbr = material.pbrMetallicRoughness;
                    // These values were taken from the tilesets used for testing
                    pbr.metallicFactor = 0.9;
                    pbr.roughnessFactor = 0.5;
                    const uniformValues = modelUniformValues(new Float32Array(worldViewProjection), new Float32Array(lightingMatrix), new Float32Array(normalMatrix), painter, layerOpacity, pbr.baseColorFactor, material.emissiveFactor, pbr.metallicFactor, pbr.roughnessFactor, material, layer);
                    const meshNeedsBlending = isLight || layerOpacity < 1 || nodeInfo.hasTranslucentParts;
                    const colorMode = enableColor ? meshNeedsBlending ? ColorMode.alphaBlended : ColorMode.unblended : ColorMode.disabled;
                    const depthMode = depthWrite && !isLight ? depthModeRW : depthModeRO;
                    program.draw(painter, context.gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments, layer.paint, painter.transform.zoom, undefined, dynamicBuffers);
                }
            }
        }
    };
    // Evaluate bucket and prepare for rendering
    prepareBatched(painter, source, layer, coords);
    if (layerOpacity === 1) {
        drawTiles(true, true);
    } else {
        // Draw transparent buildings in two passes so that only the closest surface is drawn.
        // First draw all the extrusions into only the depth buffer. No colors are drawn.
        // Then draw all the extrusions a second type, only coloring fragments if they have the
        // same depth value as the closest fragment in the previous pass. Use the stencil buffer
        // to prevent the second draw in cases where we have coincident polygons.
        drawTiles(false, true);
        drawTiles(true, false);
    }
}
function calculateTileShadowPassCulling(bucket, renderData, painter, scope) {
    if (!painter.modelManager)
        return true;
    const modelManager = painter.modelManager;
    if (!painter.shadowRenderer)
        return true;
    const shadowRenderer = painter.shadowRenderer;
    const aabb = renderData.aabb;
    let allModelsLoaded = true;
    let maxHeight = bucket.maxHeight;
    if (maxHeight === 0) {
        let maxDim = 0;
        for (const modelId in bucket.instancesPerModel) {
            const model = modelManager.getModel(modelId, scope);
            if (!model) {
                allModelsLoaded = false;
                continue;
            }
            maxDim = Math.max(maxDim, Math.max(Math.max(model.aabb.max[0], model.aabb.max[1]), model.aabb.max[2]));
        }
        maxHeight = bucket.maxScale * maxDim * 1.41 + bucket.maxVerticalOffset;
        if (allModelsLoaded)
            bucket.maxHeight = maxHeight;
    }
    aabb.max[2] = maxHeight;
    // Take into account bucket placement on DEM
    aabb.min[2] += bucket.terrainElevationMin;
    aabb.max[2] += bucket.terrainElevationMax;
    vec3_1.transformMat4(aabb.min, aabb.min, renderData.tileMatrix);
    vec3_1.transformMat4(aabb.max, aabb.max, renderData.tileMatrix);
    const intersection = aabb.intersects(shadowRenderer.getCurrentCascadeFrustum());
    if (painter.currentShadowCascade === 0) {
        bucket.isInsideFirstShadowMapFrustum = intersection === 2;
    }
    return intersection === 0;
}

//      
class CacheEntry {
}
const TimeoutFrames = 30;
class WireframeDebugCache {
    constructor() {
        this._storage = new Map();
    }
    getLinesFromTrianglesBuffer(frameIdx, indexBuffer, context) {
        {
            const entry = this._storage.get(indexBuffer.id);
            if (entry) {
                entry.lastUsedFrameIdx = frameIdx;
                return entry.buf;
            }
        }
        const gl = context.gl;
        const bufSize = gl.getBufferParameter(gl.ELEMENT_ARRAY_BUFFER, gl.BUFFER_SIZE);
        const bufTmp = new ArrayBuffer(bufSize);
        const intView = new Int16Array(bufTmp);
        gl.getBufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, new Int16Array(bufTmp));
        const lineIndexArray = new StructArrayLayout2ui4();
        for (let i = 0; i < bufSize / 2; i += 3) {
            const i0 = intView[i];
            const i1 = intView[i + 1];
            const i2 = intView[i + 2];
            lineIndexArray.emplaceBack(i0, i1);
            lineIndexArray.emplaceBack(i1, i2);
            lineIndexArray.emplaceBack(i2, i0);
        }
        // Save and restore current VAO since it is reset on IndexBuffer creation
        const previousBoundVAO = context.bindVertexArrayOES.current;
        const newEntry = new CacheEntry();
        newEntry.buf = new IndexBuffer(context, lineIndexArray);
        newEntry.lastUsedFrameIdx = frameIdx;
        this._storage.set(indexBuffer.id, newEntry);
        context.bindVertexArrayOES.set(previousBoundVAO);
        return newEntry.buf;
    }
    update(frameIdx) {
        for (const [key, obj] of this._storage) {
            if (frameIdx - obj.lastUsedFrameIdx > TimeoutFrames) {
                // Delete object from cache
                obj.buf.destroy();
                this._storage.delete(key);
            }
        }
    }
    destroy() {
        for (const [key, obj] of this._storage) {
            obj.buf.destroy();
            this._storage.delete(key);
        }
    }
}

//      
const draw = {
    symbol: drawSymbols,
    circle: drawCircles,
    heatmap: drawHeatmap,
    line: drawLine,
    fill: drawFill,
    'fill-extrusion': draw$1,
    hillshade: drawHillshade,
    raster: drawRaster,
    background: drawBackground,
    sky: drawSky,
    debug: drawDebug,
    custom: drawCustom,
    model: drawModels
};
const upload = { modelUpload: upload$1 };
/**
 * Initialize a new painter object.
 *
 * @param {Canvas} gl an experimental-webgl drawing context
 * @private
 */
class Painter {
    constructor(gl, transform) {
        this.context = new Context(gl);
        this.transform = transform;
        this._tileTextures = {};
        this.frameCopies = [];
        this.loadTimeStamps = [];
        this.setup();
        // Within each layer there are multiple distinct z-planes that can be drawn to.
        // This is implemented using the WebGL depth buffer.
        this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1;
        this.depthEpsilon = 1 / Math.pow(2, 16);
        this.deferredRenderGpuTimeQueries = [];
        this.gpuTimers = {};
        this.frameCounter = 0;
        this._backgroundTiles = {};
        this.conflationActive = false;
        this.replacementSource = new ReplacementSource();
        this.longestCutoffRange = 0;
        this.minCutoffZoom = 0;
        this._fogVisible = false;
        this._cachedTileFogOpacities = {};
        this._shadowRenderer = new ShadowRenderer(this);
        this._wireframeDebugCache = new WireframeDebugCache();
        this.renderDefaultNorthPole = true;
        this.renderDefaultSouthPole = true;
    }
    updateTerrain(style, adaptCameraAltitude) {
        const enabled = !!style && !!style.terrain && this.transform.projection.supportsTerrain;
        if (!enabled && (!this._terrain || !this._terrain.enabled))
            return;
        if (!this._terrain) {
            this._terrain = new Terrain(this, style);
        }
        const terrain = this._terrain;
        this.transform.elevation = enabled ? terrain : null;
        terrain.update(style, this.transform, adaptCameraAltitude);
        if (this.transform.elevation && !terrain.enabled) {
            // for zoom based exaggeration change, terrain.update can disable terrain.
            this.transform.elevation = null;
        }
    }
    _updateFog(style) {
        // Globe makes use of thin fog overlay with a fixed fog range,
        // so we can skip updating fog tile culling for this projection
        const isGlobe = this.transform.projection.name === 'globe';
        const fog = style.fog;
        if (!fog || isGlobe || fog.getOpacity(this.transform.pitch) < 1 || fog.properties.get('horizon-blend') < 0.03) {
            this.transform.fogCullDistSq = null;
            return;
        }
        // We start culling where the fog opacity function hits
        // 98% which leaves a non-noticeable change threshold.
        const [start, end] = fog.getFovAdjustedRange(this.transform._fov);
        if (start > end) {
            this.transform.fogCullDistSq = null;
            return;
        }
        const fogBoundFraction = 0.78;
        const fogCullDist = start + (end - start) * fogBoundFraction;
        this.transform.fogCullDistSq = fogCullDist * fogCullDist;
    }
    get terrain() {
        return this.transform._terrainEnabled() && this._terrain && this._terrain.enabled ? this._terrain : null;
    }
    get shadowRenderer() {
        return this._shadowRenderer && this._shadowRenderer.enabled ? this._shadowRenderer : null;
    }
    get wireframeDebugCache() {
        return this._wireframeDebugCache;
    }
    /*
     * Update the GL viewport, projection matrix, and transforms to compensate
     * for a new width and height value.
     */
    resize(width, height) {
        this.width = width * exported$1.devicePixelRatio;
        this.height = height * exported$1.devicePixelRatio;
        this.context.viewport.set([
            0,
            0,
            this.width,
            this.height
        ]);
        if (this.style) {
            for (const layerId of this.style.order) {
                this.style._mergedLayers[layerId].resize();
            }
        }
    }
    setup() {
        const context = this.context;
        const tileExtentArray = new StructArrayLayout2i4();
        tileExtentArray.emplaceBack(0, 0);
        tileExtentArray.emplaceBack(EXTENT, 0);
        tileExtentArray.emplaceBack(0, EXTENT);
        tileExtentArray.emplaceBack(EXTENT, EXTENT);
        this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);
        this.tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
        const debugArray = new StructArrayLayout2i4();
        debugArray.emplaceBack(0, 0);
        debugArray.emplaceBack(EXTENT, 0);
        debugArray.emplaceBack(0, EXTENT);
        debugArray.emplaceBack(EXTENT, EXTENT);
        this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);
        this.debugSegments = SegmentVector.simpleSegment(0, 0, 4, 5);
        const viewportArray = new StructArrayLayout2i4();
        viewportArray.emplaceBack(-1, -1);
        viewportArray.emplaceBack(1, -1);
        viewportArray.emplaceBack(-1, 1);
        viewportArray.emplaceBack(1, 1);
        this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members);
        this.viewportSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
        const tileBoundsArray = new StructArrayLayout4i8();
        tileBoundsArray.emplaceBack(0, 0, 0, 0);
        tileBoundsArray.emplaceBack(EXTENT, 0, EXTENT, 0);
        tileBoundsArray.emplaceBack(0, EXTENT, 0, EXTENT);
        tileBoundsArray.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT);
        this.mercatorBoundsBuffer = context.createVertexBuffer(tileBoundsArray, boundsAttributes.members);
        this.mercatorBoundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
        const quadTriangleIndices = new StructArrayLayout3ui6();
        quadTriangleIndices.emplaceBack(0, 1, 2);
        quadTriangleIndices.emplaceBack(2, 1, 3);
        this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);
        const tileLineStripIndices = new StructArrayLayout1ui2();
        for (const i of [
                0,
                1,
                3,
                2,
                0
            ])
            tileLineStripIndices.emplaceBack(i);
        this.debugIndexBuffer = context.createIndexBuffer(tileLineStripIndices);
        this.emptyTexture = new Texture(context, new RGBAImage({
            width: 1,
            height: 1
        }, Uint8Array.of(0, 0, 0, 0)), context.gl.RGBA);
        this.identityMat = mat4_1.create();
        const gl = this.context.gl;
        this.stencilClearMode = new StencilMode({
            func: gl.ALWAYS,
            mask: 0
        }, 0, 255, gl.ZERO, gl.ZERO, gl.ZERO);
        this.loadTimeStamps.push(window$1.performance.now());
    }
    getMercatorTileBoundsBuffers() {
        return {
            tileBoundsBuffer: this.mercatorBoundsBuffer,
            tileBoundsIndexBuffer: this.quadTriangleIndexBuffer,
            tileBoundsSegments: this.mercatorBoundsSegments
        };
    }
    getTileBoundsBuffers(tile) {
        tile._makeTileBoundsBuffers(this.context, this.transform.projection);
        if (tile._tileBoundsBuffer) {
            const tileBoundsBuffer = tile._tileBoundsBuffer;
            const tileBoundsIndexBuffer = tile._tileBoundsIndexBuffer;
            const tileBoundsSegments = tile._tileBoundsSegments;
            return {
                tileBoundsBuffer,
                tileBoundsIndexBuffer,
                tileBoundsSegments
            };
        } else {
            return this.getMercatorTileBoundsBuffers();
        }
    }
    /*
     * Reset the drawing canvas by clearing the stencil buffer so that we can draw
     * new tiles at the same location, while retaining previously drawn pixels.
     */
    clearStencil() {
        const context = this.context;
        const gl = context.gl;
        this.nextStencilID = 1;
        this.currentStencilSource = undefined;
        this._tileClippingMaskIDs = {};
        // As a temporary workaround for https://github.com/mapbox/mapbox-gl-js/issues/5490,
        // pending an upstream fix, we draw a fullscreen stencil=0 clipping mask here,
        // effectively clearing the stencil buffer: once an upstream patch lands, remove
        // this function in favor of context.clear({ stencil: 0x0 })
        this.getOrCreateProgram('clippingMask').draw(this, gl.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(this.identityMat), '$clipping', this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments);
    }
    resetStencilClippingMasks() {
        if (!this.terrain) {
            this.currentStencilSource = undefined;
            this._tileClippingMaskIDs = {};
        }
    }
    _renderTileClippingMasks(layer, sourceCache, tileIDs) {
        if (!sourceCache || this.currentStencilSource === sourceCache.id || !layer.isTileClipped() || !tileIDs || tileIDs.length === 0) {
            return;
        }
        if (this._tileClippingMaskIDs && !this.terrain) {
            let dirtyStencilClippingMasks = false;
            // Equivalent tile set is already rendered in stencil
            for (const coord of tileIDs) {
                if (this._tileClippingMaskIDs[coord.key] === undefined) {
                    dirtyStencilClippingMasks = true;
                    break;
                }
            }
            if (!dirtyStencilClippingMasks) {
                return;
            }
        }
        this.currentStencilSource = sourceCache.id;
        const context = this.context;
        const gl = context.gl;
        if (this.nextStencilID + tileIDs.length > 256) {
            // we'll run out of fresh IDs so we need to clear and start from scratch
            this.clearStencil();
        }
        context.setColorMode(ColorMode.disabled);
        context.setDepthMode(DepthMode.disabled);
        const program = this.getOrCreateProgram('clippingMask');
        this._tileClippingMaskIDs = {};
        for (const tileID of tileIDs) {
            const tile = sourceCache.getTile(tileID);
            const id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++;
            const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = this.getTileBoundsBuffers(tile);
            program.draw(this, gl.TRIANGLES, DepthMode.disabled, // Tests will always pass, and ref value will be written to stencil buffer.
            new StencilMode({
                func: gl.ALWAYS,
                mask: 0
            }, id, 255, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.projMatrix), '$clipping', tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
        }
    }
    stencilModeFor3D() {
        this.currentStencilSource = undefined;
        if (this.nextStencilID + 1 > 256) {
            this.clearStencil();
        }
        const id = this.nextStencilID++;
        const gl = this.context.gl;
        return new StencilMode({
            func: gl.NOTEQUAL,
            mask: 255
        }, id, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
    }
    stencilModeForClipping(tileID) {
        if (this.terrain)
            return this.terrain.stencilModeForRTTOverlap(tileID);
        const gl = this.context.gl;
        return new StencilMode({
            func: gl.EQUAL,
            mask: 255
        }, this._tileClippingMaskIDs[tileID.key], 0, gl.KEEP, gl.KEEP, gl.REPLACE);
    }
    /*
     * Sort coordinates by Z as drawing tiles is done in Z-descending order.
     * All children with the same Z write the same stencil value.  Children
     * stencil values are greater than parent's.  This is used only for raster
     * and raster-dem tiles, which are already clipped to tile boundaries, to
     * mask area of tile overlapped by children tiles.
     * Stencil ref values continue range used in _tileClippingMaskIDs.
     *
     * Returns [StencilMode for tile overscaleZ map, sortedCoords].
     */
    stencilConfigForOverlap(tileIDs) {
        const gl = this.context.gl;
        const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);
        const minTileZ = coords[coords.length - 1].overscaledZ;
        const stencilValues = coords[0].overscaledZ - minTileZ + 1;
        if (stencilValues > 1) {
            this.currentStencilSource = undefined;
            if (this.nextStencilID + stencilValues > 256) {
                this.clearStencil();
            }
            const zToStencilMode = {};
            for (let i = 0; i < stencilValues; i++) {
                zToStencilMode[i + minTileZ] = new StencilMode({
                    func: gl.GEQUAL,
                    mask: 255
                }, i + this.nextStencilID, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
            }
            this.nextStencilID += stencilValues;
            return [
                zToStencilMode,
                coords
            ];
        }
        return [
            { [minTileZ]: StencilMode.disabled },
            coords
        ];
    }
    colorModeForRenderPass() {
        const gl = this.context.gl;
        if (this._showOverdrawInspector) {
            const numOverdrawSteps = 8;
            const a = 1 / numOverdrawSteps;
            return new ColorMode([
                gl.CONSTANT_COLOR,
                gl.ONE,
                gl.CONSTANT_COLOR,
                gl.ONE
            ], new Color$1(a, a, a, 0), [
                true,
                true,
                true,
                true
            ]);
        } else if (this.renderPass === 'opaque') {
            return ColorMode.unblended;
        } else {
            return ColorMode.alphaBlended;
        }
    }
    colorModeForDrapableLayerRenderPass(emissiveStrengthForDrapedLayers) {
        const deferredDrapingEnabled = () => {
            return this.style && this.style.enable3dLights() && this.terrain && this.terrain.renderingToTexture;
        };
        const gl = this.context.gl;
        if (deferredDrapingEnabled() && this.renderPass === 'translucent') {
            return new ColorMode([
                gl.ONE,
                gl.ONE_MINUS_SRC_ALPHA,
                gl.CONSTANT_ALPHA,
                gl.ONE_MINUS_SRC_ALPHA
            ], new Color$1(0, 0, 0, emissiveStrengthForDrapedLayers === undefined ? 0 : emissiveStrengthForDrapedLayers), [
                true,
                true,
                true,
                true
            ]);
        } else {
            return this.colorModeForRenderPass();
        }
    }
    depthModeForSublayer(n, mask, func, skipOpaquePassCutoff = false) {
        if (!this.opaquePassEnabledForLayer() && !skipOpaquePassCutoff)
            return DepthMode.disabled;
        const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon;
        return new DepthMode(func || this.context.gl.LEQUAL, mask, [
            depth,
            depth
        ]);
    }
    /*
     * The opaque pass and 3D layers both use the depth buffer.
     * Layers drawn above 3D layers need to be drawn using the
     * painter's algorithm so that they appear above 3D features.
     * This returns true for layers that can be drawn using the
     * opaque pass.
     */
    opaquePassEnabledForLayer() {
        return this.currentLayer < this.opaquePassCutoff;
    }
    render(style, options) {
        // Update debug cache, i.e. clear all unused buffers
        this._wireframeDebugCache.update(this.frameCounter);
        this.style = style;
        this.options = options;
        const layers = this.style._mergedLayers;
        const layerIds = this.style.order;
        const orderedLayers = layerIds.map(id => layers[id]);
        const sourceCaches = this.style._mergedSourceCaches;
        this.imageManager = style.imageManager;
        this.modelManager = style.modelManager;
        this.symbolFadeChange = style.placement.symbolFadeChange(exported$1.now());
        this.imageManager.beginFrame();
        let conflationSourcesInStyle = 0;
        let conflationActiveThisFrame = false;
        for (const id in sourceCaches) {
            const sourceCache = sourceCaches[id];
            if (sourceCache.used) {
                sourceCache.prepare(this.context);
                if (sourceCache.getSource().usedInConflation) {
                    ++conflationSourcesInStyle;
                }
            }
        }
        const coordsAscending = {};
        const coordsDescending = {};
        const coordsDescendingSymbol = {};
        const coordsShadowCasters = {};
        const coordsSortedByDistance = {};
        for (const id in sourceCaches) {
            const sourceCache = sourceCaches[id];
            coordsAscending[id] = sourceCache.getVisibleCoordinates();
            coordsDescending[id] = coordsAscending[id].slice().reverse();
            coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse();
            coordsShadowCasters[id] = sourceCache.getShadowCasterCoordinates();
            coordsSortedByDistance[id] = sourceCache.sortCoordinatesByDistance(coordsAscending[id]);
        }
        const getLayerSource = layer => {
            const cache = this.style.getLayerSourceCache(layer);
            if (!cache || !cache.used) {
                return null;
            }
            return cache.getSource();
        };
        if (conflationSourcesInStyle) {
            const conflationLayersInStyle = [];
            for (const layer of orderedLayers) {
                if (this.layerUsedInConflation(layer, getLayerSource(layer))) {
                    conflationLayersInStyle.push(layer);
                }
            }
            // Check we have more than one conflation layer
            if (conflationLayersInStyle && conflationLayersInStyle.length > 1) {
                // Some layer types such as fill extrusions and models might have interdependencies
                // where certain features should be replaced by overlapping features from another layer with higher
                // precedence. A special data structure 'replacementSource' is used to compute regions
                // on visible tiles where potential overlap might occur between features of different layers.
                const conflationSources = [];
                for (const layer of conflationLayersInStyle) {
                    const sourceCache = this.style.getLayerSourceCache(layer);
                    if (!sourceCache || !sourceCache.used || !sourceCache.getSource().usedInConflation) {
                        continue;
                    }
                    conflationSources.push({
                        layer: layer.fqid,
                        cache: sourceCache
                    });
                }
                this.replacementSource.setSources(conflationSources);
                conflationActiveThisFrame = true;
            }
        }
        if (!conflationActiveThisFrame) {
            this.replacementSource.clear();
        }
        // Mark conflation as active for one frame after the deactivation to give
        // consumers of the feature an opportunity to clean up
        this.conflationActive = conflationActiveThisFrame;
        // Tiles on zoom level lower than the minCutoffZoom will be cut for layers with non-zero cutoffRange
        this.minCutoffZoom = 0;
        // The longest cutoff range will be used for cutting shadows if any layer has non-zero cutoffRange
        this.longestCutoffRange = 0;
        for (const layer of orderedLayers) {
            const cutoffRange = layer.cutoffRange();
            this.longestCutoffRange = Math.max(cutoffRange, this.longestCutoffRange);
            if (cutoffRange > 0) {
                const source = getLayerSource(layer);
                if (source) {
                    this.minCutoffZoom = Math.max(source.minzoom, this.minCutoffZoom);
                }
                if (layer.minzoom) {
                    this.minCutoffZoom = Math.max(layer.minzoom, this.minCutoffZoom);
                }
            }
        }
        this.opaquePassCutoff = Infinity;
        for (let i = 0; i < orderedLayers.length; i++) {
            const layer = orderedLayers[i];
            if (layer.is3D()) {
                this.opaquePassCutoff = i;
                break;
            }
        }
        // Disable fog for the frame if it doesn't contribute to the final output at all
        const fog = this.style && this.style.fog;
        if (fog) {
            this._fogVisible = fog.getOpacity(this.transform.pitch) !== 0;
            if (this._fogVisible && this.transform.projection.name !== 'globe') {
                this._fogVisible = fog.isVisibleOnFrustum(this.transform.cameraFrustum);
            }
        } else {
            this._fogVisible = false;
        }
        this._cachedTileFogOpacities = {};
        if (this.terrain) {
            this.terrain.updateTileBinding(coordsDescendingSymbol);
            // All render to texture is done in translucent pass to remove need
            // for depth buffer allocation per tile.
            this.opaquePassCutoff = 0;
        }
        const shadowRenderer = this._shadowRenderer;
        if (shadowRenderer) {
            shadowRenderer.updateShadowParameters(this.transform, this.style.directionalLight);
            for (const id in sourceCaches) {
                for (const coord of coordsAscending[id]) {
                    let tileHeight = {
                        min: 0,
                        max: 0
                    };
                    if (this.terrain) {
                        tileHeight = this.terrain.getMinMaxForTile(coord) || tileHeight;
                    }
                    // This doesn't consider any 3D layers to have height above the ground.
                    // It was decided to not compute the real tile height, because all the tiles would need to be
                    // seperately iterated before any rendering starts. The current code that calculates ShadowReceiver.lastCascade
                    // doesn't check the Z axis in shadow cascade space. That in combination with missing tile height could in theory
                    // lead to a situation where a tile is thought to fit in cascade 0, but actually extends into cascade 1.
                    // The proper fix would be to update ShadowReceiver.lastCascade calculation to consider shadow cascade bounds accurately.
                    shadowRenderer.addShadowReceiver(coord.toUnwrapped(), tileHeight.min, tileHeight.max);
                }
            }
        }
        if (this.transform.projection.name === 'globe' && !this.globeSharedBuffers) {
            this.globeSharedBuffers = new GlobeSharedBuffers(this.context);
        }
        // upload pass
        for (const layer of orderedLayers) {
            if (layer.isHidden(this.transform.zoom))
                continue;
            const sourceCache = style.getLayerSourceCache(layer);
            this.uploadLayer(this, layer, sourceCache);
        }
        if (this.style.fog && this.transform.projection.supportsFog) {
            if (!this._atmosphere) {
                this._atmosphere = new Atmosphere();
            }
            this._atmosphere.update(this);
        } else {
            if (this._atmosphere) {
                this._atmosphere.destroy();
                this._atmosphere = undefined;
            }
        }
        // Following line is billing related code. Do not change. See LICENSE.txt
        if (!isMapAuthenticated(this.context.gl))
            return;
        // Offscreen pass ===============================================
        // We first do all rendering that requires rendering to a separate
        // framebuffer, and then save those for rendering back to the map
        // later: in doing this we avoid doing expensive framebuffer restores.
        this.renderPass = 'offscreen';
        for (const layer of orderedLayers) {
            const sourceCache = style.getLayerSourceCache(layer);
            if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom))
                continue;
            const coords = sourceCache ? coordsDescending[sourceCache.id] : undefined;
            if (!(layer.type === 'custom' || layer.type === 'raster' || layer.isSky()) && !(coords && coords.length))
                continue;
            this.renderLayer(this, sourceCache, layer, coords);
        }
        this.depthRangeFor3D = [
            0,
            1 - (orderedLayers.length + 2) * this.numSublayers * this.depthEpsilon
        ];
        // Terrain depth offscreen render pass ==========================
        // With terrain on, renders the depth buffer into a texture.
        // This texture is used for occlusion testing (labels).
        // When orthographic camera is in use we don't really need the depth occlusion testing (see https://mapbox.atlassian.net/browse/MAPS3D-1132)
        // Therefore we can safely skip the rendering to the depth texture.
        const terrain = this.terrain;
        if (terrain && (this.style.hasSymbolLayers() || this.style.hasCircleLayers()) && !this.transform.isOrthographic) {
            terrain.drawDepth();
        }
        // Shadow pass ==================================================
        if (this._shadowRenderer) {
            this.renderPass = 'shadow';
            this._shadowRenderer.drawShadowPass(this.style, coordsShadowCasters);
        }
        // Rebind the main framebuffer now that all offscreen layers have been rendered:
        this.context.bindFramebuffer.set(null);
        this.context.viewport.set([
            0,
            0,
            this.width,
            this.height
        ]);
        const shouldRenderAtmosphere = this.transform.projection.name === 'globe' || this.transform.isHorizonVisible();
        // Clear buffers in preparation for drawing to the main framebuffer
        const clearColor = ((() => {
            if (options.showOverdrawInspector) {
                return Color$1.black;
            }
            if (this.style.fog && this.transform.projection.supportsFog && !shouldRenderAtmosphere) {
                const fogColor = this.style.fog.properties.get('color').toArray01();
                return new Color$1(...fogColor);
            }
            if (this.style.fog && this.transform.projection.supportsFog && shouldRenderAtmosphere) {
                const spaceColor = this.style.fog.properties.get('space-color').toArray01();
                return new Color$1(...spaceColor);
            }
            return Color$1.transparent;
        })());
        this.context.clear({
            color: clearColor,
            depth: 1
        });
        this.clearStencil();
        this._showOverdrawInspector = options.showOverdrawInspector;
        // Opaque pass ===============================================
        // Draw opaque layers top-to-bottom first.
        this.renderPass = 'opaque';
        if (this.style.fog && this.transform.projection.supportsFog && this._atmosphere && !this._showOverdrawInspector && shouldRenderAtmosphere) {
            this._atmosphere.drawStars(this, this.style.fog);
        }
        if (!this.terrain) {
            for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) {
                const layer = orderedLayers[this.currentLayer];
                const sourceCache = style.getLayerSourceCache(layer);
                if (layer.isSky())
                    continue;
                const coords = sourceCache ? (layer.is3D() ? coordsSortedByDistance : coordsDescending)[sourceCache.id] : undefined;
                this._renderTileClippingMasks(layer, sourceCache, coords);
                this.renderLayer(this, sourceCache, layer, coords);
            }
        }
        if (this.style.fog && this.transform.projection.supportsFog && this._atmosphere && !this._showOverdrawInspector && shouldRenderAtmosphere) {
            this._atmosphere.drawAtmosphereGlow(this, this.style.fog);
        }
        // Sky pass ======================================================
        // Draw all sky layers bottom to top.
        // They are drawn at max depth, they are drawn after opaque and before
        // translucent to fail depth testing and mix with translucent objects.
        this.renderPass = 'sky';
        const drawSkyOnGlobe = !this._atmosphere || globeToMercatorTransition(this.transform.zoom) > 0;
        if (drawSkyOnGlobe && (this.transform.projection.name === 'globe' || this.transform.isHorizonVisible())) {
            for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {
                const layer = orderedLayers[this.currentLayer];
                const sourceCache = style.getLayerSourceCache(layer);
                if (!layer.isSky())
                    continue;
                const coords = sourceCache ? coordsDescending[sourceCache.id] : undefined;
                this.renderLayer(this, sourceCache, layer, coords);
            }
        }
        // Translucent pass ===============================================
        // Draw all other layers bottom-to-top.
        this.renderPass = 'translucent';
        this.currentLayer = 0;
        this.firstLightBeamLayer = Number.MAX_SAFE_INTEGER;
        let shadowLayers = 0;
        if (shadowRenderer) {
            shadowLayers = shadowRenderer.getShadowCastingLayerCount();
        }
        while (this.currentLayer < layerIds.length) {
            const layer = orderedLayers[this.currentLayer];
            const sourceCache = style.getLayerSourceCache(layer);
            // Nothing to draw in translucent pass for sky layers, advance
            if (layer.isSky()) {
                ++this.currentLayer;
                continue;
            }
            // With terrain on and for draped layers only, issue rendering and progress
            // this.currentLayer until the next non-draped layer.
            // Otherwise we interleave terrain draped render with non-draped layers on top
            if (terrain && this.style.isLayerDraped(layer)) {
                if (layer.isHidden(this.transform.zoom)) {
                    ++this.currentLayer;
                    continue;
                }
                this.currentLayer;
                this.currentLayer = terrain.renderBatch(this.currentLayer);
                continue;
            }
            // For symbol layers in the translucent pass, we add extra tiles to the renderable set
            // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render
            // separate clipping masks
            let coords;
            if (sourceCache) {
                const coordsSet = layer.type === 'symbol' ? coordsDescendingSymbol : layer.is3D() ? coordsSortedByDistance : coordsDescending;
                coords = coordsSet[sourceCache.id];
            }
            this._renderTileClippingMasks(layer, sourceCache, sourceCache ? coordsAscending[sourceCache.id] : undefined);
            this.renderLayer(this, sourceCache, layer, coords);
            // Render ground shadows after the last shadow caster layer
            if (!terrain && shadowRenderer && shadowLayers > 0 && layer.hasShadowPass() && --shadowLayers === 0) {
                shadowRenderer.drawGroundShadows();
                if (this.firstLightBeamLayer <= this.currentLayer) {
                    // render light beams for 3D models (all are before ground shadows)
                    const saveCurrentLayer = this.currentLayer;
                    this.renderPass = 'light-beam';
                    for (this.currentLayer = this.firstLightBeamLayer; this.currentLayer <= saveCurrentLayer; this.currentLayer++) {
                        const layer = orderedLayers[this.currentLayer];
                        if (!layer.hasLightBeamPass())
                            continue;
                        const sourceCache = style.getLayerSourceCache(layer);
                        const coords = sourceCache ? coordsDescending[sourceCache.id] : undefined;
                        this.renderLayer(this, sourceCache, layer, coords);
                    }
                    this.currentLayer = saveCurrentLayer;
                    this.renderPass = 'translucent';
                }
            }
            ++this.currentLayer;
        }
        if (this.terrain) {
            this.terrain.postRender();
        }
        if (this.options.showTileBoundaries || this.options.showQueryGeometry || this.options.showTileAABBs) {
            //Use source with highest maxzoom
            let selectedSource = null;
            orderedLayers.forEach(layer => {
                const sourceCache = style.getLayerSourceCache(layer);
                if (sourceCache && !layer.isHidden(this.transform.zoom) && sourceCache.getVisibleCoordinates().length) {
                    if (!selectedSource || selectedSource.getSource().maxzoom < sourceCache.getSource().maxzoom) {
                        selectedSource = sourceCache;
                    }
                }
            });
            if (selectedSource) {
                if (this.options.showTileBoundaries) {
                    draw.debug(this, selectedSource, selectedSource.getVisibleCoordinates());
                }
            }
        }
        if (this.options.showPadding) {
            drawDebugPadding(this);
        }
        // Set defaults for most GL values so that anyone using the state after the render
        // encounters more expected values.
        this.context.setDefault();
        this.frameCounter = (this.frameCounter + 1) % Number.MAX_SAFE_INTEGER;
        if (this.tileLoaded && this.options.speedIndexTiming) {
            this.loadTimeStamps.push(window$1.performance.now());
            this.saveCanvasCopy();
        }
        if (!conflationActiveThisFrame) {
            this.conflationActive = false;
        }
    }
    uploadLayer(painter, layer, sourceCache) {
        this.gpuTimingStart(layer);
        if (!painter.transform.projection.unsupportedLayers || !painter.transform.projection.unsupportedLayers.includes(layer.type) || painter.terrain && layer.type === 'custom') {
            if (upload[`${ layer.type }Upload`]) {
                upload[`${ layer.type }Upload`](painter, sourceCache, layer.scope);
            }
        }
        this.gpuTimingEnd();
    }
    renderLayer(painter, sourceCache, layer, coords) {
        if (layer.isHidden(this.transform.zoom))
            return;
        if (layer.type !== 'background' && layer.type !== 'sky' && layer.type !== 'custom' && layer.type !== 'model' && layer.type !== 'raster' && !(coords && coords.length))
            return;
        this.id = layer.id;
        this.gpuTimingStart(layer);
        if (!painter.transform.projection.unsupportedLayers || !painter.transform.projection.unsupportedLayers.includes(layer.type) || painter.terrain && layer.type === 'custom') {
            draw[layer.type](painter, sourceCache, layer, coords, this.style.placement.variableOffsets, this.options.isInitialLoad);
        }
        this.gpuTimingEnd();
    }
    gpuTimingStart(layer) {
        if (!this.options.gpuTiming)
            return;
        const ext = this.context.extTimerQuery;
        const gl = this.context.gl;
        // This tries to time the draw call itself, but note that the cost for drawing a layer
        // may be dominated by the cost of uploading vertices to the GPU.
        // To instrument that, we'd need to pass the layerTimers object down into the bucket
        // uploading logic.
        let layerTimer = this.gpuTimers[layer.id];
        if (!layerTimer) {
            layerTimer = this.gpuTimers[layer.id] = {
                calls: 0,
                cpuTime: 0,
                query: gl.createQuery()
            };
        }
        layerTimer.calls++;
        gl.beginQuery(ext.TIME_ELAPSED_EXT, layerTimer.query);
    }
    gpuTimingDeferredRenderStart() {
        if (this.options.gpuTimingDeferredRender) {
            const ext = this.context.extTimerQuery;
            const gl = this.context.gl;
            const query = gl.createQuery();
            this.deferredRenderGpuTimeQueries.push(query);
            gl.beginQuery(ext.TIME_ELAPSED_EXT, query);
        }
    }
    gpuTimingDeferredRenderEnd() {
        if (!this.options.gpuTimingDeferredRender)
            return;
        const ext = this.context.extTimerQuery;
        const gl = this.context.gl;
        gl.endQuery(ext.TIME_ELAPSED_EXT);
    }
    gpuTimingEnd() {
        if (!this.options.gpuTiming)
            return;
        const ext = this.context.extTimerQuery;
        const gl = this.context.gl;
        gl.endQuery(ext.TIME_ELAPSED_EXT);
    }
    collectGpuTimers() {
        const currentLayerTimers = this.gpuTimers;
        this.gpuTimers = {};
        return currentLayerTimers;
    }
    collectDeferredRenderGpuQueries() {
        const currentQueries = this.deferredRenderGpuTimeQueries;
        this.deferredRenderGpuTimeQueries = [];
        return currentQueries;
    }
    queryGpuTimers(gpuTimers) {
        const layers = {};
        for (const layerId in gpuTimers) {
            const gpuTimer = gpuTimers[layerId];
            const ext = this.context.extTimerQuery;
            const gl = this.context.gl;
            const gpuTime = ext.getQueryParameter(gpuTimer.query, gl.QUERY_RESULT) / (1000 * 1000);
            ext.deleteQueryEXT(gpuTimer.query);
            layers[layerId] = gpuTime;
        }
        return layers;
    }
    queryGpuTimeDeferredRender(gpuQueries) {
        if (!this.options.gpuTimingDeferredRender)
            return 0;
        const ext = this.context.extTimerQuery;
        const gl = this.context.gl;
        let gpuTime = 0;
        for (const query of gpuQueries) {
            gpuTime += ext.getQueryParameter(query, gl.QUERY_RESULT) / (1000 * 1000);
            ext.deleteQueryEXT(query);
        }
        return gpuTime;
    }
    /**
     * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it.
     * @param inViewportPixelUnitsUnits True when the units accepted by the matrix are in viewport pixels instead of tile units.
     * @returns {Float32Array} matrix
     * @private
     */
    translatePosMatrix(matrix, tile, translate, translateAnchor, inViewportPixelUnitsUnits) {
        if (!translate[0] && !translate[1])
            return matrix;
        const angle = inViewportPixelUnitsUnits ? translateAnchor === 'map' ? this.transform.angle : 0 : translateAnchor === 'viewport' ? -this.transform.angle : 0;
        if (angle) {
            const sinA = Math.sin(angle);
            const cosA = Math.cos(angle);
            translate = [
                translate[0] * cosA - translate[1] * sinA,
                translate[0] * sinA + translate[1] * cosA
            ];
        }
        const translation = [
            inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom),
            inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom),
            0
        ];
        const translatedMatrix = new Float32Array(16);
        mat4_1.translate(translatedMatrix, matrix, translation);
        return translatedMatrix;
    }
    saveTileTexture(texture) {
        const textures = this._tileTextures[texture.size[0]];
        if (!textures) {
            this._tileTextures[texture.size[0]] = [texture];
        } else {
            textures.push(texture);
        }
    }
    getTileTexture(size) {
        const textures = this._tileTextures[size];
        return textures && textures.length > 0 ? textures.pop() : null;
    }
    /**
     * Checks whether a pattern image is needed, and if it is, whether it is not loaded.
     *
     * @returns true if a needed image is missing and rendering needs to be skipped.
     * @private
     */
    isPatternMissing(image, scope) {
        if (image === null)
            return true;
        if (image === undefined)
            return false;
        return !this.imageManager.getPattern(image.toString(), scope);
    }
    terrainRenderModeElevated() {
        // Whether elevation sampling should be enabled in the vertex shader.
        return this.style && !!this.style.getTerrain() && !!this.terrain && !this.terrain.renderingToTexture;
    }
    terrainUseFloatDEM() {
        const context = this.context;
        return context.extTextureFloatLinear != null;
    }
    /**
     * Returns #defines that would need to be injected into every Program
     * based on the current state of Painter.
     *
     * @returns {string[]}
     * @private
     */
    currentGlobalDefines(name, overrideFog, overrideRtt) {
        const rtt = overrideRtt === undefined ? this.terrain && this.terrain.renderingToTexture : overrideRtt;
        const zeroExaggeration = this.terrain && this.terrain.exaggeration() === 0;
        const defines = [];
        if (this.style && this.style.enable3dLights()) {
            // In case of terrain and map optimized for terrain mode flag
            // Lighting is deferred to terrain stage
            if (name === 'globeRaster' || name === 'terrainRaster') {
                defines.push('LIGHTING_3D_MODE');
                defines.push('LIGHTING_3D_ALPHA_EMISSIVENESS');
            } else {
                if (!rtt) {
                    defines.push('LIGHTING_3D_MODE');
                }
            }
        }
        if (this.renderPass === 'shadow') {
            if (!this._shadowMapDebug)
                defines.push('DEPTH_TEXTURE');
        } else if (this.shadowRenderer) {
            if (this.shadowRenderer.useNormalOffset) {
                defines.push('RENDER_SHADOWS', 'DEPTH_TEXTURE', 'NORMAL_OFFSET');
            } else {
                defines.push('RENDER_SHADOWS', 'DEPTH_TEXTURE');
            }
        }
        if (this.terrainRenderModeElevated()) {
            defines.push('TERRAIN');
            if (this.terrainUseFloatDEM())
                defines.push('TERRAIN_DEM_FLOAT_FORMAT');
            if (zeroExaggeration)
                defines.push('ZERO_EXAGGERATION');
        }
        if (this.transform.projection.name === 'globe')
            defines.push('GLOBE');
        // When terrain is active, fog is rendered as part of draping, not as part of tile
        // rendering. Removing the fog flag during tile rendering avoids additional defines.
        if (this._fogVisible && !rtt && (overrideFog === undefined || overrideFog)) {
            defines.push('FOG', 'FOG_DITHERING');
        }
        if (rtt)
            defines.push('RENDER_TO_TEXTURE');
        if (this._showOverdrawInspector)
            defines.push('OVERDRAW_INSPECTOR');
        return defines;
    }
    getOrCreateProgram(name, options) {
        this.cache = this.cache || {};
        const defines = options && options.defines || [];
        const config = options && options.config;
        const overrideFog = options && options.overrideFog;
        const overrideRtt = options && options.overrideRtt;
        const globalDefines = this.currentGlobalDefines(name, overrideFog, overrideRtt);
        const allDefines = globalDefines.concat(defines);
        const key = Program.cacheKey(shaders[name], name, allDefines, config);
        if (!this.cache[key]) {
            this.cache[key] = new Program(this.context, name, shaders[name], config, programUniforms[name], allDefines);
        }
        return this.cache[key];
    }
    /*
     * Reset some GL state to default values to avoid hard-to-debug bugs
     * in custom layers.
     */
    setCustomLayerDefaults() {
        // Prevent custom layers from unintentionally modify the last VAO used.
        // All other state is state is restored on it's own, but for VAOs it's
        // simpler to unbind so that we don't have to track the state of VAOs.
        this.context.unbindVAO();
        // The default values for this state is meaningful and often expected.
        // Leaving this state dirty could cause a lot of confusion for users.
        this.context.cullFace.setDefault();
        this.context.frontFace.setDefault();
        this.context.cullFaceSide.setDefault();
        this.context.activeTexture.setDefault();
        this.context.pixelStoreUnpack.setDefault();
        this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();
        this.context.pixelStoreUnpackFlipY.setDefault();
    }
    /*
     * Set GL state that is shared by all layers.
     */
    setBaseState() {
        const gl = this.context.gl;
        this.context.cullFace.set(false);
        this.context.viewport.set([
            0,
            0,
            this.width,
            this.height
        ]);
        this.context.blendEquation.set(gl.FUNC_ADD);
    }
    initDebugOverlayCanvas() {
        if (this.debugOverlayCanvas == null) {
            this.debugOverlayCanvas = window$1.document.createElement('canvas');
            this.debugOverlayCanvas.width = 512;
            this.debugOverlayCanvas.height = 512;
            const gl = this.context.gl;
            this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA);
        }
    }
    destroy() {
        if (this._terrain) {
            this._terrain.destroy();
        }
        if (this._atmosphere) {
            this._atmosphere.destroy();
            this._atmosphere = undefined;
        }
        if (this.globeSharedBuffers) {
            this.globeSharedBuffers.destroy();
        }
        this.emptyTexture.destroy();
        if (this.debugOverlayTexture) {
            this.debugOverlayTexture.destroy();
        }
        this._wireframeDebugCache.destroy();
    }
    prepareDrawTile() {
        if (this.terrain) {
            this.terrain.prepareDrawTile();
        }
    }
    uploadCommonLightUniforms(context, program) {
        if (this.style.enable3dLights()) {
            const directionalLight = this.style.directionalLight;
            const ambientLight = this.style.ambientLight;
            if (directionalLight && ambientLight) {
                const lightsUniforms = lightsUniformValues(directionalLight, ambientLight);
                program.setLightsUniformValues(context, lightsUniforms);
            }
        }
    }
    uploadCommonUniforms(context, program, tileID, fogMatrix, cutoffParams) {
        this.uploadCommonLightUniforms(context, program);
        // Fog is not enabled when rendering to texture so we
        // can safely skip uploading uniforms in that case
        if (this.terrain && this.terrain.renderingToTexture) {
            return;
        }
        const fog = this.style.fog;
        if (fog) {
            const fogOpacity = fog.getOpacity(this.transform.pitch);
            const fogUniforms = fogUniformValues(this, fog, tileID, fogOpacity, this.transform.frustumCorners.TL, this.transform.frustumCorners.TR, this.transform.frustumCorners.BR, this.transform.frustumCorners.BL, this.transform.globeCenterInViewSpace, this.transform.globeRadius, [
                this.transform.width * exported$1.devicePixelRatio,
                this.transform.height * exported$1.devicePixelRatio
            ], fogMatrix);
            program.setFogUniformValues(context, fogUniforms);
        }
        if (cutoffParams) {
            program.setCutoffUniformValues(context, cutoffParams.uniformValues);
        }
    }
    setTileLoadedFlag(flag) {
        this.tileLoaded = flag;
    }
    saveCanvasCopy() {
        const canvas = this.canvasCopy();
        if (!canvas)
            return;
        this.frameCopies.push(canvas);
        this.tileLoaded = false;
    }
    canvasCopy() {
        const gl = this.context.gl;
        const texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, 0);
        return texture;
    }
    getCanvasCopiesAndTimestamps() {
        return {
            canvasCopies: this.frameCopies,
            timeStamps: this.loadTimeStamps
        };
    }
    averageElevationNeedsEasing() {
        if (!this.transform._elevation)
            return false;
        const fog = this.style && this.style.fog;
        if (!fog)
            return false;
        const fogOpacity = fog.getOpacity(this.transform.pitch);
        if (fogOpacity === 0)
            return false;
        return true;
    }
    getBackgroundTiles() {
        const oldTiles = this._backgroundTiles;
        const newTiles = this._backgroundTiles = {};
        const tileSize = 512;
        const tileIDs = this.transform.coveringTiles({ tileSize });
        for (const tileID of tileIDs) {
            newTiles[tileID.key] = oldTiles[tileID.key] || new Tile(tileID, tileSize, this.transform.tileZoom, this);
        }
        return newTiles;
    }
    clearBackgroundTiles() {
        this._backgroundTiles = {};
    }
    /*
     * Replacement source's features get precedence over features defined in other sources.
     * E.g. landmark features replace fill extrusion buildings at the same position.
     * Initially planned to be used for Tiled3DModelSource, 2D source that is used with ModelLayer of buildings type and
     * custom layer buildings.
     */
    layerUsedInConflation(layer, source) {
        if (!layer.is3D()) {
            return false;
        }
        if (layer.minzoom && layer.minzoom > this.transform.zoom) {
            return false;
        }
        if (layer.sourceLayer === 'building') {
            return true;
        }
        return !!source && source.type === 'batched-model';
    }
    isTileAffectedByFog(id) {
        if (!this.style || !this.style.fog)
            return false;
        if (this.transform.projection.name === 'globe')
            return true;
        let cachedRange = this._cachedTileFogOpacities[id.key];
        if (!cachedRange) {
            this._cachedTileFogOpacities[id.key] = cachedRange = this.style.fog.getOpacityForTile(id);
        }
        return cachedRange[0] >= FOG_OPACITY_THRESHOLD || cachedRange[1] >= FOG_OPACITY_THRESHOLD;
    }
}

//      
// Describes simplified shadow volume of a tile. Consists of eight corner
// points of the aabb (possibly transformed) and four side planes. Top and bottom
// planes are left out as they rarely contribute visibility.
const cascadeCount = 2;
const shadowMapResolution = 2048;
class ShadowReceiver {
    constructor(aabb, lastCascade) {
        this.aabb = aabb;
        this.lastCascade = lastCascade;
    }
}
class ShadowReceivers {
    add(tileId, aabb) {
        const receiver = this.receivers[tileId.key];
        if (receiver !== undefined) {
            receiver.aabb.min[0] = Math.min(receiver.aabb.min[0], aabb.min[0]);
            receiver.aabb.min[1] = Math.min(receiver.aabb.min[1], aabb.min[1]);
            receiver.aabb.min[2] = Math.min(receiver.aabb.min[2], aabb.min[2]);
            receiver.aabb.max[0] = Math.max(receiver.aabb.max[0], aabb.max[0]);
            receiver.aabb.max[1] = Math.max(receiver.aabb.max[1], aabb.max[1]);
            receiver.aabb.max[2] = Math.max(receiver.aabb.max[2], aabb.max[2]);
        } else {
            this.receivers[tileId.key] = new ShadowReceiver(aabb, null);
        }
    }
    clear() {
        this.receivers = {};
    }
    get(tileId) {
        return this.receivers[tileId.key];
    }
    // Returns the number of cascades that need to be rendered based on visibility on screen.
    // Cascades that need to be rendered always include the first cascade.
    computeRequiredCascades(frustum, worldSize, cascades) {
        const frustumAabb = Aabb.fromPoints(frustum.points);
        let lastCascade = 0;
        for (const receiverKey in this.receivers) {
            const receiver = this.receivers[receiverKey];
            if (!receiver)
                continue;
            if (!frustumAabb.intersectsAabb(receiver.aabb))
                continue;
            receiver.aabb.min = frustumAabb.closestPoint(receiver.aabb.min);
            receiver.aabb.max = frustumAabb.closestPoint(receiver.aabb.max);
            const clampedTileAabbPoints = receiver.aabb.getCorners();
            for (let i = 0; i < cascades.length; i++) {
                let aabbInsideCascade = true;
                for (const point of clampedTileAabbPoints) {
                    const p = [
                        point[0] * worldSize,
                        point[1] * worldSize,
                        point[2]
                    ];
                    vec3_1.transformMat4(p, p, cascades[i].matrix);
                    if (p[0] < -1 || p[0] > 1 || p[1] < -1 || p[1] > 1) {
                        aabbInsideCascade = false;
                        break;
                    }
                }
                receiver.lastCascade = i;
                lastCascade = Math.max(lastCascade, i);
                if (aabbInsideCascade) {
                    break;
                }
            }
        }
        return lastCascade + 1;
    }
}
class ShadowRenderer {
    constructor(painter) {
        this.painter = painter;
        this._enabled = false;
        this._shadowLayerCount = 0;
        this._numCascadesToRender = 0;
        this._cascades = [];
        this._groundShadowTiles = [];
        this._receivers = new ShadowReceivers();
        this._depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, [
            0,
            1
        ]);
        this._uniformValues = defaultShadowUniformValues();
        this.useNormalOffset = false;
    }
    destroy() {
        for (const cascade of this._cascades) {
            cascade.texture.destroy();
            cascade.framebuffer.destroy();
        }
        this._cascades = [];
    }
    updateShadowParameters(transform, directionalLight) {
        const painter = this.painter;
        this._enabled = false;
        this._shadowLayerCount = 0;
        this._receivers.clear();
        if (!directionalLight || !directionalLight.properties) {
            return;
        }
        const shadowIntensity = directionalLight.properties.get('shadow-intensity');
        if (!directionalLight.shadowsEnabled() || shadowIntensity <= 0) {
            return;
        }
        this._shadowLayerCount = painter.style.order.reduce((accumulator, layerId) => {
            const layer = painter.style._mergedLayers[layerId];
            return accumulator + (layer.hasShadowPass() && !layer.isHidden(transform.zoom) ? 1 : 0);
        }, 0);
        this._enabled = this._shadowLayerCount > 0;
        if (!this._enabled) {
            return;
        }
        const context = painter.context;
        const width = shadowMapResolution;
        const height = shadowMapResolution;
        if (this._cascades.length === 0) {
            for (let i = 0; i < cascadeCount; ++i) {
                const useColor = painter._shadowMapDebug;
                const gl = context.gl;
                const fbo = context.createFramebuffer(width, height, useColor, 'texture');
                const depthTexture = new Texture(context, {
                    width,
                    height,
                    data: null
                }, gl.DEPTH_COMPONENT);
                fbo.depthAttachment.set(depthTexture.texture);
                if (useColor) {
                    const colorTexture = new Texture(context, {
                        width,
                        height,
                        data: null
                    }, gl.RGBA);
                    fbo.colorAttachment.set(colorTexture.texture);
                }
                this._cascades.push({
                    framebuffer: fbo,
                    texture: depthTexture,
                    matrix: [],
                    far: 0,
                    boundingSphereRadius: 0,
                    frustum: new Frustum(),
                    scale: 0
                });
            }
        }
        this.shadowDirection = shadowDirectionFromProperties(directionalLight);
        let verticalRange = 0;
        if (transform.elevation) {
            const elevation = transform.elevation;
            const range = [
                10000,
                -10000
            ];
            elevation.visibleDemTiles.filter(tile => tile.dem).forEach(tile => {
                const minMaxTree = tile.dem.tree;
                range[0] = Math.min(range[0], minMaxTree.minimums[0]);
                range[1] = Math.max(range[1], minMaxTree.maximums[0]);
            });
            if (range[0] !== 10000) {
                verticalRange = (range[1] - range[0]) * elevation.exaggeration();
            }
        }
        const cascadeSplitDist = transform.cameraToCenterDistance * 1.5;
        const shadowCutoutDist = cascadeSplitDist * 3;
        const cameraInvProj = new Float64Array(16);
        for (let cascadeIndex = 0; cascadeIndex < cascadeCount; ++cascadeIndex) {
            const cascade = this._cascades[cascadeIndex];
            let near = transform.height / 50;
            let far = 1;
            {
                if (cascadeIndex === 0) {
                    far = cascadeSplitDist;
                } else {
                    near = cascadeSplitDist;
                    far = shadowCutoutDist;
                }
            }
            const [matrix, radius] = createLightMatrix(transform, this.shadowDirection, near, far, shadowMapResolution, verticalRange);
            cascade.scale = transform.scale;
            cascade.matrix = matrix;
            cascade.boundingSphereRadius = radius;
            mat4_1.invert(cameraInvProj, cascade.matrix);
            cascade.frustum = Frustum.fromInvProjectionMatrix(cameraInvProj, 1, 0, true);
            cascade.far = far;
        }
        this._uniformValues['u_fade_range'] = [
            this._cascades[1].far * 0.75,
            this._cascades[1].far
        ];
        this._uniformValues['u_shadow_intensity'] = shadowIntensity;
        this._uniformValues['u_shadow_direction'] = [
            this.shadowDirection[0],
            this.shadowDirection[1],
            this.shadowDirection[2]
        ];
        this._uniformValues['u_shadow_texel_size'] = 1 / shadowMapResolution;
        this._uniformValues['u_shadow_map_resolution'] = shadowMapResolution;
        this._uniformValues['u_shadowmap_0'] = TextureSlots.ShadowMap0;
        this._uniformValues['u_shadowmap_1'] = TextureSlots.ShadowMap0 + 1;
        // Render shadows on the ground plane as an extra layer of blended "tiles"
        const tileCoverOptions = {
            tileSize: 512,
            renderWorldCopies: true
        };
        this._groundShadowTiles = painter.transform.coveringTiles(tileCoverOptions);
        const elevation = painter.transform.elevation;
        for (const tileId of this._groundShadowTiles) {
            let tileHeight = {
                min: 0,
                max: 0
            };
            if (elevation) {
                const minMax = elevation.getMinMaxForTile(tileId);
                if (minMax)
                    tileHeight = minMax;
            }
            this.addShadowReceiver(tileId.toUnwrapped(), tileHeight.min, tileHeight.max);
        }
    }
    get enabled() {
        return this._enabled;
    }
    set enabled(enabled) {
        // called on layer rendering to disable shadow receiving.
        this._enabled = enabled;
    }
    drawShadowPass(style, sourceCoords) {
        if (!this._enabled) {
            return;
        }
        const painter = this.painter;
        const context = painter.context;
        // For each shadow receiver, compute how many cascades would need to be
        // sampled for the VISIBLE part of the receiver to be fully covered by
        // shadows.
        this._numCascadesToRender = this._receivers.computeRequiredCascades(painter.transform.getFrustum(0), painter.transform.worldSize, this._cascades);
        context.viewport.set([
            0,
            0,
            shadowMapResolution,
            shadowMapResolution
        ]);
        for (let cascade = 0; cascade < this._numCascadesToRender; ++cascade) {
            painter.currentShadowCascade = cascade;
            context.bindFramebuffer.set(this._cascades[cascade].framebuffer.framebuffer);
            context.clear({
                color: Color$1.white,
                depth: 1
            });
            for (const layerId of style.order) {
                const layer = style._mergedLayers[layerId];
                if (!layer.hasShadowPass() || layer.isHidden(painter.transform.zoom))
                    continue;
                const sourceCache = style.getLayerSourceCache(layer);
                const coords = sourceCache ? sourceCoords[sourceCache.id] : undefined;
                if (layer.type !== 'model' && !(coords && coords.length))
                    continue;
                painter.renderLayer(painter, sourceCache, layer, coords);
            }
        }
        painter.currentShadowCascade = 0;
    }
    drawGroundShadows() {
        if (!this._enabled) {
            return;
        }
        const painter = this.painter;
        const style = painter.style;
        const context = painter.context;
        const directionalLight = style.directionalLight;
        const ambientLight = style.ambientLight;
        if (!directionalLight || !ambientLight) {
            return;
        }
        const baseDefines = [];
        const cutoffParams = getCutoffParams(painter, painter.longestCutoffRange);
        if (cutoffParams.shouldRenderCutoff) {
            baseDefines.push('RENDER_CUTOFF');
        }
        const shadowColor = calculateGroundShadowFactor(directionalLight, ambientLight);
        const depthMode = new DepthMode(context.gl.LEQUAL, DepthMode.ReadOnly, painter.depthRangeFor3D);
        for (const id of this._groundShadowTiles) {
            const unwrapped = id.toUnwrapped();
            const affectedByFog = painter.isTileAffectedByFog(id);
            const program = painter.getOrCreateProgram('groundShadow', {
                defines: baseDefines,
                overrideFog: affectedByFog
            });
            this.setupShadows(unwrapped, program);
            painter.uploadCommonUniforms(context, program, unwrapped, null, cutoffParams);
            const uniformValues = groundShadowUniformValues(painter.transform.calculateProjMatrix(unwrapped), shadowColor);
            program.draw(painter, context.gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.multiply, CullFaceMode.disabled, uniformValues, 'ground_shadow', painter.tileExtentBuffer, painter.quadTriangleIndexBuffer, painter.tileExtentSegments, {}, painter.transform.zoom, null, null);
        }
    }
    getShadowPassColorMode() {
        return this.painter._shadowMapDebug ? ColorMode.unblended : ColorMode.disabled;
    }
    getShadowPassDepthMode() {
        return this._depthMode;
    }
    getShadowCastingLayerCount() {
        return this._shadowLayerCount;
    }
    calculateShadowPassMatrixFromTile(unwrappedId) {
        const tr = this.painter.transform;
        const tileMatrix = tr.calculatePosMatrix(unwrappedId, tr.worldSize);
        const lightMatrix = this._cascades[this.painter.currentShadowCascade].matrix;
        mat4_1.multiply(tileMatrix, lightMatrix, tileMatrix);
        return Float32Array.from(tileMatrix);
    }
    calculateShadowPassMatrixFromMatrix(matrix) {
        const lightMatrix = this._cascades[this.painter.currentShadowCascade].matrix;
        mat4_1.multiply(matrix, lightMatrix, matrix);
        return Float32Array.from(matrix);
    }
    setupShadows(unwrappedTileID, program, normalOffsetMode, tileOverscaledZ = 0) {
        if (!this._enabled) {
            return;
        }
        const transform = this.painter.transform;
        const context = this.painter.context;
        const gl = context.gl;
        const uniforms = this._uniformValues;
        const lightMatrix = new Float64Array(16);
        const tileMatrix = transform.calculatePosMatrix(unwrappedTileID, transform.worldSize);
        for (let i = 0; i < cascadeCount; i++) {
            mat4_1.multiply(lightMatrix, this._cascades[i].matrix, tileMatrix);
            uniforms[i === 0 ? 'u_light_matrix_0' : 'u_light_matrix_1'] = Float32Array.from(lightMatrix);
            context.activeTexture.set(gl.TEXTURE0 + TextureSlots.ShadowMap0 + i);
            this._cascades[i].texture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
        }
        this.useNormalOffset = !!normalOffsetMode;
        if (this.useNormalOffset) {
            const meterInTiles = tileToMeter(unwrappedTileID.canonical);
            const texelScale = 2 / transform.tileSize * EXTENT / shadowMapResolution;
            const shadowTexelInTileCoords0 = texelScale * this._cascades[0].boundingSphereRadius;
            const shadowTexelInTileCoords1 = texelScale * this._cascades[1].boundingSphereRadius;
            // Instanced model tiles could have smoothened (shared among neighbor faces) normals. Normal is not surface normal
            // and this is why it is needed to increase the offset. 3.0 in case of model-tile could be alternatively replaced by
            // 2.0 if normal would not get scaled by dotScale in shadow_normal_offset().
            const tileTypeMultiplier = normalOffsetMode === 'vector-tile' ? 1 : 3;
            const scale = tileTypeMultiplier / Math.pow(2, tileOverscaledZ - unwrappedTileID.canonical.z - (1 - transform.zoom + Math.floor(transform.zoom)));
            const offset0 = shadowTexelInTileCoords0 * scale;
            const offset1 = shadowTexelInTileCoords1 * scale;
            uniforms['u_shadow_normal_offset'] = [
                meterInTiles,
                offset0,
                offset1
            ];
            uniforms['u_shadow_bias'] = [
                0.00006,
                0.0012,
                0.012
            ];    // Reduce constant offset
        } else {
            uniforms['u_shadow_bias'] = [
                0.00036,
                0.0012,
                0.012
            ];
        }
        program.setShadowUniformValues(context, uniforms);
    }
    setupShadowsFromMatrix(worldMatrix, program, normalOffset = false) {
        if (!this._enabled) {
            return;
        }
        const context = this.painter.context;
        const gl = context.gl;
        const uniforms = this._uniformValues;
        const lightMatrix = new Float64Array(16);
        for (let i = 0; i < cascadeCount; i++) {
            mat4_1.multiply(lightMatrix, this._cascades[i].matrix, worldMatrix);
            uniforms[i === 0 ? 'u_light_matrix_0' : 'u_light_matrix_1'] = Float32Array.from(lightMatrix);
            context.activeTexture.set(gl.TEXTURE0 + TextureSlots.ShadowMap0 + i);
            this._cascades[i].texture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
        }
        this.useNormalOffset = normalOffset;
        if (normalOffset) {
            const scale = 5;
            // Experimentally found value
            uniforms['u_shadow_normal_offset'] = [
                1,
                scale,
                scale
            ];
            // meterToTile isn't used
            uniforms['u_shadow_bias'] = [
                0.00006,
                0.0012,
                0.012
            ];    // Reduce constant offset
        } else {
            uniforms['u_shadow_bias'] = [
                0.00036,
                0.0012,
                0.012
            ];
        }
        program.setShadowUniformValues(context, uniforms);
    }
    // When the same uniform values are used multiple times on different programs, it is sufficient
    // to call program.setShadowUniformValues(context, uniforms) instead of calling setupShadowsFromMatrix multiple times.
    getShadowUniformValues() {
        return this._uniformValues;
    }
    getCurrentCascadeFrustum() {
        return this._cascades[this.painter.currentShadowCascade].frustum;
    }
    computeSimplifiedTileShadowVolume(id, height, worldSize, lightDir) {
        if (lightDir[2] >= 0) {
            return {};
        }
        const corners = tileAabb(id, height, worldSize).getCorners();
        const t = height / -lightDir[2];
        // Project vertices of bottom edges belonging to sides facing away from the light.
        if (lightDir[0] < 0) {
            vec3_1.add(corners[0], corners[0], [
                lightDir[0] * t,
                0,
                0
            ]);
            vec3_1.add(corners[3], corners[3], [
                lightDir[0] * t,
                0,
                0
            ]);
        } else if (lightDir[0] > 0) {
            vec3_1.add(corners[1], corners[1], [
                lightDir[0] * t,
                0,
                0
            ]);
            vec3_1.add(corners[2], corners[2], [
                lightDir[0] * t,
                0,
                0
            ]);
        }
        if (lightDir[1] < 0) {
            vec3_1.add(corners[0], corners[0], [
                0,
                lightDir[1] * t,
                0
            ]);
            vec3_1.add(corners[1], corners[1], [
                0,
                lightDir[1] * t,
                0
            ]);
        } else if (lightDir[1] > 0) {
            vec3_1.add(corners[2], corners[2], [
                0,
                lightDir[1] * t,
                0
            ]);
            vec3_1.add(corners[3], corners[3], [
                0,
                lightDir[1] * t,
                0
            ]);
        }
        const tileShadowVolume = {};
        /* $FlowIgnore[invalid-tuple-arity] we know corners have the same length than vertices */
        tileShadowVolume.vertices = corners;
        tileShadowVolume.planes = [
            computePlane(corners[1], corners[0], corners[4]),
            // top
            computePlane(corners[2], corners[1], corners[5]),
            // right
            computePlane(corners[3], corners[2], corners[6]),
            // bottom
            computePlane(corners[0], corners[3], corners[7])
        ];
        return tileShadowVolume;
    }
    addShadowReceiver(tileId, minHeight, maxHeight) {
        this._receivers.add(tileId, Aabb.fromTileIdAndHeight(tileId, minHeight, maxHeight));
    }
    getMaxCascadeForTile(tileId) {
        const receiver = this._receivers.get(tileId);
        return !!receiver && !!receiver.lastCascade ? receiver.lastCascade : 0;
    }
}
function tileAabb(id, height, worldSize) {
    const tileToWorld = worldSize / (1 << id.canonical.z);
    const minx = id.canonical.x * tileToWorld + id.wrap * worldSize;
    const maxx = (id.canonical.x + 1) * tileToWorld + id.wrap * worldSize;
    const miny = id.canonical.y * tileToWorld + id.wrap * worldSize;
    const maxy = (id.canonical.y + 1) * tileToWorld + id.wrap * worldSize;
    return new Aabb([
        minx,
        miny,
        0
    ], [
        maxx,
        maxy,
        height
    ]);
}
function computePlane(a, b, c) {
    const bc = vec3_1.sub([], c, b);
    const ba = vec3_1.sub([], a, b);
    const normal = vec3_1.cross([], bc, ba);
    const len = vec3_1.length(normal);
    if (len === 0) {
        return [
            0,
            0,
            1,
            0
        ];
    }
    vec3_1.scale(normal, normal, 1 / len);
    return [
        normal[0],
        normal[1],
        normal[2],
        -vec3_1.dot(normal, b)
    ];
}
function shadowDirectionFromProperties(directionalLight) {
    const direction = directionalLight.properties.get('direction');
    const spherical = cartesianPositionToSpherical(direction.x, direction.y, direction.z);
    // Limit light position specifically for shadow rendering.
    // If the polar coordinate goes very high, we get visual artifacts.
    // We limit the position in order to avoid these issues.
    // 75 degrees is an arbitrarily chosen value, based on a subjective assessment of the visuals.
    const MaxPolarCoordinate = 75;
    spherical[2] = clamp(spherical[2], 0, MaxPolarCoordinate);
    const position = sphericalPositionToCartesian([
        spherical[0],
        spherical[1],
        spherical[2]
    ]);
    // Convert polar and azimuthal to cartesian
    return vec3_1.fromValues(position.x, position.y, position.z);
}
function calculateGroundShadowFactor(directionalLight, ambientLight) {
    const dirColor = directionalLight.properties.get('color');
    const dirIntensity = directionalLight.properties.get('intensity');
    const dirDirection = directionalLight.properties.get('direction');
    const directionVec = [
        dirDirection.x,
        dirDirection.y,
        dirDirection.z
    ];
    const ambientColor = ambientLight.properties.get('color');
    const ambientIntensity = ambientLight.properties.get('intensity');
    const groundNormal = [
        0,
        0,
        1
    ];
    const dirDirectionalFactor = Math.max(vec3_1.dot(groundNormal, directionVec), 0);
    const ambStrength = [
        0,
        0,
        0
    ];
    vec3_1.scale(ambStrength, ambientColor.toArray01Linear().slice(0, 3), ambientIntensity);
    const dirStrength = [
        0,
        0,
        0
    ];
    vec3_1.scale(dirStrength, dirColor.toArray01Linear().slice(0, 3), dirDirectionalFactor * dirIntensity);
    // Multiplier X to get from lit surface color L to shadowed surface color S
    // X = A / (A + D)
    // A: Ambient light coming into the surface; taking into account color and intensity
    // D: Directional light coming into the surface; taking into account color, intensity and direction
    const shadow = [
        ambStrength[0] > 0 ? ambStrength[0] / (ambStrength[0] + dirStrength[0]) : 0,
        ambStrength[1] > 0 ? ambStrength[1] / (ambStrength[1] + dirStrength[1]) : 0,
        ambStrength[2] > 0 ? ambStrength[2] / (ambStrength[2] + dirStrength[2]) : 0
    ];
    // Because blending will happen in sRGB space, convert the shadow factor to sRGB
    return linearVec3TosRGB(shadow);
}
function createLightMatrix(transform, shadowDirection, near, far, resolution, verticalRange) {
    const zoom = transform.zoom;
    const scale = transform.scale;
    const ws = transform.worldSize;
    const wsInverse = 1 / ws;
    // Find the minimum shadow cascade bounding sphere to create a rotation invariant shadow volume
    // https://lxjk.github.io/2017/04/15/Calculate-Minimal-Bounding-Sphere-of-Frustum.html
    const aspectRatio = transform.aspect;
    const k = Math.sqrt(1 + aspectRatio * aspectRatio) * Math.tan(transform.fovX * 0.5);
    const k2 = k * k;
    const farMinusNear = far - near;
    const farPlusNear = far + near;
    let centerDepth;
    let radius;
    if (k2 > farMinusNear / farPlusNear) {
        centerDepth = far;
        radius = far * k;
    } else {
        centerDepth = 0.5 * farPlusNear * (1 + k2);
        radius = 0.5 * Math.sqrt(farMinusNear * farMinusNear + 2 * (far * far + near * near) * k2 + farPlusNear * farPlusNear * k2 * k2);
    }
    const pixelsPerMeter = transform.projection.pixelsPerMeter(transform.center.lat, ws);
    const cameraToWorldMerc = transform._camera.getCameraToWorldMercator();
    const sphereCenter = [
        0,
        0,
        -centerDepth * wsInverse
    ];
    vec3_1.transformMat4(sphereCenter, sphereCenter, cameraToWorldMerc);
    let sphereRadius = radius * wsInverse;
    // Transform frustum bounds to mercator space
    const frustumPointToMercator = function (point) {
        point[0] /= scale;
        point[1] /= scale;
        point[2] = mercatorZfromAltitude(point[2], transform._center.lat);
        return point;
    };
    // Check if we have padding we need to recalculate radii
    const padding = transform._edgeInsets;
    // If there is padding
    if (padding.left !== 0 || padding.top !== 0 || padding.right !== 0 || padding.bottom !== 0) {
        // and the padding is not symmetrical
        if (padding.left !== padding.right || padding.top !== padding.bottom) {
            const zUnit = transform.projection.zAxisUnit === 'meters' ? pixelsPerMeter : 1;
            const worldToCamera = transform._camera.getWorldToCamera(transform.worldSize, zUnit);
            const cameraToClip = transform._camera.getCameraToClipPerspective(transform._fov, transform.width / transform.height, near, far);
            // Apply center of perspective offset
            cameraToClip[8] = -transform.centerOffset.x * 2 / transform.width;
            cameraToClip[9] = transform.centerOffset.y * 2 / transform.height;
            const cameraProj = new Float64Array(16);
            mat4_1.mul(cameraProj, cameraToClip, worldToCamera);
            const cameraInvProj = new Float64Array(16);
            mat4_1.invert(cameraInvProj, cameraProj);
            const frustum = Frustum.fromInvProjectionMatrix(cameraInvProj, ws, zoom, true);
            // Iterate over the frustum points to get the furthest one from the center
            for (const p of frustum.points) {
                const fp = frustumPointToMercator(p);
                sphereRadius = Math.max(sphereRadius, vec3_1.len(vec3_1.subtract([], sphereCenter, fp)));
            }
        }
    }
    const roundingMarginFactor = resolution / (resolution - 1);
    sphereRadius *= roundingMarginFactor;
    const pitch = Math.acos(shadowDirection[2]);
    const bearing = Math.atan2(-shadowDirection[0], -shadowDirection[1]);
    const camera = new FreeCamera();
    camera.position = sphereCenter;
    camera.setPitchBearing(pitch, bearing);
    // Construct the light view matrix
    const lightWorldToView = camera.getWorldToCamera(ws, pixelsPerMeter);
    // The lightMatrixNearZ value is a bit arbitrary. Its magnitude needs to be high enough to fit features that would
    // cast shadows into the view, but low enough to preserve depth precision in the shadow map.
    // The mercatorZfromZoom term gets used for the first cascade when zoom level is very high.
    // The radius term gets used for the second cascade in most cases and for the first cascade at lower zoom levels.
    const radiusPx = sphereRadius * ws;
    const lightMatrixNearZ = Math.min(transform._mercatorZfromZoom(17) * ws * -2, radiusPx * -2);
    const lightMatrixFarZ = (radiusPx + verticalRange * pixelsPerMeter) / shadowDirection[2];
    const lightViewToClip = camera.getCameraToClipOrthographic(-radiusPx, radiusPx, -radiusPx, radiusPx, lightMatrixNearZ, lightMatrixFarZ);
    const lightWorldToClip = new Float64Array(16);
    mat4_1.multiply(lightWorldToClip, lightViewToClip, lightWorldToView);
    // Move light camera in discrete steps in order to reduce shimmering when translating
    const alignedCenter = vec3_1.fromValues(Math.floor(sphereCenter[0] * 1000000) / 1000000 * ws, Math.floor(sphereCenter[1] * 1000000) / 1000000 * ws, 0);
    const halfResolution = 0.5 * resolution;
    const projectedPoint = [
        0,
        0,
        0
    ];
    vec3_1.transformMat4(projectedPoint, alignedCenter, lightWorldToClip);
    vec3_1.scale(projectedPoint, projectedPoint, halfResolution);
    const roundedPoint = [
        Math.floor(projectedPoint[0]),
        Math.floor(projectedPoint[1]),
        Math.floor(projectedPoint[2])
    ];
    const offsetVec = [
        0,
        0,
        0
    ];
    vec3_1.sub(offsetVec, projectedPoint, roundedPoint);
    vec3_1.scale(offsetVec, offsetVec, -1 / halfResolution);
    const truncMatrix = new Float64Array(16);
    mat4_1.identity(truncMatrix);
    mat4_1.translate(truncMatrix, truncMatrix, offsetVec);
    mat4_1.multiply(lightWorldToClip, truncMatrix, lightWorldToClip);
    return [
        lightWorldToClip,
        radiusPx
    ];
}

//      
class ModelManager extends Evented {
    constructor(requestManager) {
        super();
        this.requestManager = requestManager;
        this.models = { '': {} };
        this.numModelsLoading = {};
    }
    loadModel(id, url) {
        return loadGLTF(this.requestManager.transformRequest(url, ResourceType.Model).url).then(gltf => {
            if (!gltf)
                return;
            const nodes = convertModel(gltf);
            const model = new Model(id, undefined, undefined, nodes);
            model.computeBoundsAndApplyParent();
            return model;
        }).catch(err => {
            this.fire(new ErrorEvent(new Error(`Could not load model ${ id } from ${ url }: ${ err.message }`)));
        });
    }
    load(modelUris, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        const modelIds = Object.keys(modelUris);
        this.numModelsLoading[scope] = (this.numModelsLoading[scope] || 0) + modelIds.length;
        const modelLoads = [];
        for (const modelId of modelIds) {
            modelLoads.push(this.loadModel(modelId, modelUris[modelId]));
        }
        Promise.allSettled(modelLoads).then(results => {
            for (let i = 0; i < results.length; i++) {
                const {status, value} = results[i];
                if (status === 'fulfilled' && value)
                    this.models[scope][modelIds[i]] = value;
            }
            this.numModelsLoading[scope] -= modelIds.length;
            this.fire(new Event('data', { dataType: 'style' }));
        }).catch(err => {
            this.fire(new ErrorEvent(new Error(`Could not load models: ${ err.message }`)));
        });
    }
    isLoaded() {
        for (const scope in this.numModelsLoading) {
            if (this.numModelsLoading[scope] > 0)
                return false;
        }
        return true;
    }
    hasModel(id, scope) {
        return !!this.getModel(id, scope);
    }
    getModel(id, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        return this.models[scope][id];
    }
    addModel(id, url, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        // Destroy model if it exists
        if (this.hasModel(id, scope)) {
            this.removeModel(id, scope);
        }
        this.load({ [id]: this.requestManager.normalizeModelURL(url) }, scope);
    }
    addModels(models, scope) {
        const modelUris = {};
        for (const modelId in models) {
            modelUris[modelId] = this.requestManager.normalizeModelURL(models[modelId]);
        }
        this.load(modelUris, scope);
    }
    removeModel(id, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        const model = this.models[scope][id];
        delete this.models[scope][id];
        model.destroy();
    }
    listModels(scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        return Object.keys(this.models[scope]);
    }
    upload(painter, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        for (const modelId in this.models[scope]) {
            this.models[scope][modelId].upload(painter.context);
        }
    }
}

// We're skipping validation errors with the `source.canvas` identifier in order
// to continue to allow canvas sources to be added at runtime/updated in
// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424):
const emitValidationErrors = (evented, errors) => emitValidationErrors$1(evented, errors && errors.filter(error => error.identifier !== 'source.canvas'));
const supportedDiffOperations = pick(operations, [
    'addLayer',
    'removeLayer',
    'setLights',
    'setPaintProperty',
    'setLayoutProperty',
    'setSlot',
    'setFilter',
    'addSource',
    'removeSource',
    'setLayerZoomRange',
    'setLight',
    'setTransition',
    'setGeoJSONSourceData',
    'setTerrain',
    'setFog',
    'setProjection',
    'setCamera',
    'addImport',
    'removeImport',
    'setImportUrl',
    'setImportData',
    'setImportConfig'
]);
const ignoredDiffOperations = pick(operations, [
    'setCenter',
    'setZoom',
    'setBearing',
    'setPitch'
]);
const empty = emptyStyle();
const MAX_IMPORT_DEPTH = 5;
const defaultTransition = {
    duration: 300,
    delay: 0
};
// Symbols are draped only on native and for certain cases only
const drapedLayers = new Set([
    'fill',
    'line',
    'background',
    'hillshade',
    'raster'
]);
/**
 * @private
 */
class Style extends Evented {
    // Shared cache of imported stylesheets
    // Keeps track of ancestors' Style URLs.
    // Merged layers and sources
    // exposed to allow stubbing by unit tests
    constructor(map, options = {}) {
        super();
        this.map = map;
        // Empty string indicates the root Style scope.
        this.scope = options.scope || '';
        this.fragments = [];
        this.importDepth = options.importDepth || 0;
        this.importsCache = options.importsCache || new Map();
        this.resolvedImports = options.resolvedImports || new Set();
        this.transition = extend$1({}, defaultTransition);
        this._buildingIndex = new BuildingIndex(this);
        this.crossTileSymbolIndex = new CrossTileSymbolIndex();
        this._mergedOrder = [];
        this._drapedFirstOrder = [];
        this._mergedLayers = {};
        this._mergedSourceCaches = {};
        this._mergedOtherSourceCaches = {};
        this._mergedSymbolSourceCaches = {};
        this._has3DLayers = false;
        this._hasCircleLayers = false;
        this._hasSymbolLayers = false;
        this._changes = options.styleChanges || new StyleChanges();
        if (options.dispatcher) {
            this.dispatcher = options.dispatcher;
        } else {
            this.dispatcher = new Dispatcher(getGlobalWorkerPool(), this);
        }
        if (options.imageManager) {
            this.imageManager = options.imageManager;
        } else {
            this.imageManager = new ImageManager();
            this.imageManager.setEventedParent(this);
        }
        this.imageManager.createScope(this.scope);
        if (options.glyphManager) {
            this.glyphManager = options.glyphManager;
        } else {
            this.glyphManager = new GlyphManager(map._requestManager, options.localFontFamily ? LocalGlyphMode.all : options.localIdeographFontFamily ? LocalGlyphMode.ideographs : LocalGlyphMode.none, options.localFontFamily || options.localIdeographFontFamily);
        }
        if (options.modelManager) {
            this.modelManager = options.modelManager;
        } else {
            this.modelManager = new ModelManager(map._requestManager);
            this.modelManager.setEventedParent(this);
        }
        this._layers = {};
        this._serializedLayers = {};
        this._sourceCaches = {};
        this._otherSourceCaches = {};
        this._symbolSourceCaches = {};
        this._loaded = false;
        this._precompileDone = false;
        this._shouldPrecompile = false;
        this._availableImages = [];
        this._order = [];
        this._markersNeedUpdate = false;
        this.options = new Map();
        this._configDependentLayers = new Set();
        this.dispatcher.broadcast('setReferrer', getReferrer());
        const self = this;
        this._rtlTextPluginCallback = Style.registerForPluginStateChange(event => {
            const state = {
                pluginStatus: event.pluginStatus,
                pluginURL: event.pluginURL
            };
            self.dispatcher.broadcast('syncRTLPluginState', state, (err, results) => {
                triggerPluginCompletionEvent(err);
                if (results) {
                    const allComplete = results.every(elem => elem);
                    if (allComplete) {
                        for (const id in self._sourceCaches) {
                            const sourceCache = self._sourceCaches[id];
                            const sourceCacheType = sourceCache.getSource().type;
                            if (sourceCacheType === 'vector' || sourceCacheType === 'geojson') {
                                sourceCache.reload();    // Should be a no-op if the plugin loads before any tiles load
                            }
                        }
                    }
                }
            });
        });
        this.on('data', event => {
            if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') {
                return;
            }
            const source = this.getOwnSource(event.sourceId);
            if (!source || !source.vectorLayerIds) {
                return;
            }
            for (const layerId in this._layers) {
                const layer = this._layers[layerId];
                if (layer.source === source.id) {
                    this._validateLayer(layer);
                }
            }
        });
    }
    loadURL(url, options = {}) {
        this.fire(new Event('dataloading', { dataType: 'style' }));
        const validate = typeof options.validate === 'boolean' ? options.validate : !isMapboxURL(url);
        url = this.map._requestManager.normalizeStyleURL(url, options.accessToken);
        this.resolvedImports.add(url);
        const cachedImport = this.importsCache.get(url);
        if (cachedImport)
            return this._load(cachedImport, validate);
        const request = this.map._requestManager.transformRequest(url, ResourceType.Style);
        this._request = getJSON(request, (error, json) => {
            this._request = null;
            if (error) {
                this.fire(new ErrorEvent(error));
            } else if (json) {
                this.importsCache.set(url, json);
                return this._load(json, validate);
            }
        });
    }
    loadJSON(json, options = {}) {
        this.fire(new Event('dataloading', { dataType: 'style' }));
        this._request = exported$1.frame(() => {
            this._request = null;
            this._load(json, options.validate !== false);
        });
    }
    loadEmpty() {
        this.fire(new Event('dataloading', { dataType: 'style' }));
        this._load(empty, false);
    }
    _loadImports(imports, validate) {
        // We take the root style into account when calculating the import depth.
        if (this.importDepth >= MAX_IMPORT_DEPTH - 1) {
            warnOnce(`Style doesn't support nesting deeper than ${ MAX_IMPORT_DEPTH }`);
            return this._reloadImports();
        }
        const waitForStyles = [];
        for (const importSpec of imports) {
            const style = this._createFragmentStyle(importSpec);
            const waitForStyle = new Promise(resolve => style.on('style.import.load', resolve));
            waitForStyles.push(waitForStyle);
            // Load empty style if one of the ancestors was already
            // instantiated from this URL to avoid recursion.
            if (this.resolvedImports.has(importSpec.url)) {
                style.loadEmpty();
                continue;
            }
            // Use previously cached style JSON if the import data is not set.
            const json = importSpec.data || this.importsCache.get(importSpec.url);
            if (json) {
                style.loadJSON(json, { validate });
            } else if (importSpec.url) {
                style.loadURL(importSpec.url, { validate });
            } else {
                style.loadEmpty();
            }
            const fragment = {
                style,
                id: importSpec.id,
                config: importSpec.config
            };
            this.fragments.push(fragment);
        }
        // $FlowFixMe[method-unbinding]
        Promise.all(waitForStyles).then(() => this._reloadImports());
    }
    _createFragmentStyle(importSpec) {
        const scope = this.scope ? makeFQID(importSpec.id, this.scope) : importSpec.id;
        const style = new Style(this.map, {
            scope,
            styleChanges: this._changes,
            importDepth: this.importDepth + 1,
            importsCache: this.importsCache,
            // Clone resolvedImports so it's not being shared between siblings
            resolvedImports: new Set(this.resolvedImports),
            // Use shared Dispatcher and assets Managers between Styles
            dispatcher: this.dispatcher,
            imageManager: this.imageManager,
            glyphManager: this.glyphManager,
            modelManager: this.modelManager
        });
        // Bubble all events fired by the style to the map.
        style.setEventedParent(this.map, { style });
        style.setConfig(importSpec.config);
        return style;
    }
    _reloadImports() {
        this.mergeAll();
        this._updateMapProjection();
        this.dispatcher.broadcast('setLayers', {
            layers: this._serializeLayers(this._order),
            scope: this.scope,
            options: this.options
        });
        const isRootStyle = this.isRootStyle();
        this._shouldPrecompile = isRootStyle;
        this.fire(new Event('data', { dataType: 'style' }));
        this.fire(new Event(isRootStyle ? 'style.load' : 'style.import.load'));
    }
    _load(json, validate) {
        const schema = json.schema;
        // This style was loaded as a root style, but it is marked as a fragment and/or has a schema. We instead load
        // it as an import with the well-known ID "basemap" to make sure that we don't expose the internals.
        if (this.isRootStyle() && (json.fragment || schema && json.fragment !== false)) {
            const basemap = {
                id: 'basemap',
                data: json,
                url: ''
            };
            const style = extend$1({}, empty, { imports: [basemap] });
            this._load(style, validate);
            return;
        }
        this.updateSchema(schema);
        if (validate && emitValidationErrors(this, validateStyle(json))) {
            return;
        }
        this._loaded = true;
        this.stylesheet = clone$9(json);
        for (const id in json.sources) {
            this.addSource(id, json.sources[id], { validate: false });
        }
        this._changes.changed = false;
        // avoid triggering redundant style update after adding initial sources
        if (json.sprite) {
            this._loadSprite(json.sprite);
        } else {
            this.imageManager.setLoaded(true, this.scope);
            this.dispatcher.broadcast('spriteLoaded', {
                scope: this.scope,
                isLoaded: true
            });
        }
        this.glyphManager.setURL(json.glyphs, this.scope);
        const layers = derefLayers(this.stylesheet.layers);
        this._order = layers.map(layer => layer.id);
        if (this.stylesheet.light) {
            warnOnce('The `light` root property is deprecated, prefer using `lights` with `flat` light type instead.');
        }
        if (this.stylesheet.lights) {
            if (this.stylesheet.lights.length === 1 && this.stylesheet.lights[0].type === 'flat') {
                const flatLight = this.stylesheet.lights[0];
                this.light = new Light(flatLight.properties, flatLight.id);
            } else {
                this.setLights(this.stylesheet.lights);
            }
        }
        if (!this.light) {
            this.light = new Light(this.stylesheet.light);
        }
        this._layers = {};
        this._serializedLayers = {};
        for (const layer of layers) {
            const styleLayer = createStyleLayer(layer, this.options);
            styleLayer.setScope(this.scope);
            if (styleLayer.isConfigDependent)
                this._configDependentLayers.add(styleLayer.fqid);
            styleLayer.setEventedParent(this, { layer: { id: styleLayer.id } });
            this._layers[styleLayer.id] = styleLayer;
            this._layers[styleLayer.id] = styleLayer;
            this._serializedLayers[styleLayer.id] = styleLayer.serialize();
            const sourceCache = this.getOwnLayerSourceCache(styleLayer);
            const shadowsEnabled = !!this.directionalLight && this.directionalLight.shadowsEnabled();
            if (sourceCache && styleLayer.canCastShadows() && shadowsEnabled) {
                sourceCache.castsShadows = true;
            }
        }
        if (this.stylesheet.models) {
            this.modelManager.addModels(this.stylesheet.models, this.scope);
        }
        const terrain = this.stylesheet.terrain;
        if (terrain && !this.terrainSetForDrapingOnly()) {
            this._createTerrain(terrain, DrapeRenderMode.elevated);
        }
        if (this.stylesheet.fog) {
            this._createFog(this.stylesheet.fog);
        }
        if (this.stylesheet.transition) {
            this.setTransition(this.stylesheet.transition);
        }
        this.mergeAll();
        this._updateMapProjection();
        // Trigger update
        this.map._triggerCameraUpdate(this.camera);
        this.fire(new Event('data', { dataType: 'style' }));
        if (json.imports) {
            this._loadImports(json.imports, validate);
        } else {
            this.dispatcher.broadcast('setLayers', {
                layers: this._serializeLayers(this._order),
                scope: this.scope,
                options: this.options
            });
            const isRootStyle = this.isRootStyle();
            this._shouldPrecompile = isRootStyle;
            this.fire(new Event(isRootStyle ? 'style.load' : 'style.import.load'));
        }
    }
    isRootStyle() {
        return this.importDepth === 0;
    }
    mergeAll() {
        let light;
        let ambientLight;
        let directionalLight;
        let terrain;
        let fog;
        let projection;
        let transition;
        let camera;
        this.forEachFragmentStyle(style => {
            if (!style.stylesheet)
                return;
            if (style.light != null)
                light = style.light;
            if (style.stylesheet.lights) {
                for (const light of style.stylesheet.lights) {
                    if (light.type === 'ambient' && style.ambientLight != null)
                        ambientLight = style.ambientLight;
                    if (light.type === 'directional' && style.directionalLight != null)
                        directionalLight = style.directionalLight;
                }
            }
            const isGlobe = style.stylesheet.projection && style.stylesheet.projection.name === 'globe';
            if ((style.stylesheet.terrain || isGlobe) && style.terrain != null) {
                const nextIsElevated = style.terrain.drapeRenderMode === DrapeRenderMode.elevated;
                const prevIsDeffered = terrain && terrain.drapeRenderMode === DrapeRenderMode.deferred;
                if (!terrain || prevIsDeffered || nextIsElevated) {
                    terrain = style.terrain;
                }
            }
            if (style.stylesheet.fog && style.fog != null)
                fog = style.fog;
            if (style.stylesheet.camera != null)
                camera = style.stylesheet.camera;
            if (style.stylesheet.projection != null)
                projection = style.stylesheet.projection;
            if (style.stylesheet.transition != null)
                transition = style.stylesheet.transition;
        });
        // $FlowFixMe[incompatible-type]
        this.light = light;
        this.ambientLight = ambientLight;
        this.directionalLight = directionalLight;
        this.terrain = terrain;
        this.fog = fog;
        // Use perspective camera as a fallback if no camera is specified
        this.camera = camera || { 'camera-projection': 'perspective' };
        this.projection = projection || { name: 'mercator' };
        this.transition = extend$1({}, defaultTransition, transition);
        this.mergeSources();
        this.mergeLayers();
    }
    forEachFragmentStyle(fn) {
        const traverse = style => {
            for (const fragment of style.fragments) {
                traverse(fragment.style);
            }
            fn(style);
        };
        traverse(this);
    }
    mergeTerrain() {
        let terrain;
        this.forEachFragmentStyle(style => {
            if (style.terrain != null) {
                const nextIsElevated = style.terrain.drapeRenderMode === DrapeRenderMode.elevated;
                const prevIsDeffered = terrain && terrain.drapeRenderMode === DrapeRenderMode.deferred;
                if (!terrain || prevIsDeffered || nextIsElevated) {
                    terrain = style.terrain;
                }
            }
        });
        this.terrain = terrain;
    }
    mergeProjection() {
        let projection;
        this.forEachFragmentStyle(style => {
            if (style.stylesheet.projection != null)
                projection = style.stylesheet.projection;
        });
        this.projection = projection || { name: 'mercator' };
    }
    mergeSources() {
        const mergedSourceCaches = {};
        const mergedOtherSourceCaches = {};
        const mergedSymbolSourceCaches = {};
        this.forEachFragmentStyle(style => {
            for (const id in style._sourceCaches) {
                const fqid = makeFQID(id, style.scope);
                mergedSourceCaches[fqid] = style._sourceCaches[id];
            }
            for (const id in style._otherSourceCaches) {
                const fqid = makeFQID(id, style.scope);
                mergedOtherSourceCaches[fqid] = style._otherSourceCaches[id];
            }
            for (const id in style._symbolSourceCaches) {
                const fqid = makeFQID(id, style.scope);
                mergedSymbolSourceCaches[fqid] = style._symbolSourceCaches[id];
            }
        });
        this._mergedSourceCaches = mergedSourceCaches;
        this._mergedOtherSourceCaches = mergedOtherSourceCaches;
        this._mergedSymbolSourceCaches = mergedSymbolSourceCaches;
    }
    mergeLayers() {
        const slots = {};
        const mergedOrder = [];
        const mergedLayers = {};
        this._has3DLayers = false;
        this._hasCircleLayers = false;
        this._hasSymbolLayers = false;
        this.forEachFragmentStyle(style => {
            for (const layerId of style._order) {
                const layer = style._layers[layerId];
                if (layer.type === 'slot') {
                    const slotName = getNameFromFQID(layerId);
                    if (slots[slotName])
                        continue;
                    else
                        slots[slotName] = [];
                }
                if (layer.slot && slots[layer.slot]) {
                    slots[layer.slot].push(layer);
                    continue;
                }
                mergedOrder.push(layer);
            }
        });
        this._mergedOrder = [];
        const sort = (layers = []) => {
            for (const layer of layers) {
                if (layer.type === 'slot') {
                    const slotName = getNameFromFQID(layer.id);
                    if (slots[slotName])
                        sort(slots[slotName]);
                } else {
                    const fqid = makeFQID(layer.id, layer.scope);
                    this._mergedOrder.push(fqid);
                    mergedLayers[fqid] = layer;
                    // Typed layer bookkeeping
                    if (layer.is3D())
                        this._has3DLayers = true;
                    if (layer.type === 'circle')
                        this._hasCircleLayers = true;
                    if (layer.type === 'symbol')
                        this._hasSymbolLayers = true;
                }
            }
        };
        sort(mergedOrder);
        this._mergedLayers = mergedLayers;
        this.updateDrapeFirstLayers();
        this._buildingIndex.processLayersChanged();
    }
    terrainSetForDrapingOnly() {
        return !!this.terrain && this.terrain.drapeRenderMode === DrapeRenderMode.deferred;
    }
    getCamera() {
        return this.stylesheet.camera;
    }
    setCamera(camera) {
        this.stylesheet.camera = extend$1({}, this.stylesheet.camera, camera);
        this.camera = this.stylesheet.camera;
        return this;
    }
    setProjection(projection) {
        if (projection) {
            this.stylesheet.projection = projection;
        } else {
            delete this.stylesheet.projection;
        }
        this.mergeProjection();
        this._updateMapProjection();
    }
    applyProjectionUpdate() {
        if (!this._loaded)
            return;
        this.dispatcher.broadcast('setProjection', this.map.transform.projectionOptions);
        if (this.map.transform.projection.requiresDraping) {
            const hasTerrain = this.getTerrain() || this.stylesheet.terrain;
            if (!hasTerrain) {
                this.setTerrainForDraping();
            }
        } else if (this.terrainSetForDrapingOnly()) {
            this.setTerrain(null);
        }
    }
    _updateMapProjection() {
        // Skip projection updates from the children fragments
        if (!this.isRootStyle())
            return;
        if (!this.map._useExplicitProjection) {
            // Update the visible projection if map's is null
            this.map._prioritizeAndUpdateProjection(null, this.projection);
        } else {
            // Ensure that style is consistent with current projection on style load
            this.applyProjectionUpdate();
        }
    }
    _loadSprite(url) {
        this._spriteRequest = loadSprite(url, this.map._requestManager, (err, images) => {
            this._spriteRequest = null;
            if (err) {
                this.fire(new ErrorEvent(err));
            } else if (images) {
                for (const id in images) {
                    this.imageManager.addImage(id, this.scope, images[id]);
                }
            }
            this.imageManager.setLoaded(true, this.scope);
            this._availableImages = this.imageManager.listImages(this.scope);
            this.dispatcher.broadcast('setImages', {
                scope: this.scope,
                images: this._availableImages
            });
            this.dispatcher.broadcast('spriteLoaded', {
                scope: this.scope,
                isLoaded: true
            });
            this.fire(new Event('data', { dataType: 'style' }));
        });
    }
    _validateLayer(layer) {
        const source = this.getOwnSource(layer.source);
        if (!source) {
            return;
        }
        const sourceLayer = layer.sourceLayer;
        if (!sourceLayer) {
            return;
        }
        if (source.type === 'geojson' || source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1) {
            this.fire(new ErrorEvent(new Error(`Source layer "${ sourceLayer }" ` + `does not exist on source "${ source.id }" ` + `as specified by style layer "${ layer.id }"`)));
        }
    }
    loaded() {
        if (!this._loaded)
            return false;
        if (Object.keys(this._changes.updatedSourceCaches).length)
            return false;
        for (const id in this._sourceCaches)
            if (!this._sourceCaches[id].loaded())
                return false;
        if (!this.imageManager.isLoaded())
            return false;
        if (!this.modelManager.isLoaded())
            return false;
        for (const {style} of this.fragments) {
            if (!style.loaded())
                return false;
        }
        return true;
    }
    _serializeImports() {
        if (!this.stylesheet.imports)
            return undefined;
        return this.stylesheet.imports.map((importSpec, index) => {
            const fragment = this.fragments[index];
            if (fragment && fragment.style) {
                importSpec.data = fragment.style.serialize();
            }
            return importSpec;
        });
    }
    _serializeSources() {
        const sources = {};
        for (const cacheId in this._sourceCaches) {
            const source = this._sourceCaches[cacheId].getSource();
            if (!sources[source.id]) {
                sources[source.id] = source.serialize();
            }
        }
        return sources;
    }
    _serializeLayers(ids) {
        const serializedLayers = [];
        for (const id of ids) {
            const layer = this._layers[id];
            if (layer && layer.type !== 'custom') {
                serializedLayers.push(layer.serialize());
            }
        }
        return serializedLayers;
    }
    hasLightTransitions() {
        if (this.light && this.light.hasTransition()) {
            return true;
        }
        if (this.ambientLight && this.ambientLight.hasTransition()) {
            return true;
        }
        if (this.directionalLight && this.directionalLight.hasTransition()) {
            return true;
        }
        return false;
    }
    hasFogTransition() {
        if (!this.fog)
            return false;
        return this.fog.hasTransition();
    }
    hasTransitions() {
        if (this.hasLightTransitions()) {
            return true;
        }
        if (this.hasFogTransition()) {
            return true;
        }
        for (const id in this._sourceCaches) {
            if (this._sourceCaches[id].hasTransition()) {
                return true;
            }
        }
        for (const layerId in this._layers) {
            const layer = this._layers[layerId];
            if (layer.hasTransition()) {
                return true;
            }
        }
        return false;
    }
    get order() {
        if (this.terrain) {
            return this._drapedFirstOrder;
        }
        return this._mergedOrder;
    }
    isLayerDraped(layer) {
        if (!this.terrain)
            return false;
        if (typeof layer.isLayerDraped === 'function')
            return layer.isLayerDraped(this.getLayerSourceCache(layer));
        return drapedLayers.has(layer.type);
    }
    _checkLoaded() {
        if (!this._loaded) {
            throw new Error('Style is not done loading');
        }
    }
    _checkLayer(layerId) {
        const layer = this.getOwnLayer(layerId);
        if (!layer) {
            this.fire(new ErrorEvent(new Error(`The layer '${ layerId }' does not exist in the map's style.`)));
            return;
        }
        return layer;
    }
    _checkSource(sourceId) {
        const source = this.getOwnSource(sourceId);
        if (!source) {
            this.fire(new ErrorEvent(new Error(`The source '${ sourceId }' does not exist in the map's style.`)));
            return;
        }
        return source;
    }
    /**
     * Apply queued style updates in a batch and recalculate zoom-dependent paint properties.
     * @private
     */
    update(parameters) {
        if (!this._loaded) {
            return;
        }
        if (this.ambientLight) {
            this.ambientLight.recalculate(parameters);
        }
        if (this.directionalLight) {
            this.directionalLight.recalculate(parameters);
        }
        const brightness = this.calculateLightsBrightness();
        parameters.brightness = brightness || 0;
        if (brightness !== this._brightness) {
            this._brightness = brightness;
            this.dispatcher.broadcast('setBrightness', brightness);
        }
        const changed = this._changes.changed;
        if (this._changes.changed) {
            const updatesByScope = this._changes.getLayerUpdatesByScope();
            for (const scope in updatesByScope) {
                const {updatedIds, removedIds} = updatesByScope[scope];
                if (updatedIds || removedIds) {
                    this._updateWorkerLayers(scope, updatedIds, removedIds);
                }
            }
            this.updateSourceCaches();
            this._updateTilesForChangedImages();
            this.updateLayers(parameters);
            if (this.light) {
                this.light.updateTransitions(parameters);
            }
            if (this.ambientLight) {
                this.ambientLight.updateTransitions(parameters);
            }
            if (this.directionalLight) {
                this.directionalLight.updateTransitions(parameters);
            }
            if (this.fog) {
                this.fog.updateTransitions(parameters);
            }
            this._changes.reset();
        }
        const sourcesUsedBefore = {};
        for (const sourceId in this._mergedSourceCaches) {
            const sourceCache = this._mergedSourceCaches[sourceId];
            sourcesUsedBefore[sourceId] = sourceCache.used;
            sourceCache.used = false;
        }
        for (const layerId of this._mergedOrder) {
            const layer = this._mergedLayers[layerId];
            layer.recalculate(parameters, this._availableImages);
            if (!layer.isHidden(parameters.zoom)) {
                const sourceCache = this.getOwnLayerSourceCache(layer);
                if (sourceCache)
                    sourceCache.used = true;
            }
            if (!this._precompileDone && this._shouldPrecompile) {
                for (let i = layer.minzoom || DEFAULT_MIN_ZOOM; i < (layer.maxzoom || DEFAULT_MAX_ZOOM); i++) {
                    const painter = this.map.painter;
                    if (painter) {
                        const programIds = layer.getProgramIds();
                        if (!programIds)
                            continue;
                        for (const programId of programIds) {
                            const params = layer.getDefaultProgramParams(programId, parameters.zoom);
                            if (params) {
                                painter.style = this;
                                if (this.fog) {
                                    painter._fogVisible = true;
                                    params.overrideFog = true;
                                    painter.getOrCreateProgram(programId, params);
                                }
                                painter._fogVisible = false;
                                params.overrideFog = false;
                                painter.getOrCreateProgram(programId, params);
                                if (this.stylesheet.terrain || this.stylesheet.projection && this.stylesheet.projection.name === 'globe') {
                                    params.overrideRtt = true;
                                    painter.getOrCreateProgram(programId, params);
                                }
                            }
                        }
                    }
                }
            }
        }
        if (this._shouldPrecompile) {
            this._precompileDone = true;
        }
        for (const sourceId in sourcesUsedBefore) {
            const sourceCache = this._mergedSourceCaches[sourceId];
            if (sourcesUsedBefore[sourceId] !== sourceCache.used) {
                sourceCache.getSource().fire(new Event('data', {
                    sourceDataType: 'visibility',
                    dataType: 'source',
                    sourceId: sourceCache.getSource().id
                }));
            }
        }
        if (this.light) {
            this.light.recalculate(parameters);
        }
        if (this.terrain) {
            this.terrain.recalculate(parameters);
        }
        if (this.fog) {
            this.fog.recalculate(parameters);
        }
        this.z = parameters.zoom;
        if (this._markersNeedUpdate) {
            this._updateMarkersOpacity();
            this._markersNeedUpdate = false;
        }
        if (changed) {
            this.fire(new Event('data', { dataType: 'style' }));
        }
        for (const {style} of this.fragments) {
            style.update(parameters);
        }
    }
    /*
     * Apply any queued image changes.
     */
    _updateTilesForChangedImages() {
        const changedImages = Array.from(this._changes.changedImages.keys());
        if (changedImages.length) {
            for (const name in this._sourceCaches) {
                this._sourceCaches[name].reloadTilesForDependencies([
                    'icons',
                    'patterns'
                ], changedImages);
            }
            this._changes.changedImages.clear();
        }
    }
    _updateWorkerLayers(scope, updatedIds, removedIds) {
        const fragmentStyle = this.getFragmentStyle(scope);
        this.dispatcher.broadcast('updateLayers', {
            layers: updatedIds ? fragmentStyle._serializeLayers(updatedIds) : [],
            scope,
            removedIds: removedIds || [],
            options: fragmentStyle.options
        });
    }
    /**
     * Update this style's state to match the given style JSON, performing only
     * the necessary mutations.
     *
     * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec
     * diff algorithm produces an operation that is not supported.
     *
     * @returns {boolean} true if any changes were made; false otherwise
     * @private
     */
    setState(nextState) {
        this._checkLoaded();
        if (emitValidationErrors(this, validateStyle(nextState)))
            return false;
        nextState = clone$9(nextState);
        nextState.layers = derefLayers(nextState.layers);
        const changes = diffStyles(this.serialize(), nextState).filter(op => !(op.command in ignoredDiffOperations));
        if (changes.length === 0) {
            return false;
        }
        const unimplementedOps = changes.filter(op => !(op.command in supportedDiffOperations));
        if (unimplementedOps.length > 0) {
            throw new Error(`Unimplemented: ${ unimplementedOps.map(op => op.command).join(', ') }.`);
        }
        changes.forEach(op => {
            this[op.command].apply(this, op.args);
        });
        this.stylesheet = nextState;
        this.mergeAll();
        this.dispatcher.broadcast('setLayers', {
            layers: this._serializeLayers(this._order),
            scope: this.scope,
            options: this.options
        });
        return true;
    }
    addImage(id, image) {
        if (this.getImage(id)) {
            return this.fire(new ErrorEvent(new Error('An image with this name already exists.')));
        }
        this.imageManager.addImage(id, this.scope, image);
        this._afterImageUpdated(id);
        return this;
    }
    updateImage(id, image) {
        this.imageManager.updateImage(id, this.scope, image);
    }
    getImage(id) {
        return this.imageManager.getImage(id, this.scope);
    }
    removeImage(id) {
        if (!this.getImage(id)) {
            return this.fire(new ErrorEvent(new Error('No image with this name exists.')));
        }
        this.imageManager.removeImage(id, this.scope);
        this._afterImageUpdated(id);
        return this;
    }
    _afterImageUpdated(id) {
        this._availableImages = this.imageManager.listImages(this.scope);
        this._changes.changedImages.add(id);
        this._changes.changed = true;
        this.dispatcher.broadcast('setImages', {
            scope: this.scope,
            images: this._availableImages
        });
        this.fire(new Event('data', { dataType: 'style' }));
    }
    listImages() {
        this._checkLoaded();
        return this._availableImages.slice();
    }
    addModel(id, url, options = {}) {
        this._checkLoaded();
        if (this._validate(validateModel, `models.${ id }`, url, null, options))
            return this;
        this.modelManager.addModel(id, url, this.scope);
        this._changes.changed = true;
        return this;
    }
    hasModel(id) {
        return this.modelManager.hasModel(id, this.scope);
    }
    removeModel(id) {
        if (!this.hasModel(id)) {
            return this.fire(new ErrorEvent(new Error('No model with this ID exists.')));
        }
        this.modelManager.removeModel(id, this.scope);
        return this;
    }
    listModels() {
        this._checkLoaded();
        return this.modelManager.listModels(this.scope);
    }
    addSource(id, source, options = {}) {
        this._checkLoaded();
        if (this.getOwnSource(id) !== undefined) {
            throw new Error(`There is already a source with ID "${ id }".`);
        }
        if (!source.type) {
            throw new Error(`The type property must be defined, but only the following properties were given: ${ Object.keys(source).join(', ') }.`);
        }
        const builtIns = [
            'vector',
            'raster',
            'geojson',
            'video',
            'image'
        ];
        const shouldValidate = builtIns.indexOf(source.type) >= 0;
        if (shouldValidate && this._validate(validateSource, `sources.${ id }`, source, null, options))
            return;
        if (this.map && this.map._collectResourceTiming)
            source.collectResourceTiming = true;
        const sourceInstance = create(id, source, this.dispatcher, this);
        sourceInstance.scope = this.scope;
        sourceInstance.setEventedParent(this, () => ({
            isSourceLoaded: this._isSourceCacheLoaded(sourceInstance.id),
            source: sourceInstance.serialize(),
            sourceId: sourceInstance.id
        }));
        const addSourceCache = onlySymbols => {
            const sourceCacheId = (onlySymbols ? 'symbol:' : 'other:') + sourceInstance.id;
            const sourceCacheFQID = makeFQID(sourceCacheId, this.scope);
            const sourceCache = this._sourceCaches[sourceCacheId] = new SourceCache(sourceCacheFQID, sourceInstance, onlySymbols);
            (onlySymbols ? this._symbolSourceCaches : this._otherSourceCaches)[sourceInstance.id] = sourceCache;
            sourceCache.onAdd(this.map);
        };
        addSourceCache(false);
        if (source.type === 'vector' || source.type === 'geojson') {
            addSourceCache(true);
        }
        if (sourceInstance.onAdd)
            sourceInstance.onAdd(this.map);
        this.mergeSources();
        this._changes.changed = true;
    }
    /**
     * Remove a source from this stylesheet, given its ID.
     * @param {string} id ID of the source to remove.
     * @throws {Error} If no source is found with the given ID.
     * @returns {Map} The {@link Map} object.
     */
    removeSource(id) {
        this._checkLoaded();
        const source = this.getOwnSource(id);
        if (!source) {
            throw new Error('There is no source with this ID');
        }
        for (const layerId in this._layers) {
            if (this._layers[layerId].source === id) {
                return this.fire(new ErrorEvent(new Error(`Source "${ id }" cannot be removed while layer "${ layerId }" is using it.`)));
            }
        }
        if (this.terrain && this.terrain.get().source === id) {
            return this.fire(new ErrorEvent(new Error(`Source "${ id }" cannot be removed while terrain is using it.`)));
        }
        const sourceCaches = this.getOwnSourceCaches(id);
        for (const sourceCache of sourceCaches) {
            const id = getNameFromFQID(sourceCache.id);
            delete this._sourceCaches[id];
            delete this._changes.updatedSourceCaches[sourceCache.id];
            sourceCache.fire(new Event('data', {
                sourceDataType: 'metadata',
                dataType: 'source',
                sourceId: sourceCache.getSource().id
            }));
            sourceCache.setEventedParent(null);
            sourceCache.clearTiles();
        }
        delete this._otherSourceCaches[id];
        delete this._symbolSourceCaches[id];
        this.mergeSources();
        source.setEventedParent(null);
        if (source.onRemove) {
            source.onRemove(this.map);
        }
        this._changes.changed = true;
        return this;
    }
    /**
     * Set the data of a GeoJSON source, given its ID.
     * @param {string} id ID of the source.
     * @param {GeoJSON|string} data GeoJSON source.
     */
    setGeoJSONSourceData(id, data) {
        this._checkLoaded();
        const geojsonSource = this.getOwnSource(id);
        geojsonSource.setData(data);
        this._changes.changed = true;
    }
    /**
     * Get a source by ID.
     * @param {string} id ID of the desired source.
     * @returns {?Source} The source object.
     */
    getOwnSource(id) {
        const sourceCache = this.getOwnSourceCache(id);
        return sourceCache && sourceCache.getSource();
    }
    getOwnSources() {
        const sources = [];
        for (const id in this._otherSourceCaches) {
            const sourceCache = this.getOwnSourceCache(id);
            if (sourceCache)
                sources.push(sourceCache.getSource());
        }
        return sources;
    }
    setLights(lights) {
        this._checkLoaded();
        if (!lights) {
            delete this.ambientLight;
            delete this.directionalLight;
            return;
        }
        const transitionParameters = this._getTransitionParameters();
        for (const light of lights) {
            if (this._validate(validateLights, 'lights', light)) {
                return;
            }
            switch (light.type) {
            case 'ambient':
                if (this.ambientLight) {
                    const ambientLight = this.ambientLight;
                    ambientLight.set(light);
                    ambientLight.updateTransitions(transitionParameters);
                } else {
                    this.ambientLight = new Lights(light, properties$1, this.scope, this.options);
                }
                break;
            case 'directional':
                if (this.directionalLight) {
                    const directionalLight = this.directionalLight;
                    directionalLight.set(light);
                    directionalLight.updateTransitions(transitionParameters);
                } else {
                    this.directionalLight = new Lights(light, properties, this.scope, this.options);
                }
                break;
            }
        }
        const evaluationParameters = new EvaluationParameters(this.z || 0, transitionParameters);
        if (this.ambientLight) {
            this.ambientLight.recalculate(evaluationParameters);
        }
        if (this.directionalLight) {
            this.directionalLight.recalculate(evaluationParameters);
        }
        this._brightness = this.calculateLightsBrightness();
        this.dispatcher.broadcast('setBrightness', this._brightness);
    }
    calculateLightsBrightness() {
        const directional = this.directionalLight;
        const ambient = this.ambientLight;
        if (!directional || !ambient) {
            return;
        }
        // Based on: https://www.w3.org/WAI/GL/wiki/Relative_luminance
        const relativeLuminance = color => {
            const r = color[0] <= 0.03928 ? color[0] / 12.92 : Math.pow((color[0] + 0.055) / 1.055, 2.4);
            const g = color[1] <= 0.03928 ? color[1] / 12.92 : Math.pow((color[1] + 0.055) / 1.055, 2.4);
            const b = color[2] <= 0.03928 ? color[2] / 12.92 : Math.pow((color[2] + 0.055) / 1.055, 2.4);
            return 0.2126 * r + 0.7152 * g + 0.0722 * b;
        };
        const directionalColor = directional.properties.get('color').toArray01();
        const directionalIntensity = directional.properties.get('intensity');
        const direction = directional.properties.get('direction');
        const sphericalDirection = cartesianPositionToSpherical(direction.x, direction.y, direction.z);
        const polarIntensity = 1 - sphericalDirection[2] / 90;
        const directionalBrightness = relativeLuminance(directionalColor) * directionalIntensity * polarIntensity;
        const ambientColor = ambient.properties.get('color').toArray01();
        const ambientIntensity = ambient.properties.get('intensity');
        const ambientBrightness = relativeLuminance(ambientColor) * ambientIntensity;
        return (directionalBrightness + ambientBrightness) / 2;
    }
    getBrightness() {
        return this._brightness;
    }
    getLights() {
        if (!this.enable3dLights())
            return null;
        const lights = [];
        if (this.directionalLight) {
            lights.push(this.directionalLight.get());
        }
        if (this.ambientLight) {
            lights.push(this.ambientLight.get());
        }
        return lights;
    }
    enable3dLights() {
        return !!this.ambientLight && !!this.directionalLight;
    }
    getFragmentStyle(fragmentId) {
        if (!fragmentId)
            return this;
        const fragment = this.fragments.find(({id}) => id === fragmentId);
        if (!fragment)
            throw new Error(`Style import not found: ${ fragmentId }`);
        return fragment.style;
    }
    setConfigProperty(fragmentId, key, value) {
        const expressionParsed = createExpression(value);
        if (expressionParsed.result !== 'success') {
            emitValidationErrors(this, expressionParsed.value);
            return;
        }
        const expression = expressionParsed.value.expression;
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        fragmentStyle.options.set(key, expression);
        fragmentStyle.updateConfigDependencies();
    }
    setConfig(config, schema) {
        this.options.clear();
        if (!config)
            return;
        for (const key in config) {
            const expressionParsed = createExpression(config[key]);
            if (expressionParsed.result === 'success') {
                this.options.set(key, expressionParsed.value.expression);
            }
        }
        this.updateSchema(schema);
    }
    updateSchema(schema) {
        if (!schema)
            return;
        for (const id in schema) {
            // already set by config
            if (this.options.has(id))
                continue;
            const expression = schema[id].default;
            const expressionParsed = createExpression(expression);
            if (expressionParsed.result === 'success') {
                this.options.set(id, expressionParsed.value.expression);
            }
        }
    }
    updateConfigDependencies() {
        for (const id of this._configDependentLayers) {
            const layer = this.getLayer(id);
            if (layer) {
                layer.possiblyEvaluateVisibility();
                this._updateLayer(layer);
            }
        }
        // If the root style uses the lights from the updated fragment,
        // update the configs in the corresponding light instances.
        if (this.ambientLight && this.ambientLight.scope === this.scope) {
            this.ambientLight.updateConfig(this.options);
        }
        if (this.directionalLight && this.directionalLight.scope === this.scope) {
            this.directionalLight.updateConfig(this.options);
        }
        this._changes.changed = true;
    }
    /**
     * Add a layer to the map style. The layer will be inserted before the layer with
     * ID `before`, or appended if `before` is omitted.
     * @param {Object | CustomLayerInterface} layerObject The style layer to add.
     * @param {string} [before] ID of an existing layer to insert before.
     * @param {Object} options Style setter options.
     * @returns {Map} The {@link Map} object.
     */
    addLayer(layerObject, before, options = {}) {
        this._checkLoaded();
        const id = layerObject.id;
        if (this._layers[id]) {
            this.fire(new ErrorEvent(new Error(`Layer with id "${ id }" already exists on this map`)));
            return;
        }
        let layer;
        if (layerObject.type === 'custom') {
            if (emitValidationErrors(this, validateCustomStyleLayer(layerObject)))
                return;
            layer = createStyleLayer(layerObject, this.options);
        } else {
            if (typeof layerObject.source === 'object') {
                this.addSource(id, layerObject.source);
                layerObject = clone$9(layerObject);
                layerObject = extend$1(layerObject, { source: id });
            }
            // this layer is not in the style.layers array, so we pass an impossible array index
            if (this._validate(validateLayer, `layers.${ id }`, layerObject, { arrayIndex: -1 }, options))
                return;
            layer = createStyleLayer(layerObject, this.options);
            this._validateLayer(layer);
            layer.setEventedParent(this, { layer: { id } });
            this._serializedLayers[layer.id] = layer.serialize();
        }
        if (layer.isConfigDependent)
            this._configDependentLayers.add(layer.fqid);
        layer.setScope(this.scope);
        const index = before ? this._order.indexOf(before) : this._order.length;
        if (before && index === -1) {
            this.fire(new ErrorEvent(new Error(`Layer with id "${ before }" does not exist on this map.`)));
            return;
        }
        this._order.splice(index, 0, id);
        this._layerOrderChanged = true;
        this._layers[id] = layer;
        const sourceCache = this.getOwnLayerSourceCache(layer);
        const shadowsEnabled = !!this.directionalLight && this.directionalLight.shadowsEnabled();
        if (sourceCache && layer.canCastShadows() && shadowsEnabled) {
            sourceCache.castsShadows = true;
        }
        const removedLayer = this._changes.getRemovedLayer(layer);
        if (removedLayer && layer.source && sourceCache && layer.type !== 'custom') {
            // If, in the current batch, we have already removed this layer
            // and we are now re-adding it with a different `type`, then we
            // need to clear (rather than just reload) the underyling source's
            // tiles.  Otherwise, tiles marked 'reloading' will have buckets /
            // buffers that are set up for the _previous_ version of this
            // layer, causing, e.g.:
            // https://github.com/mapbox/mapbox-gl-js/issues/3633
            this._changes.discardLayerRemoval(layer);
            const fqid = makeFQID(layer.source, layer.scope);
            if (removedLayer.type !== layer.type) {
                this._changes.updatedSourceCaches[fqid] = 'clear';
            } else {
                this._changes.updatedSourceCaches[fqid] = 'reload';
                sourceCache.pause();
            }
        }
        this._updateLayer(layer);
        // $FlowFixMe[method-unbinding]
        if (layer.onAdd) {
            layer.onAdd(this.map);
        }
        layer.scope = this.scope;
        this.mergeLayers();
    }
    /**
     * Moves a layer to a different z-position. The layer will be inserted before the layer with
     * ID `before`, or appended if `before` is omitted.
     * @param {string} id  ID of the layer to move.
     * @param {string} [before] ID of an existing layer to insert before.
     */
    moveLayer(id, before) {
        this._checkLoaded();
        this._changes.changed = true;
        const layer = this._checkLayer(id);
        if (!layer)
            return;
        if (id === before) {
            return;
        }
        const index = this._order.indexOf(id);
        this._order.splice(index, 1);
        const newIndex = before ? this._order.indexOf(before) : this._order.length;
        if (before && newIndex === -1) {
            this.fire(new ErrorEvent(new Error(`Layer with id "${ before }" does not exist on this map.`)));
            return;
        }
        this._order.splice(newIndex, 0, id);
        this._layerOrderChanged = true;
        this.mergeLayers();
    }
    /**
     * Remove the layer with the given id from the style.
     *
     * If no such layer exists, an `error` event is fired.
     *
     * @param {string} id ID of the layer to remove.
     * @fires Map.event:error
     */
    removeLayer(id) {
        this._checkLoaded();
        const layer = this._checkLayer(id);
        if (!layer)
            return;
        layer.setEventedParent(null);
        const index = this._order.indexOf(id);
        this._order.splice(index, 1);
        delete this._layers[id];
        delete this._serializedLayers[id];
        this._changes.changed = true;
        this._layerOrderChanged = true;
        this._configDependentLayers.delete(layer.fqid);
        this._changes.removeLayer(layer);
        const sourceCache = this.getOwnLayerSourceCache(layer);
        if (sourceCache && sourceCache.castsShadows) {
            let shadowCastersLeft = false;
            for (const key in this._layers) {
                if (this._layers[key].source === layer.source && this._layers[key].canCastShadows()) {
                    shadowCastersLeft = true;
                    break;
                }
            }
            sourceCache.castsShadows = shadowCastersLeft;
        }
        if (layer.onRemove) {
            layer.onRemove(this.map);
        }
        this.mergeLayers();
    }
    /**
     * Return the style layer object with the given `id`.
     *
     * @param {string} id ID of the desired layer.
     * @returns {?StyleLayer} A layer, if one with the given `id` exists.
     */
    getOwnLayer(id) {
        return this._layers[id];
    }
    /**
     * Checks if a specific layer is present within the style.
     *
     * @param {string} id ID of the desired layer.
     * @returns {boolean} A boolean specifying if the given layer is present.
     */
    hasLayer(id) {
        return id in this._mergedLayers;
    }
    /**
     * Checks if a specific layer type is present within the style.
     *
     * @param {string} type Type of the desired layer.
     * @returns {boolean} A boolean specifying if the given layer type is present.
     */
    hasLayerType(type) {
        for (const layerId in this._layers) {
            const layer = this._layers[layerId];
            if (layer.type === type) {
                return true;
            }
        }
        return false;
    }
    setLayerZoomRange(layerId, minzoom, maxzoom) {
        this._checkLoaded();
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        if (layer.minzoom === minzoom && layer.maxzoom === maxzoom)
            return;
        if (minzoom != null) {
            layer.minzoom = minzoom;
        }
        if (maxzoom != null) {
            layer.maxzoom = maxzoom;
        }
        this._updateLayer(layer);
    }
    setSlot(layerId, slot) {
        this._checkLoaded();
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        if (layer.slot === slot) {
            return;
        }
        layer.slot = slot;
        this._updateLayer(layer);
    }
    setFilter(layerId, filter, options = {}) {
        this._checkLoaded();
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        if (deepEqual(layer.filter, filter)) {
            return;
        }
        if (filter === null || filter === undefined) {
            layer.filter = undefined;
            this._updateLayer(layer);
            return;
        }
        if (this._validate(validateFilter, `layers.${ layer.id }.filter`, filter, { layerType: layer.type }, options)) {
            return;
        }
        layer.filter = clone$9(filter);
        this._updateLayer(layer);
    }
    /**
     * Get a layer's filter object.
     * @param {string} layerId The layer to inspect.
     * @returns {*} The layer's filter, if any.
     */
    getFilter(layerId) {
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        return clone$9(layer.filter);
    }
    setLayoutProperty(layerId, name, value, options = {}) {
        this._checkLoaded();
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        if (deepEqual(layer.getLayoutProperty(name), value))
            return;
        layer.setLayoutProperty(name, value, options);
        if (layer.isConfigDependent)
            this._configDependentLayers.add(layer.fqid);
        this._updateLayer(layer);
    }
    /**
     * Get a layout property's value from a given layer.
     * @param {string} layerId The layer to inspect.
     * @param {string} name The name of the layout property.
     * @returns {*} The property value.
     */
    getLayoutProperty(layerId, name) {
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        return layer.getLayoutProperty(name);
    }
    setPaintProperty(layerId, name, value, options = {}) {
        this._checkLoaded();
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        if (deepEqual(layer.getPaintProperty(name), value))
            return;
        const requiresRelayout = layer.setPaintProperty(name, value, options);
        if (layer.isConfigDependent)
            this._configDependentLayers.add(layer.fqid);
        if (requiresRelayout) {
            this._updateLayer(layer);
        }
        this._changes.changed = true;
        this._changes.updatedPaintProps.add(layer.fqid);
    }
    getPaintProperty(layerId, name) {
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        return layer.getPaintProperty(name);
    }
    setFeatureState(target, state) {
        this._checkLoaded();
        const sourceId = target.source;
        const sourceLayer = target.sourceLayer;
        const source = this._checkSource(sourceId);
        if (!source)
            return;
        const sourceType = source.type;
        if (sourceType === 'geojson' && sourceLayer) {
            this.fire(new ErrorEvent(new Error(`GeoJSON sources cannot have a sourceLayer parameter.`)));
            return;
        }
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
            return;
        }
        if (target.id === undefined) {
            this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided.`)));
        }
        const sourceCaches = this.getOwnSourceCaches(sourceId);
        for (const sourceCache of sourceCaches) {
            sourceCache.setFeatureState(sourceLayer, target.id, state);
        }
    }
    removeFeatureState(target, key) {
        this._checkLoaded();
        const sourceId = target.source;
        const source = this._checkSource(sourceId);
        if (!source)
            return;
        const sourceType = source.type;
        const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined;
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
            return;
        }
        if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) {
            this.fire(new ErrorEvent(new Error(`A feature id is required to remove its specific state property.`)));
            return;
        }
        const sourceCaches = this.getOwnSourceCaches(sourceId);
        for (const sourceCache of sourceCaches) {
            sourceCache.removeFeatureState(sourceLayer, target.id, key);
        }
    }
    getFeatureState(target) {
        this._checkLoaded();
        const sourceId = target.source;
        const sourceLayer = target.sourceLayer;
        const source = this._checkSource(sourceId);
        if (!source)
            return;
        const sourceType = source.type;
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
            return;
        }
        if (target.id === undefined) {
            this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided.`)));
        }
        const sourceCaches = this.getOwnSourceCaches(sourceId);
        return sourceCaches[0].getFeatureState(sourceLayer, target.id);
    }
    setTransition(transition) {
        this.stylesheet.transition = extend$1({}, this.stylesheet.transition, transition);
        this.transition = this.stylesheet.transition;
        return this;
    }
    getTransition() {
        return extend$1({}, this.stylesheet.transition);
    }
    serialize() {
        this._checkLoaded();
        const terrain = this.getTerrain();
        const scopedTerrain = terrain && this.terrain && this.terrain.scope === this.scope ? terrain : undefined;
        return filterObject({
            version: this.stylesheet.version,
            name: this.stylesheet.name,
            metadata: this.stylesheet.metadata,
            imports: this._serializeImports(),
            schema: this.stylesheet.schema,
            camera: this.stylesheet.camera,
            light: this.stylesheet.light,
            lights: this.stylesheet.lights,
            terrain: scopedTerrain,
            fog: this.stylesheet.fog,
            center: this.stylesheet.center,
            zoom: this.stylesheet.zoom,
            bearing: this.stylesheet.bearing,
            pitch: this.stylesheet.pitch,
            sprite: this.stylesheet.sprite,
            glyphs: this.stylesheet.glyphs,
            transition: this.stylesheet.transition,
            projection: this.stylesheet.projection,
            sources: this._serializeSources(),
            layers: this._serializeLayers(this._order)
        }, value => {
            return value !== undefined;
        });
    }
    _updateLayer(layer) {
        this._changes.updateLayer(layer);
        const sourceCache = this.getLayerSourceCache(layer);
        const fqid = makeFQID(layer.source, layer.scope);
        if (layer.source && !this._changes.updatedSourceCaches[fqid] && //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865)
            sourceCache && sourceCache.getSource().type !== 'raster') {
            this._changes.updatedSourceCaches[fqid] = 'reload';
            sourceCache.pause();
        }
        this._changes.changed = true;
        layer.invalidateCompiledFilter();
    }
    _flattenAndSortRenderedFeatures(sourceResults) {
        // Feature order is complicated.
        // The order between features in two 2D layers is determined by layer order (subject to draped rendering modification).
        //  - if terrain/globe enabled layers are reordered in a drape-first, immediate-second manner
        //  - if terrain/globe disabled layers are not reordered
        // The order between features in two 3D layers is always determined by depth.
        // The order between a feature in a 2D layer and a 3D layer is tricky:
        //      Most often layer order determines the feature order in this case. If
        //      a line layer is above a extrusion layer the line feature will be rendered
        //      above the extrusion. If the line layer is below the extrusion layer,
        //      it will be rendered below it.
        //
        //      There is a weird case though.
        //      You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b
        //      Each layer has a feature that overlaps the other features.
        //      The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above.
        //      The feature in line_layer is rendered above extrusion_layer_a.
        //      This means that that the line_layer feature is above the extrusion_layer_b feature despite
        //      it being in an earlier layer.
        const isLayer3D = layerId => this._mergedLayers[layerId].type === 'fill-extrusion';
        const order = this.order;
        const layerIndex = {};
        const features3D = [];
        for (let l = order.length - 1; l >= 0; l--) {
            const layerId = order[l];
            if (isLayer3D(layerId)) {
                layerIndex[layerId] = l;
                for (const sourceResult of sourceResults) {
                    const layerFeatures = sourceResult[layerId];
                    if (layerFeatures) {
                        for (const featureWrapper of layerFeatures) {
                            features3D.push(featureWrapper);
                        }
                    }
                }
            }
        }
        features3D.sort((a, b) => {
            return b.intersectionZ - a.intersectionZ;
        });
        const features = [];
        for (let l = order.length - 1; l >= 0; l--) {
            const layerId = order[l];
            if (isLayer3D(layerId)) {
                // add all 3D features that are in or above the current layer
                for (let i = features3D.length - 1; i >= 0; i--) {
                    const topmost3D = features3D[i].feature;
                    if (layerIndex[topmost3D.layer.id] < l)
                        break;
                    features.push(topmost3D);
                    features3D.pop();
                }
            } else {
                for (const sourceResult of sourceResults) {
                    const layerFeatures = sourceResult[layerId];
                    if (layerFeatures) {
                        for (const featureWrapper of layerFeatures) {
                            features.push(featureWrapper.feature);
                        }
                    }
                }
            }
        }
        return features;
    }
    queryRenderedFeatures(queryGeometry, params, transform) {
        if (params && params.filter) {
            this._validate(validateFilter, 'queryRenderedFeatures.filter', params.filter, null, params);
        }
        params.scope = this.scope;
        params.availableImages = this._availableImages;
        params.serializedLayers = this._serializedLayers;
        const includedSources = {};
        if (params && params.layers) {
            if (!Array.isArray(params.layers)) {
                this.fire(new ErrorEvent(new Error('parameters.layers must be an Array.')));
                return [];
            }
            for (const layerId of params.layers) {
                const layer = this._mergedLayers[layerId];
                if (!layer) {
                    // this layer is not in the style.layers array
                    this.fire(new ErrorEvent(new Error(`The layer '${ layerId }' does not exist in the map's style and cannot be queried for features.`)));
                    return [];
                }
                includedSources[layer.source] = true;
            }
        }
        const sourceResults = [];
        const serializedLayers = params.serializedLayers || {};
        const has3DLayer = params && params.layers ? params.layers.some(layerId => {
            const layer = this.getLayer(layerId);
            return layer && layer.is3D();
        }) : this.has3DLayers();
        const queryGeometryStruct = QueryGeometry.createFromScreenPoints(queryGeometry, transform);
        for (const id in this._mergedSourceCaches) {
            const source = this._mergedSourceCaches[id].getSource();
            if (!source || source.scope !== params.scope)
                continue;
            const sourceId = this._mergedSourceCaches[id].getSource().id;
            if (params.layers && !includedSources[sourceId])
                continue;
            const showQueryGeometry = !!this.map._showQueryGeometry;
            sourceResults.push(queryRenderedFeatures(this._mergedSourceCaches[id], this._mergedLayers, serializedLayers, queryGeometryStruct, params, transform, has3DLayer, showQueryGeometry));
        }
        if (this.placement) {
            // If a placement has run, query against its CollisionIndex
            // for symbol results, and treat it as an extra source to merge
            sourceResults.push(queryRenderedSymbols(this._mergedLayers, serializedLayers, // $FlowFixMe[method-unbinding]
            this.getLayerSourceCache.bind(this), queryGeometryStruct.screenGeometry, params, this.placement.collisionIndex, this.placement.retainedQueryData));
        }
        return this._flattenAndSortRenderedFeatures(sourceResults);
    }
    querySourceFeatures(sourceID, params) {
        if (params && params.filter) {
            this._validate(validateFilter, 'querySourceFeatures.filter', params.filter, null, params);
        }
        const sourceCaches = this.getOwnSourceCaches(sourceID);
        let results = [];
        for (const sourceCache of sourceCaches) {
            results = results.concat(querySourceFeatures(sourceCache, params));
        }
        return results;
    }
    addSourceType(name, SourceType, callback) {
        if (Style.getSourceType(name)) {
            return callback(new Error(`A source type called "${ name }" already exists.`));
        }
        Style.setSourceType(name, SourceType);
        if (!SourceType.workerSourceURL) {
            return callback(null, null);
        }
        this.dispatcher.broadcast('loadWorkerSource', {
            name,
            url: SourceType.workerSourceURL
        }, callback);
    }
    getFlatLight() {
        return this.light.getLight();
    }
    setFlatLight(lightOptions, id, options = {}) {
        this._checkLoaded();
        const light = this.light.getLight();
        let _update = false;
        for (const key in lightOptions) {
            if (!deepEqual(lightOptions[key], light[key])) {
                _update = true;
                break;
            }
        }
        if (!_update)
            return;
        const parameters = this._getTransitionParameters();
        this.light.setLight(lightOptions, id, options);
        this.light.updateTransitions(parameters);
    }
    getTerrain() {
        return this.terrain && this.terrain.drapeRenderMode === DrapeRenderMode.elevated ? this.terrain.get() : null;
    }
    setTerrainForDraping() {
        const mockTerrainOptions = {
            source: '',
            exaggeration: 0
        };
        this.setTerrain(mockTerrainOptions, DrapeRenderMode.deferred);
    }
    // eslint-disable-next-line no-warning-comments
    // TODO: generic approach for root level property: light, terrain, skybox.
    // It is not done here to prevent rebasing issues.
    setTerrain(terrainOptions, drapeRenderMode = DrapeRenderMode.elevated) {
        this._checkLoaded();
        // Disabling
        if (!terrainOptions) {
            delete this.terrain;
            delete this.stylesheet.terrain;
            this._force3DLayerUpdate();
            this._markersNeedUpdate = true;
            return;
        }
        let options = terrainOptions;
        if (drapeRenderMode === DrapeRenderMode.elevated) {
            // Input validation and source object unrolling
            if (typeof options.source === 'object') {
                const id = 'terrain-dem-src';
                this.addSource(id, options.source);
                options = clone$9(options);
                options = extend$1(options, { source: id });
            }
            if (this._validate(validateTerrain, 'terrain', options)) {
                return;
            }
        }
        // Enabling
        if (!this.terrain || this.terrain && drapeRenderMode !== this.terrain.drapeRenderMode) {
            if (!options)
                return;
            this._createTerrain(options, drapeRenderMode);
            this.fire(new Event('data', { dataType: 'style' }));
        } else {
            // Updating
            const terrain = this.terrain;
            const currSpec = terrain.get();
            for (const name of Object.keys(spec.terrain)) {
                // Fallback to use default style specification when the properties wasn't set
                if (!options.hasOwnProperty(name) && !!spec.terrain[name].default) {
                    // $FlowFixMe[prop-missing]
                    options[name] = spec.terrain[name].default;
                }
            }
            for (const key in terrainOptions) {
                if (!deepEqual(terrainOptions[key], currSpec[key])) {
                    terrain.set(terrainOptions);
                    this.stylesheet.terrain = terrainOptions;
                    const parameters = this._getTransitionParameters({ duration: 0 });
                    terrain.updateTransitions(parameters);
                    this.fire(new Event('data', { dataType: 'style' }));
                    break;
                }
            }
        }
        this.mergeTerrain();
        this.updateDrapeFirstLayers();
        this._markersNeedUpdate = true;
    }
    _createFog(fogOptions) {
        const fog = this.fog = new Fog(fogOptions, this.map.transform);
        this.stylesheet.fog = fog.get();
        const parameters = this._getTransitionParameters({ duration: 0 });
        fog.updateTransitions(parameters);
    }
    _updateMarkersOpacity() {
        if (this.map._markers.length === 0) {
            return;
        }
        this.map._requestDomTask(() => {
            for (const marker of this.map._markers) {
                marker._evaluateOpacity();
            }
        });
    }
    getFog() {
        return this.fog ? this.fog.get() : null;
    }
    setFog(fogOptions) {
        this._checkLoaded();
        if (!fogOptions) {
            // Remove fog
            delete this.fog;
            delete this.stylesheet.fog;
            this._markersNeedUpdate = true;
            return;
        }
        if (!this.fog) {
            // Initialize Fog
            this._createFog(fogOptions);
        } else {
            // Updating fog
            const fog = this.fog;
            if (!deepEqual(fog.get(), fogOptions)) {
                fog.set(fogOptions);
                this.stylesheet.fog = fog.get();
                const parameters = this._getTransitionParameters({ duration: 0 });
                fog.updateTransitions(parameters);
            }
        }
        this._markersNeedUpdate = true;
    }
    _getTransitionParameters(transition) {
        return {
            now: exported$1.now(),
            transition: extend$1(this.transition, transition)
        };
    }
    updateDrapeFirstLayers() {
        if (!this.terrain) {
            return;
        }
        const draped = [];
        const nonDraped = [];
        for (const layerId in this._mergedLayers) {
            const layer = this._mergedLayers[layerId];
            if (this.isLayerDraped(layer)) {
                draped.push(layerId);
            } else {
                nonDraped.push(layerId);
            }
        }
        this._drapedFirstOrder = [];
        this._drapedFirstOrder.push(...draped);
        this._drapedFirstOrder.push(...nonDraped);
    }
    _createTerrain(terrainOptions, drapeRenderMode) {
        const terrain = this.terrain = new Terrain$1(terrainOptions, drapeRenderMode);
        terrain.setScope(this.scope);
        this.stylesheet.terrain = terrainOptions;
        this.mergeTerrain();
        this.updateDrapeFirstLayers();
        this._force3DLayerUpdate();
        const parameters = this._getTransitionParameters({ duration: 0 });
        terrain.updateTransitions(parameters);
    }
    _force3DLayerUpdate() {
        for (const layerId in this._layers) {
            const layer = this._layers[layerId];
            if (layer.type === 'fill-extrusion') {
                this._updateLayer(layer);
            }
        }
    }
    _forceSymbolLayerUpdate() {
        for (const layerId in this._layers) {
            const layer = this._layers[layerId];
            if (layer.type === 'symbol') {
                this._updateLayer(layer);
            }
        }
    }
    _validate(validate, key, value, props, options = {}) {
        if (options && options.validate === false) {
            return false;
        }
        // Fallback to the default glyphs URL if none is specified
        const style = extend$1({}, this.serialize());
        return emitValidationErrors(this, validate.call(validateStyle, extend$1({
            key,
            style,
            value,
            styleSpec: spec
        }, props)));
    }
    _remove() {
        if (this._request) {
            this._request.cancel();
            this._request = null;
        }
        if (this._spriteRequest) {
            this._spriteRequest.cancel();
            this._spriteRequest = null;
        }
        evented.off('pluginStateChange', this._rtlTextPluginCallback);
        for (const layerId in this._mergedLayers) {
            const layer = this._mergedLayers[layerId];
            layer.setEventedParent(null);
        }
        for (const id in this._mergedSourceCaches) {
            this._mergedSourceCaches[id].clearTiles();
            this._mergedSourceCaches[id].setEventedParent(null);
        }
        this.setEventedParent(null);
        delete this.fog;
        delete this.terrain;
        delete this.ambientLight;
        delete this.directionalLight;
        // Shared managers should be removed only on removing the root style
        if (this.isRootStyle()) {
            this.imageManager.setEventedParent(null);
            this.modelManager.setEventedParent(null);
            this.dispatcher.remove();
        }
    }
    clearSource(id) {
        const sourceCaches = this.getSourceCaches(id);
        for (const sourceCache of sourceCaches) {
            sourceCache.clearTiles();
        }
    }
    clearSources() {
        for (const id in this._mergedSourceCaches) {
            this._mergedSourceCaches[id].clearTiles();
        }
    }
    reloadSource(id) {
        const sourceCaches = this.getSourceCaches(id);
        for (const sourceCache of sourceCaches) {
            sourceCache.resume();
            sourceCache.reload();
        }
    }
    updateSources(transform) {
        let lightDirection;
        if (this.directionalLight) {
            lightDirection = shadowDirectionFromProperties(this.directionalLight);
        }
        for (const id in this._mergedSourceCaches) {
            this._mergedSourceCaches[id].update(transform, undefined, undefined, lightDirection);
        }
    }
    _generateCollisionBoxes() {
        for (const id in this._sourceCaches) {
            const sourceCache = this._sourceCaches[id];
            sourceCache.resume();
            sourceCache.reload();
        }
    }
    _updatePlacement(transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, forceFullPlacement = false) {
        let symbolBucketsChanged = false;
        let placementCommitted = false;
        const layerTiles = {};
        const layerTilesInYOrder = {};
        for (const layerId of this._mergedOrder) {
            const styleLayer = this._mergedLayers[layerId];
            if (styleLayer.type !== 'symbol')
                continue;
            const sourceId = makeFQID(styleLayer.source, styleLayer.scope);
            let sourceTiles = layerTiles[sourceId];
            if (!sourceTiles) {
                const sourceCache = this.getLayerSourceCache(styleLayer);
                if (!sourceCache)
                    continue;
                const tiles = sourceCache.getRenderableIds(true).map(id => sourceCache.getTileByID(id));
                layerTilesInYOrder[sourceId] = tiles.slice();
                sourceTiles = layerTiles[sourceId] = tiles.sort((a, b) => b.tileID.overscaledZ - a.tileID.overscaledZ || (a.tileID.isLessThan(b.tileID) ? -1 : 1));
            }
            const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, sourceTiles, transform.center.lng, transform.projection);
            symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged;
        }
        this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);
        // Anything that changes our "in progress" layer and tile indices requires us
        // to start over. When we start over, we do a full placement instead of incremental
        // to prevent starvation.
        // We need to restart placement to keep layer indices in sync.
        // Also force full placement when fadeDuration === 0 to ensure that newly loaded
        // tiles will fully display symbols in their first frame
        forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0;
        if (this._layerOrderChanged) {
            this.fire(new Event('neworder'));
        }
        if (forceFullPlacement || !this.pauseablePlacement || this.pauseablePlacement.isDone() && !this.placement.stillRecent(exported$1.now(), transform.zoom)) {
            const fogState = this.fog && transform.projection.supportsFog ? this.fog.state : null;
            this.pauseablePlacement = new PauseablePlacement(transform, this._mergedOrder, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement, fogState, this._buildingIndex);
            this._layerOrderChanged = false;
        }
        if (this.pauseablePlacement.isDone()) {
            // the last placement finished running, but the next one hasn’t
            // started yet because of the `stillRecent` check immediately
            // above, so mark it stale to ensure that we request another
            // render frame
            this.placement.setStale();
        } else {
            this.pauseablePlacement.continuePlacement(this._mergedOrder, this._mergedLayers, layerTiles, layerTilesInYOrder);
            if (this.pauseablePlacement.isDone()) {
                this.placement = this.pauseablePlacement.commit(exported$1.now());
                placementCommitted = true;
            }
            if (symbolBucketsChanged) {
                // since the placement gets split over multiple frames it is possible
                // these buckets were processed before they were changed and so the
                // placement is already stale while it is in progress
                this.pauseablePlacement.placement.setStale();
            }
        }
        if (placementCommitted || symbolBucketsChanged) {
            for (const layerId of this._mergedOrder) {
                const styleLayer = this._mergedLayers[layerId];
                if (styleLayer.type !== 'symbol')
                    continue;
                this.placement.updateLayerOpacities(styleLayer, layerTiles[makeFQID(styleLayer.source, styleLayer.scope)]);
            }
        }
        // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols
        const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(exported$1.now());
        return needsRerender;
    }
    _releaseSymbolFadeTiles() {
        for (const id in this._sourceCaches) {
            this._sourceCaches[id].releaseSymbolFadeTiles();
        }
    }
    // Fragments and merging
    addImport(importSpec) {
        this._checkLoaded();
        const imports = this.stylesheet.imports = this.stylesheet.imports || [];
        const index = imports.findIndex(({id}) => id === importSpec.id);
        if (index !== -1) {
            return this.fire(new ErrorEvent(new Error(`Import with id '${ importSpec.id }' already exists in the map's style.`)));
        }
        imports.push(importSpec);
        this._loadImports([importSpec], true);
        return this;
    }
    setImportUrl(importId, url) {
        this._checkLoaded();
        const imports = this.stylesheet.imports || [];
        const index = this.getImportIndex(importId);
        if (index === -1)
            return this;
        imports[index].url = url;
        // Update related fragment
        const fragment = this.fragments[index];
        fragment.style = this._createFragmentStyle({
            id: importId,
            url
        });
        const waitForStyle = new Promise(resolve => fragment.style.on('style.import.load', resolve));
        fragment.style.loadURL(url);
        waitForStyle.then(() => this._reloadImports());
        return this;
    }
    setImportData(importId, stylesheet) {
        this._checkLoaded();
        const index = this.getImportIndex(importId);
        const imports = this.stylesheet.imports || [];
        if (index === -1)
            return this;
        // Reload import from the URL if import data is unset
        if (!stylesheet) {
            delete imports[index].data;
            return this.setImportUrl(importId, imports[index].url);
        }
        // Update related fragment
        const fragment = this.fragments[index];
        fragment.style.setState(stylesheet);
        this._reloadImports();
        return this;
    }
    setImportConfig(importId, config) {
        this._checkLoaded();
        const index = this.getImportIndex(importId);
        const imports = this.stylesheet.imports || [];
        if (index === -1)
            return this;
        if (config) {
            imports[index].config = config;
        } else {
            delete imports[index].config;
        }
        // Update related fragment
        const fragment = this.fragments[index];
        const schema = fragment.style.stylesheet && fragment.style.stylesheet.schema;
        fragment.config = config;
        fragment.style.setConfig(config, schema);
        fragment.style.updateConfigDependencies();
        return this;
    }
    removeImport(importId) {
        this._checkLoaded();
        const imports = this.stylesheet.imports || [];
        const index = this.getImportIndex(importId);
        if (index === -1)
            return this;
        imports.splice(index, 1);
        // Update related fragment
        const fragment = this.fragments[index];
        fragment.style._remove();
        this.fragments.splice(index, 1);
        this._reloadImports();
        return this;
    }
    getImportIndex(importId) {
        const imports = this.stylesheet.imports || [];
        const index = imports.findIndex(importSpec => importSpec.id === importId);
        if (index === -1) {
            this.fire(new ErrorEvent(new Error(`Import '${ importId }' does not exist in the map's style and cannot be updated.`)));
        }
        return index;
    }
    /**
     * Return the style layer object with the given `id`.
     *
     * @param {string} id ID of the desired layer.
     * @returns {?StyleLayer} A layer, if one with the given `id` exists.
     */
    getLayer(id) {
        return this._mergedLayers[id];
    }
    getSources() {
        const sources = [];
        for (const id in this._mergedOtherSourceCaches) {
            const sourceCache = this._mergedOtherSourceCaches[id];
            if (sourceCache)
                sources.push(sourceCache.getSource());
        }
        return sources;
    }
    /**
     * Get a source by ID.
     * @param {string} id ID of the desired source.
     * @returns {?Source} The source object.
     */
    getSource(id, scope) {
        const sourceCache = this.getSourceCache(id, scope);
        return sourceCache && sourceCache.getSource();
    }
    getLayerSource(layer) {
        const sourceCache = this.getLayerSourceCache(layer);
        return sourceCache && sourceCache.getSource();
    }
    getSourceCache(id, scope) {
        const fqid = makeFQID(id, scope);
        return this._mergedOtherSourceCaches[fqid];
    }
    getLayerSourceCache(layer) {
        const fqid = makeFQID(layer.source, layer.scope);
        return layer.type === 'symbol' ? this._mergedSymbolSourceCaches[fqid] : this._mergedOtherSourceCaches[fqid];
    }
    getSourceCaches(fqid) {
        const sourceCaches = [];
        if (this._mergedOtherSourceCaches[fqid]) {
            sourceCaches.push(this._mergedOtherSourceCaches[fqid]);
        }
        if (this._mergedSymbolSourceCaches[fqid]) {
            sourceCaches.push(this._mergedSymbolSourceCaches[fqid]);
        }
        return sourceCaches;
    }
    updateSourceCaches() {
        for (const fqid in this._changes.updatedSourceCaches) {
            const action = this._changes.updatedSourceCaches[fqid];
            if (action === 'reload') {
                this.reloadSource(fqid);
            } else if (action === 'clear') {
                this.clearSource(fqid);
            }
        }
    }
    updateLayers(parameters) {
        for (const id of this._changes.updatedPaintProps) {
            const layer = this.getLayer(id);
            if (layer)
                layer.updateTransitions(parameters);
        }
    }
    // Callbacks from web workers
    getImages(mapId, params, callback) {
        this.imageManager.getImages(params.icons, params.scope, callback);
        // Apply queued image changes before setting the tile's dependencies so that the tile
        // is not reloaded unecessarily. Without this forced update the reload could happen in cases
        // like this one:
        // - icons contains "my-image"
        // - imageManager.getImages(...) triggers `onstyleimagemissing`
        // - the user adds "my-image" within the callback
        // - addImage adds "my-image" to this._changes.changedImages
        // - the next frame triggers a reload of this tile even though it already has the latest version
        this._updateTilesForChangedImages();
        const setDependencies = sourceCache => {
            if (sourceCache) {
                sourceCache.setDependencies(params.tileID.key, params.type, params.icons);
            }
        };
        setDependencies(this._otherSourceCaches[params.source]);
        setDependencies(this._symbolSourceCaches[params.source]);
    }
    getGlyphs(mapId, params, callback) {
        this.glyphManager.getGlyphs(params.stacks, params.scope, callback);
    }
    getResource(mapId, params, callback) {
        return makeRequest(params, callback);
    }
    getOwnSourceCache(source) {
        return this._otherSourceCaches[source];
    }
    getOwnLayerSourceCache(layer) {
        return layer.type === 'symbol' ? this._symbolSourceCaches[layer.source] : this._otherSourceCaches[layer.source];
    }
    getOwnSourceCaches(source) {
        const sourceCaches = [];
        if (this._otherSourceCaches[source]) {
            sourceCaches.push(this._otherSourceCaches[source]);
        }
        if (this._symbolSourceCaches[source]) {
            sourceCaches.push(this._symbolSourceCaches[source]);
        }
        return sourceCaches;
    }
    _isSourceCacheLoaded(source) {
        const sourceCaches = this.getOwnSourceCaches(source);
        if (sourceCaches.length === 0) {
            this.fire(new ErrorEvent(new Error(`There is no source with ID '${ source }'`)));
            return false;
        }
        return sourceCaches.every(sc => sc.loaded());
    }
    has3DLayers() {
        return this._has3DLayers;
    }
    hasSymbolLayers() {
        return this._hasSymbolLayers;
    }
    hasCircleLayers() {
        return this._hasCircleLayers;
    }
    _clearWorkerCaches() {
        this.dispatcher.broadcast('clearCaches');
    }
    destroy() {
        this._clearWorkerCaches();
        if (this.terrainSetForDrapingOnly()) {
            delete this.terrain;
            delete this.stylesheet.terrain;
        }
    }
}
Style.getSourceType = getType;
Style.setSourceType = setType;
Style.registerForPluginStateChange = registerForPluginStateChange;

//       strict
/**
 * Throttle the given function to run at most every `period` milliseconds.
 * @private
 */
function throttle(fn, time) {
    let pending = false;
    let timerId = null;
    const later = () => {
        timerId = null;
        if (pending) {
            fn();
            timerId = setTimeout(later, time);
            pending = false;
        }
    };
    return () => {
        pending = true;
        if (!timerId) {
            later();
        }
        return timerId;
    };
}

//      
/*
 * Adds the map's position to its page's location hash.
 * Passed as an option to the map object.
 *
 * @returns {Hash} `this`
 */
class Hash {
    constructor(hashName) {
        this._hashName = hashName && encodeURIComponent(hashName);
        bindAll([
            '_getCurrentHash',
            '_onHashChange',
            '_updateHash'
        ], this);
        // Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds.
        // $FlowFixMe[method-unbinding]
        this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 30 * 1000 / 100);
    }
    /*
     * Map element to listen for coordinate changes
     *
     * @param {Object} map
     * @returns {Hash} `this`
     */
    addTo(map) {
        this._map = map;
        // $FlowFixMe[method-unbinding]
        window$1.addEventListener('hashchange', this._onHashChange, false);
        map.on('moveend', this._updateHash);
        return this;
    }
    /*
     * Removes hash
     *
     * @returns {Popup} `this`
     */
    remove() {
        if (!this._map)
            return this;
        this._map.off('moveend', this._updateHash);
        // $FlowFixMe[method-unbinding]
        window$1.removeEventListener('hashchange', this._onHashChange, false);
        clearTimeout(this._updateHash());
        this._map = undefined;
        return this;
    }
    getHashString() {
        const map = this._map;
        if (!map)
            return '';
        const hash = getHashString(map);
        if (this._hashName) {
            const hashName = this._hashName;
            let found = false;
            const parts = window$1.location.hash.slice(1).split('&').map(part => {
                const key = part.split('=')[0];
                if (key === hashName) {
                    found = true;
                    return `${ key }=${ hash }`;
                }
                return part;
            }).filter(a => a);
            if (!found) {
                parts.push(`${ hashName }=${ hash }`);
            }
            return `#${ parts.join('&') }`;
        }
        return `#${ hash }`;
    }
    _getCurrentHash() {
        // Get the current hash from location, stripped from its number sign
        const hash = window$1.location.hash.replace('#', '');
        if (this._hashName) {
            // Split the parameter-styled hash into parts and find the value we need
            let keyval;
            hash.split('&').map(part => part.split('=')).forEach(part => {
                if (part[0] === this._hashName) {
                    keyval = part;
                }
            });
            return (keyval ? keyval[1] || '' : '').split('/');
        }
        return hash.split('/');
    }
    _onHashChange() {
        const map = this._map;
        if (!map)
            return false;
        const loc = this._getCurrentHash();
        if (loc.length >= 3 && !loc.some(v => isNaN(v))) {
            const bearing = map.dragRotate.isEnabled() && map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : map.getBearing();
            map.jumpTo({
                center: [
                    +loc[2],
                    +loc[1]
                ],
                zoom: +loc[0],
                bearing,
                pitch: +(loc[4] || 0)
            });
            return true;
        }
        return false;
    }
    _updateHashUnthrottled() {
        // Replace if already present, else append the updated hash string
        const location = window$1.location.href.replace(/(#.+)?$/, this.getHashString());
        window$1.history.replaceState(window$1.history.state, null, location);
    }
}
function getHashString(map, mapFeedback) {
    const center = map.getCenter(), zoom = Math.round(map.getZoom() * 100) / 100,
        // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px
        precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), m = Math.pow(10, precision), lng = Math.round(center.lng * m) / m, lat = Math.round(center.lat * m) / m, bearing = map.getBearing(), pitch = map.getPitch();
    // new map feedback site has some constraints that don't allow
    // us to use the same hash format as we do for the Map hash option.
    let hash = mapFeedback ? `/${ lng }/${ lat }/${ zoom }` : `${ zoom }/${ lat }/${ lng }`;
    if (bearing || pitch)
        hash += `/${ Math.round(bearing * 10) / 10 }`;
    if (pitch)
        hash += `/${ Math.round(pitch) }`;
    return hash;
}

//      
const defaultInertiaOptions = {
    linearity: 0.3,
    easing: bezier$1(0, 0, 0.3, 1)
};
const defaultPanInertiaOptions = extend$1({
    deceleration: 2500,
    maxSpeed: 1400
}, defaultInertiaOptions);
const defaultZoomInertiaOptions = extend$1({
    deceleration: 20,
    maxSpeed: 1400
}, defaultInertiaOptions);
const defaultBearingInertiaOptions = extend$1({
    deceleration: 1000,
    maxSpeed: 360
}, defaultInertiaOptions);
const defaultPitchInertiaOptions = extend$1({
    deceleration: 1000,
    maxSpeed: 90
}, defaultInertiaOptions);
class HandlerInertia {
    constructor(map) {
        this._map = map;
        this.clear();
    }
    clear() {
        this._inertiaBuffer = [];
    }
    record(settings) {
        this._drainInertiaBuffer();
        this._inertiaBuffer.push({
            time: exported$1.now(),
            settings
        });
    }
    _drainInertiaBuffer() {
        const inertia = this._inertiaBuffer, now = exported$1.now(), cutoff = 160;
        //msec
        while (inertia.length > 0 && now - inertia[0].time > cutoff)
            inertia.shift();
    }
    _onMoveEnd(panInertiaOptions) {
        if (this._map._prefersReducedMotion()) {
            return;
        }
        this._drainInertiaBuffer();
        if (this._inertiaBuffer.length < 2) {
            return;
        }
        const deltas = {
            zoom: 0,
            bearing: 0,
            pitch: 0,
            pan: new Point$2(0, 0),
            pinchAround: undefined,
            around: undefined
        };
        for (const {settings} of this._inertiaBuffer) {
            deltas.zoom += settings.zoomDelta || 0;
            deltas.bearing += settings.bearingDelta || 0;
            deltas.pitch += settings.pitchDelta || 0;
            if (settings.panDelta)
                deltas.pan._add(settings.panDelta);
            if (settings.around)
                deltas.around = settings.around;
            if (settings.pinchAround)
                deltas.pinchAround = settings.pinchAround;
        }
        const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1];
        const duration = lastEntry.time - this._inertiaBuffer[0].time;
        const easeOptions = {};
        if (deltas.pan.mag()) {
            const result = calculateEasing(deltas.pan.mag(), duration, extend$1({}, defaultPanInertiaOptions, panInertiaOptions || {}));
            easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag());
            easeOptions.center = this._map.transform.center;
            extendDuration(easeOptions, result);
        }
        if (deltas.zoom) {
            const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);
            easeOptions.zoom = this._map.transform.zoom + result.amount;
            extendDuration(easeOptions, result);
        }
        if (deltas.bearing) {
            const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);
            easeOptions.bearing = this._map.transform.bearing + clamp(result.amount, -179, 179);
            extendDuration(easeOptions, result);
        }
        if (deltas.pitch) {
            const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions);
            easeOptions.pitch = this._map.transform.pitch + result.amount;
            extendDuration(easeOptions, result);
        }
        if (easeOptions.zoom || easeOptions.bearing) {
            const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround;
            easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();
        }
        this.clear();
        easeOptions.noMoveStart = true;
        return easeOptions;
    }
}
// Unfortunately zoom, bearing, etc can't have different durations and easings so
// we need to choose one. We use the longest duration and it's corresponding easing.
function extendDuration(easeOptions, result) {
    if (!easeOptions.duration || easeOptions.duration < result.duration) {
        easeOptions.duration = result.duration;
        easeOptions.easing = result.easing;
    }
}
function calculateEasing(amount, inertiaDuration, inertiaOptions) {
    const {maxSpeed, linearity, deceleration} = inertiaOptions;
    const speed = clamp(amount * linearity / (inertiaDuration / 1000), -maxSpeed, maxSpeed);
    const duration = Math.abs(speed) / (deceleration * linearity);
    return {
        easing: inertiaOptions.easing,
        duration: duration * 1000,
        amount: speed * (duration / 2)
    };
}

//      
/**
 * `MapMouseEvent` is a class used by other classes to generate
 * mouse events of specific types such as 'click' or 'hover'.
 * For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 *
 * @extends {Object}
 * @example
 * // Example of a MapMouseEvent of type "click"
 * map.on('click', (e) => {
 *     console.log(e);
 *     // {
 *     //     lngLat: {
 *     //         lng: 40.203,
 *     //         lat: -74.451
 *     //     },
 *     //     originalEvent: {...},
 *     //     point: {
 *     //         x: 266,
 *     //         y: 464
 *     //     },
 *     //      target: {...},
 *     //      type: "click"
 *     // }
 * });
 * @see [Reference: `Map` events API documentation](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events)
 * @see [Example: Display popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)
 * @see [Example: Display popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
 */
class MapMouseEvent extends Event {
    /**
     * The type of originating event. For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
     */
    /**
     * The `Map` object that fired the event.
     */
    /**
     * The DOM event which caused the map event.
     */
    /**
     * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.
     */
    /**
     * The geographic location on the map of the mouse cursor.
     */
    /**
     * If a single `layerId`(as a single string) or multiple `layerIds` (as an array of strings) were specified when adding the event listener with {@link Map#on},
     * `features` will be an array of [GeoJSON](http://geojson.org/) [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
     * The array will contain all features from that layer that are rendered at the event's point,
     * in the order that they are rendered with the topmost feature being at the start of the array.
     * The `features` are identical to those returned by {@link Map#queryRenderedFeatures}.
     *
     * If no `layerId` was specified when adding the event listener, `features` will be `undefined`.
     * You can get the features at the point with `map.queryRenderedFeatures(e.point)`.
     *
     * @example
     * // logging features for a specific layer (with `e.features`)
     * map.on('click', 'myLayerId', (e) => {
     *     console.log(`There are ${e.features.length} features at point ${e.point}`);
     * });
     *
     * @example
     * // logging features for two layers (with `e.features`)
     * map.on('click', ['layer1', 'layer2'], (e) => {
     *     console.log(`There are ${e.features.length} features at point ${e.point}`);
     * });
     *
     * @example
     * // logging all features for all layers (without `e.features`)
     * map.on('click', (e) => {
     *     const features = map.queryRenderedFeatures(e.point);
     *     console.log(`There are ${features.length} features at point ${e.point}`);
     * });
     */
    /**
     * Prevents subsequent default processing of the event by the map.
     *
     * Calling this method will prevent the following default map behaviors:
     *
     *   * On `mousedown` events, the behavior of {@link DragPanHandler}.
     *   * On `mousedown` events, the behavior of {@link DragRotateHandler}.
     *   * On `mousedown` events, the behavior of {@link BoxZoomHandler}.
     *   * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler}.
     *
     * @example
     * map.on('click', (e) => {
     *     e.preventDefault();
     * });
     */
    preventDefault() {
        this._defaultPrevented = true;
    }
    /**
     * `true` if `preventDefault` has been called.
     * @private
     */
    get defaultPrevented() {
        return this._defaultPrevented;
    }
    /**
     * @private
     */
    constructor(type, map, originalEvent, data = {}) {
        const point = mousePos(map.getCanvasContainer(), originalEvent);
        const lngLat = map.unproject(point);
        super(type, extend$1({
            point,
            lngLat,
            originalEvent
        }, data));
        this._defaultPrevented = false;
        this.target = map;
    }
}
/**
 * `MapTouchEvent` is a class used by other classes to generate
 * mouse events of specific types such as 'touchstart' or 'touchend'.
 * For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 *
 * @extends {Object}
 *
 * @example
 * // Example of a MapTouchEvent of type "touch"
 * map.on('touchstart', (e) => {
 *     console.log(e);
 *     // {
 *     //   lngLat: {
 *     //      lng: 40.203,
 *     //      lat: -74.451
 *     //   },
 *     //   lngLats: [
 *     //      {
 *     //         lng: 40.203,
 *     //         lat: -74.451
 *     //      }
 *     //   ],
 *     //   originalEvent: {...},
 *     //   point: {
 *     //      x: 266,
 *     //      y: 464
 *     //   },
 *     //   points: [
 *     //      {
 *     //         x: 266,
 *     //         y: 464
 *     //      }
 *     //   ]
 *     //   preventDefault(),
 *     //   target: {...},
 *     //   type: "touchstart"
 *     // }
 * });
 * @see [Reference: `Map` events API documentation](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events)
 * @see [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
 */
class MapTouchEvent extends Event {
    /**
     * The type of originating event. For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
     */
    /**
     * The `Map` object that fired the event.
     */
    /**
     * The DOM event which caused the map event.
     */
    /**
     * The geographic location on the map of the center of the touch event points.
     */
    /**
     * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left
     * corner.
     */
    /**
     * The array of pixel coordinates corresponding to a
     * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.
     */
    /**
     * The geographical locations on the map corresponding to a
     * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.
     */
    /**
     * If a `layerId` was specified when adding the event listener with {@link Map#on}, `features` will be an array of
     * [GeoJSON](http://geojson.org/) [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
     * The array will contain all features from that layer that are rendered at the event's point.
     * The `features` are identical to those returned by {@link Map#queryRenderedFeatures}.
     *
     * If no `layerId` was specified when adding the event listener, `features` will be `undefined`.
     * You can get the features at the point with `map.queryRenderedFeatures(e.point)`.
     *
     * @example
     * // logging features for a specific layer (with `e.features`)
     * map.on('touchstart', 'myLayerId', (e) => {
     *     console.log(`There are ${e.features.length} features at point ${e.point}`);
     * });
     *
     * @example
     * // logging all features for all layers (without `e.features`)
     * map.on('touchstart', (e) => {
     *     const features = map.queryRenderedFeatures(e.point);
     *     console.log(`There are ${features.length} features at point ${e.point}`);
     * });
     */
    /**
     * Prevents subsequent default processing of the event by the map.
     *
     * Calling this method will prevent the following default map behaviors:
     *
     *   * On `touchstart` events, the behavior of {@link DragPanHandler}.
     *   * On `touchstart` events, the behavior of {@link TouchZoomRotateHandler}.
     *
     * @example
     * map.on('touchstart', (e) => {
     *     e.preventDefault();
     * });
     */
    preventDefault() {
        this._defaultPrevented = true;
    }
    /**
     * Returns `true` if `preventDefault` has been called.
     * @private
     */
    get defaultPrevented() {
        return this._defaultPrevented;
    }
    /**
     * @private
     */
    constructor(type, map, originalEvent) {
        const touches = type === 'touchend' ? originalEvent.changedTouches : originalEvent.touches;
        const points = touchPos(map.getCanvasContainer(), touches);
        const lngLats = points.map(t => map.unproject(t));
        const point = points.reduce((prev, curr, i, arr) => {
            return prev.add(curr.div(arr.length));
        }, new Point$2(0, 0));
        const lngLat = map.unproject(point);
        super(type, {
            points,
            point,
            lngLats,
            lngLat,
            originalEvent
        });
        this._defaultPrevented = false;
    }
}
/**
 * `MapWheelEvent` is a class used by other classes to generate
 * mouse events of specific types such as 'wheel'.
 * For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 *
 * @extends {Object}
 * @example
 * // Example event trigger for a MapWheelEvent of type "wheel"
 * map.on('wheel', (e) => {
 *     console.log('event type:', e.type);
 *     // event type: wheel
 * });
 * @example
 * // Example of a MapWheelEvent of type "wheel"
 * // {
 * //   originalEvent: WheelEvent {...},
 * // 	 target: Map {...},
 * // 	 type: "wheel"
 * // }
 * @see [Reference: `Map` events API documentation](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events)
 */
class MapWheelEvent extends Event {
    /**
     * The type of originating event. For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
     */
    /**
     * The `Map` object that fired the event.
     */
    /**
     * The DOM event which caused the map event.
     */
    /**
     * Prevents subsequent default processing of the event by the map.
     * Calling this method will prevent the the behavior of {@link ScrollZoomHandler}.
     *
     * @example
     * map.on('wheel', (e) => {
     *     // Prevent the default map scroll zoom behavior.
     *     e.preventDefault();
     * });
     */
    preventDefault() {
        this._defaultPrevented = true;
    }
    /**
     * `true` if `preventDefault` has been called.
     * @private
     */
    get defaultPrevented() {
        return this._defaultPrevented;
    }
    /**
     * @private
     */
    constructor(type, map, originalEvent) {
        super(type, { originalEvent });
        this._defaultPrevented = false;
    }
}    /**
 * `MapBoxZoomEvent` is a class used to generate
 * the events 'boxzoomstart', 'boxzoomend', and 'boxzoomcancel'.
 * For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 *
 * @typedef {Object} MapBoxZoomEvent
 * @property {MouseEvent} originalEvent The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent`.
 * @property {('boxzoomstart' | 'boxzoomend' | 'boxzoomcancel')} type The type of originating event. For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 * @property {Map} target The `Map` instance that triggered the event.
 * @example
 * // Example trigger of a BoxZoomEvent of type "boxzoomstart"
 * map.on('boxzoomstart', (e) => {
 *     console.log('event type:', e.type);
 *     // event type: boxzoomstart
 * });
 * @example
 * // Example of a BoxZoomEvent of type "boxzoomstart"
 * // {
 * //   originalEvent: {...},
 * //   type: "boxzoomstart",
 * //   target: {...}
 * // }
 * @see [Reference: `Map` events API documentation](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events)
 * @see [Example: Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
 */
     /**
 * `MapDataEvent` is a class used to generate
 * events related to loading data, styles, and sources.
 * For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 *
 * @typedef {Object} MapDataEvent
 * @property {('data' | 'dataloading' | 'styledata' | 'styledataloading' | 'sourcedata'| 'sourcedataloading')} type The type of originating event. For a full list of available events, see [`Map` events](/mapbox-gl-js/api/map/#map-events).
 * @property {('source' | 'style')} dataType The type of data that has changed. One of `'source'` or `'style'`, where `'source'` refers to the data associated with any source, and `'style'` refers to the entire [style](https://docs.mapbox.com/help/glossary/style/) used by the map.
 * @property {boolean} [isSourceLoaded] True if the event has a `dataType` of `source` and the source has no outstanding network requests.
 * @property {Object} [source] The [style spec representation of the source](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) if the event has a `dataType` of `source`.
 * @property {string} [sourceId] The `id` of the [`source`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) that triggered the event, if the event has a `dataType` of `source`. Same as the `id` of the object in the `source` property.
 * @property {string} [sourceDataType] Included if the event has a `dataType` of `source` and the event signals
 *     that internal data has been received or changed. Possible values are `metadata`, `content` and `visibility`.
 * @property {Object} [tile] The tile being loaded or changed, if the event has a `dataType` of `source` and
 *     the event is related to loading of a tile.
 * @property {Coordinate} [coord] The coordinate of the tile if the event has a `dataType` of `source` and
 *     the event is related to loading of a tile.
 * @example
 * // Example of a MapDataEvent of type "sourcedata"
 * map.on('sourcedata', (e) => {
 *     console.log(e);
 *     // {
 *     //   dataType: "source",
 *     //   isSourceLoaded: false,
 *     //   source: {
 *     //     type: "vector",
 *     //     url: "mapbox://mapbox.mapbox-streets-v8,mapbox.mapbox-terrain-v2"
 *     //   },
 *     //   sourceDataType: "visibility",
 *     //   sourceId: "composite",
 *     //   style: {...},
 *     //   target: {...},
 *     //   type: "sourcedata"
 *     // }
 * });
 * @see [Reference: `Map` events API documentation](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events)
 * @see [Example: Change a map's style](https://docs.mapbox.com/mapbox-gl-js/example/setstyle/)
 * @see [Example: Add a GeoJSON line](https://docs.mapbox.com/mapbox-gl-js/example/geojson-line/)
 */

//      
class MapEventHandler {
    constructor(map, options) {
        this._map = map;
        this._clickTolerance = options.clickTolerance;
    }
    reset() {
        this._mousedownPos = undefined;
    }
    wheel(e) {
        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:
        // - ScrollZoom
        return this._firePreventable(new MapWheelEvent(e.type, this._map, e));
    }
    mousedown(e, point) {
        this._mousedownPos = point;
        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:
        // - MousePan
        // - MouseRotate
        // - MousePitch
        // - DblclickHandler
        return this._firePreventable(new MapMouseEvent(e.type, this._map, e));
    }
    mouseup(e) {
        this._map.fire(new MapMouseEvent(e.type, this._map, e));
    }
    preclick(e) {
        const synth = extend$1({}, e);
        synth.type = 'preclick';
        this._map.fire(new MapMouseEvent(synth.type, this._map, synth));
    }
    click(e, point) {
        if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance)
            return;
        this.preclick(e);
        this._map.fire(new MapMouseEvent(e.type, this._map, e));
    }
    dblclick(e) {
        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:
        // - DblClickZoom
        return this._firePreventable(new MapMouseEvent(e.type, this._map, e));
    }
    mouseover(e) {
        this._map.fire(new MapMouseEvent(e.type, this._map, e));
    }
    mouseout(e) {
        this._map.fire(new MapMouseEvent(e.type, this._map, e));
    }
    touchstart(e) {
        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:
        // - TouchPan
        // - TouchZoom
        // - TouchRotate
        // - TouchPitch
        // - TapZoom
        // - SwipeZoom
        return this._firePreventable(new MapTouchEvent(e.type, this._map, e));
    }
    touchmove(e) {
        this._map.fire(new MapTouchEvent(e.type, this._map, e));
    }
    touchend(e) {
        this._map.fire(new MapTouchEvent(e.type, this._map, e));
    }
    touchcancel(e) {
        this._map.fire(new MapTouchEvent(e.type, this._map, e));
    }
    _firePreventable(mapEvent) {
        this._map.fire(mapEvent);
        if (mapEvent.defaultPrevented) {
            // returning an object marks the handler as active and resets other handlers
            return {};
        }
    }
    isEnabled() {
        return true;
    }
    isActive() {
        return false;
    }
    enable() {
    }
    disable() {
    }
}
class BlockableMapEventHandler {
    constructor(map) {
        this._map = map;
    }
    reset() {
        this._delayContextMenu = false;
        this._contextMenuEvent = undefined;
    }
    mousemove(e) {
        // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active
        this._map.fire(new MapMouseEvent(e.type, this._map, e));
    }
    mousedown() {
        this._delayContextMenu = true;
    }
    mouseup() {
        this._delayContextMenu = false;
        if (this._contextMenuEvent) {
            this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent));
            delete this._contextMenuEvent;
        }
    }
    contextmenu(e) {
        if (this._delayContextMenu) {
            // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake
            this._contextMenuEvent = e;
        } else {
            // Windows: contextmenu fired on mouseup, so fire event now
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
        }
        // prevent browser context menu when necessary
        if (this._map.listens('contextmenu')) {
            e.preventDefault();
        }
    }
    isEnabled() {
        return true;
    }
    isActive() {
        return false;
    }
    enable() {
    }
    disable() {
    }
}

//      
/**
 * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box.
 * The bounding box is defined by clicking and holding `shift` while dragging the cursor.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 * @see [Example: Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
 */
class BoxZoomHandler {
    /**
     * @private
     */
    constructor(map, options) {
        this._map = map;
        this._el = map.getCanvasContainer();
        this._container = map.getContainer();
        this._clickTolerance = options.clickTolerance || 1;
    }
    /**
     * Returns a Boolean indicating whether the "box zoom" interaction is enabled.
     *
     * @returns {boolean} Returns `true` if the "box zoom" interaction is enabled.
     * @example
     * const isBoxZoomEnabled = map.boxZoom.isEnabled();
     */
    isEnabled() {
        return !!this._enabled;
    }
    /**
     * Returns a Boolean indicating whether the "box zoom" interaction is active (currently being used).
     *
     * @returns {boolean} Returns `true` if the "box zoom" interaction is active.
     * @example
     * const isBoxZoomActive = map.boxZoom.isActive();
     */
    isActive() {
        return !!this._active;
    }
    /**
     * Enables the "box zoom" interaction.
     *
     * @example
     * map.boxZoom.enable();
     */
    enable() {
        if (this.isEnabled())
            return;
        this._enabled = true;
    }
    /**
     * Disables the "box zoom" interaction.
     *
     * @example
     * map.boxZoom.disable();
     */
    disable() {
        if (!this.isEnabled())
            return;
        this._enabled = false;
    }
    mousedown(e, point) {
        if (!this.isEnabled())
            return;
        if (!(e.shiftKey && e.button === 0))
            return;
        disableDrag();
        this._startPos = this._lastPos = point;
        this._active = true;
    }
    mousemoveWindow(e, point) {
        if (!this._active)
            return;
        const pos = point;
        const p0 = this._startPos;
        const p1 = this._lastPos;
        if (!p0 || !p1 || p1.equals(pos) || !this._box && pos.dist(p0) < this._clickTolerance) {
            return;
        }
        this._lastPos = pos;
        if (!this._box) {
            this._box = create$a('div', 'mapboxgl-boxzoom', this._container);
            this._container.classList.add('mapboxgl-crosshair');
            this._fireEvent('boxzoomstart', e);
        }
        const minX = Math.min(p0.x, pos.x), maxX = Math.max(p0.x, pos.x), minY = Math.min(p0.y, pos.y), maxY = Math.max(p0.y, pos.y);
        this._map._requestDomTask(() => {
            if (this._box) {
                this._box.style.transform = `translate(${ minX }px,${ minY }px)`;
                this._box.style.width = `${ maxX - minX }px`;
                this._box.style.height = `${ maxY - minY }px`;
            }
        });
    }
    mouseupWindow(e, point) {
        if (!this._active)
            return;
        const p0 = this._startPos, p1 = point;
        if (!p0 || e.button !== 0)
            return;
        this.reset();
        suppressClick();
        if (p0.x === p1.x && p0.y === p1.y) {
            this._fireEvent('boxzoomcancel', e);
        } else {
            this._map.fire(new Event('boxzoomend', { originalEvent: e }));
            return { cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._map.getBearing(), { linear: false }) };
        }
    }
    keydown(e) {
        if (!this._active)
            return;
        if (e.keyCode === 27) {
            this.reset();
            this._fireEvent('boxzoomcancel', e);
        }
    }
    blur() {
        this.reset();
    }
    reset() {
        this._active = false;
        this._container.classList.remove('mapboxgl-crosshair');
        if (this._box) {
            this._box.remove();
            this._box = null;
        }
        enableDrag();
        delete this._startPos;
        delete this._lastPos;
    }
    _fireEvent(type, e) {
        return this._map.fire(new Event(type, { originalEvent: e }));
    }
}

function indexTouches(touches, points) {
    const obj = {};
    for (let i = 0; i < touches.length; i++) {
        obj[touches[i].identifier] = points[i];
    }
    return obj;
}

//      
function getCentroid(points) {
    const sum = new Point$2(0, 0);
    for (const point of points) {
        sum._add(point);
    }
    return sum.div(points.length);
}
const MAX_TAP_INTERVAL = 500;
const MAX_TOUCH_TIME = 500;
const MAX_DIST = 30;
class SingleTapRecognizer {
    constructor(options) {
        this.reset();
        this.numTouches = options.numTouches;
    }
    reset() {
        this.centroid = undefined;
        this.startTime = 0;
        this.touches = {};
        this.aborted = false;
    }
    touchstart(e, points, mapTouches) {
        if (this.centroid || mapTouches.length > this.numTouches) {
            this.aborted = true;
        }
        if (this.aborted) {
            return;
        }
        if (this.startTime === 0) {
            this.startTime = e.timeStamp;
        }
        if (mapTouches.length === this.numTouches) {
            this.centroid = getCentroid(points);
            this.touches = indexTouches(mapTouches, points);
        }
    }
    touchmove(e, points, mapTouches) {
        if (this.aborted || !this.centroid)
            return;
        const newTouches = indexTouches(mapTouches, points);
        for (const id in this.touches) {
            const prevPos = this.touches[id];
            const pos = newTouches[id];
            if (!pos || pos.dist(prevPos) > MAX_DIST) {
                this.aborted = true;
            }
        }
    }
    touchend(e, points, mapTouches) {
        if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) {
            this.aborted = true;
        }
        if (mapTouches.length === 0) {
            const centroid = !this.aborted && this.centroid;
            this.reset();
            if (centroid)
                return centroid;
        }
    }
}
class TapRecognizer {
    constructor(options) {
        this.singleTap = new SingleTapRecognizer(options);
        this.numTaps = options.numTaps;
        this.reset();
    }
    reset() {
        this.lastTime = Infinity;
        this.lastTap = undefined;
        this.count = 0;
        this.singleTap.reset();
    }
    touchstart(e, points, mapTouches) {
        this.singleTap.touchstart(e, points, mapTouches);
    }
    touchmove(e, points, mapTouches) {
        this.singleTap.touchmove(e, points, mapTouches);
    }
    touchend(e, points, mapTouches) {
        const tap = this.singleTap.touchend(e, points, mapTouches);
        if (tap) {
            const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL;
            const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST;
            if (!soonEnough || !closeEnough) {
                this.reset();
            }
            this.count++;
            this.lastTime = e.timeStamp;
            this.lastTap = tap;
            if (this.count === this.numTaps) {
                this.reset();
                return tap;
            }
        }
    }
}

//      
class TapZoomHandler {
    constructor() {
        this._zoomIn = new TapRecognizer({
            numTouches: 1,
            numTaps: 2
        });
        this._zoomOut = new TapRecognizer({
            numTouches: 2,
            numTaps: 1
        });
        this.reset();
    }
    reset() {
        this._active = false;
        this._zoomIn.reset();
        this._zoomOut.reset();
    }
    touchstart(e, points, mapTouches) {
        this._zoomIn.touchstart(e, points, mapTouches);
        this._zoomOut.touchstart(e, points, mapTouches);
    }
    touchmove(e, points, mapTouches) {
        this._zoomIn.touchmove(e, points, mapTouches);
        this._zoomOut.touchmove(e, points, mapTouches);
    }
    touchend(e, points, mapTouches) {
        const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches);
        const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches);
        if (zoomInPoint) {
            this._active = true;
            e.preventDefault();
            setTimeout(() => this.reset(), 0);
            return {
                cameraAnimation: map => map.easeTo({
                    duration: 300,
                    zoom: map.getZoom() + 1,
                    around: map.unproject(zoomInPoint)
                }, { originalEvent: e })
            };
        } else if (zoomOutPoint) {
            this._active = true;
            e.preventDefault();
            setTimeout(() => this.reset(), 0);
            return {
                cameraAnimation: map => map.easeTo({
                    duration: 300,
                    zoom: map.getZoom() - 1,
                    around: map.unproject(zoomOutPoint)
                }, { originalEvent: e })
            };
        }
    }
    touchcancel() {
        this.reset();
    }
    enable() {
        this._enabled = true;
    }
    disable() {
        this._enabled = false;
        this.reset();
    }
    isEnabled() {
        return this._enabled;
    }
    isActive() {
        return this._active;
    }
}

//      
const LEFT_BUTTON = 0;
const RIGHT_BUTTON = 2;
// the values for each button in MouseEvent.buttons
const BUTTONS_FLAGS = {
    [LEFT_BUTTON]: 1,
    [RIGHT_BUTTON]: 2
};
function buttonStillPressed(e, button) {
    const flag = BUTTONS_FLAGS[button];
    return e.buttons === undefined || (e.buttons & flag) !== flag;
}
class MouseHandler {
    constructor(options) {
        this.reset();
        this._clickTolerance = options.clickTolerance || 1;
    }
    blur() {
        this.reset();
    }
    reset() {
        this._active = false;
        this._moved = false;
        this._lastPoint = undefined;
        this._eventButton = undefined;
    }
    _correctButton(e, button) {
        //eslint-disable-line
        return false;    // implemented by child
    }
    _move(lastPoint, point) {
        //eslint-disable-line
        return {};    // implemented by child
    }
    mousedown(e, point) {
        if (this._lastPoint)
            return;
        const eventButton = mouseButton(e);
        if (!this._correctButton(e, eventButton))
            return;
        this._lastPoint = point;
        this._eventButton = eventButton;
    }
    mousemoveWindow(e, point) {
        const lastPoint = this._lastPoint;
        if (!lastPoint)
            return;
        e.preventDefault();
        if (this._eventButton != null && buttonStillPressed(e, this._eventButton)) {
            // Some browsers don't fire a `mouseup` when the mouseup occurs outside
            // the window or iframe:
            // https://github.com/mapbox/mapbox-gl-js/issues/4622
            //
            // If the button is no longer pressed during this `mousemove` it may have
            // been released outside of the window or iframe.
            this.reset();
            return;
        }
        if (!this._moved && point.dist(lastPoint) < this._clickTolerance)
            return;
        this._moved = true;
        this._lastPoint = point;
        // implemented by child class
        return this._move(lastPoint, point);
    }
    mouseupWindow(e) {
        if (!this._lastPoint)
            return;
        const eventButton = mouseButton(e);
        if (eventButton !== this._eventButton)
            return;
        if (this._moved)
            suppressClick();
        this.reset();
    }
    enable() {
        this._enabled = true;
    }
    disable() {
        this._enabled = false;
        this.reset();
    }
    isEnabled() {
        return this._enabled;
    }
    isActive() {
        return this._active;
    }
}
class MousePanHandler extends MouseHandler {
    mousedown(e, point) {
        super.mousedown(e, point);
        if (this._lastPoint)
            this._active = true;
    }
    _correctButton(e, button) {
        return button === LEFT_BUTTON && !e.ctrlKey;
    }
    _move(lastPoint, point) {
        return {
            around: point,
            panDelta: point.sub(lastPoint)
        };
    }
}
class MouseRotateHandler extends MouseHandler {
    _correctButton(e, button) {
        return button === LEFT_BUTTON && e.ctrlKey || button === RIGHT_BUTTON;
    }
    _move(lastPoint, point) {
        const degreesPerPixelMoved = 0.8;
        const bearingDelta = (point.x - lastPoint.x) * degreesPerPixelMoved;
        if (bearingDelta) {
            this._active = true;
            return { bearingDelta };
        }
    }
    contextmenu(e) {
        // prevent browser context menu when necessary; we don't allow it with rotation
        // because we can't discern rotation gesture start from contextmenu on Mac
        e.preventDefault();
    }
}
class MousePitchHandler extends MouseHandler {
    _correctButton(e, button) {
        return button === LEFT_BUTTON && e.ctrlKey || button === RIGHT_BUTTON;
    }
    _move(lastPoint, point) {
        const degreesPerPixelMoved = -0.5;
        const pitchDelta = (point.y - lastPoint.y) * degreesPerPixelMoved;
        if (pitchDelta) {
            this._active = true;
            return { pitchDelta };
        }
    }
    contextmenu(e) {
        // prevent browser context menu when necessary; we don't allow it with rotation
        // because we can't discern rotation gesture start from contextmenu on Mac
        e.preventDefault();
    }
}

//      
class TouchPanHandler {
    constructor(map, options) {
        this._map = map;
        this._el = map.getCanvasContainer();
        this._minTouches = 1;
        this._clickTolerance = options.clickTolerance || 1;
        this.reset();
        bindAll([
            '_addTouchPanBlocker',
            '_showTouchPanBlockerAlert'
        ], this);
    }
    reset() {
        this._active = false;
        this._touches = {};
        this._sum = new Point$2(0, 0);
    }
    touchstart(e, points, mapTouches) {
        return this._calculateTransform(e, points, mapTouches);
    }
    touchmove(e, points, mapTouches) {
        if (!this._active || mapTouches.length < this._minTouches)
            return;
        // if cooperative gesture handling is set to true, require two fingers to touch pan
        if (this._map._cooperativeGestures && !this._map.isMoving()) {
            if (mapTouches.length === 1 && !isFullscreen()) {
                this._showTouchPanBlockerAlert();
                return;
            } else if (this._alertContainer.style.visibility !== 'hidden') {
                // immediately hide alert if it is visible when two fingers are used to pan.
                this._alertContainer.style.visibility = 'hidden';
                clearTimeout(this._alertTimer);
            }
        }
        if (e.cancelable) {
            e.preventDefault();
        }
        return this._calculateTransform(e, points, mapTouches);
    }
    touchend(e, points, mapTouches) {
        this._calculateTransform(e, points, mapTouches);
        if (this._active && mapTouches.length < this._minTouches) {
            this.reset();
        }
    }
    touchcancel() {
        this.reset();
    }
    _calculateTransform(e, points, mapTouches) {
        if (mapTouches.length > 0)
            this._active = true;
        const touches = indexTouches(mapTouches, points);
        const touchPointSum = new Point$2(0, 0);
        const touchDeltaSum = new Point$2(0, 0);
        let touchDeltaCount = 0;
        for (const identifier in touches) {
            const point = touches[identifier];
            const prevPoint = this._touches[identifier];
            if (prevPoint) {
                touchPointSum._add(point);
                touchDeltaSum._add(point.sub(prevPoint));
                touchDeltaCount++;
                touches[identifier] = point;
            }
        }
        this._touches = touches;
        if (touchDeltaCount < this._minTouches || !touchDeltaSum.mag())
            return;
        const panDelta = touchDeltaSum.div(touchDeltaCount);
        this._sum._add(panDelta);
        if (this._sum.mag() < this._clickTolerance)
            return;
        const around = touchPointSum.div(touchDeltaCount);
        return {
            around,
            panDelta
        };
    }
    enable() {
        this._enabled = true;
        if (this._map._cooperativeGestures) {
            this._addTouchPanBlocker();
            // override touch-action css property to enable scrolling page over map
            this._el.classList.add('mapboxgl-touch-pan-blocker-override', 'mapboxgl-scrollable-page');
        }
    }
    disable() {
        this._enabled = false;
        if (this._map._cooperativeGestures) {
            clearTimeout(this._alertTimer);
            this._alertContainer.remove();
            this._el.classList.remove('mapboxgl-touch-pan-blocker-override', 'mapboxgl-scrollable-page');
        }
        this.reset();
    }
    isEnabled() {
        return !!this._enabled;
    }
    isActive() {
        return !!this._active;
    }
    _addTouchPanBlocker() {
        if (this._map && !this._alertContainer) {
            this._alertContainer = create$a('div', 'mapboxgl-touch-pan-blocker', this._map._container);
            this._alertContainer.textContent = this._map._getUIString('TouchPanBlocker.Message');
            // dynamically set the font size of the touch pan blocker alert message
            this._alertContainer.style.fontSize = `${ Math.max(10, Math.min(24, Math.floor(this._el.clientWidth * 0.05))) }px`;
        }
    }
    _showTouchPanBlockerAlert() {
        this._alertContainer.style.visibility = 'visible';
        this._alertContainer.classList.add('mapboxgl-touch-pan-blocker-show');
        this._alertContainer.setAttribute('role', 'alert');
        clearTimeout(this._alertTimer);
        this._alertTimer = setTimeout(() => {
            this._alertContainer.classList.remove('mapboxgl-touch-pan-blocker-show');
            this._alertContainer.setAttribute('role', 'null');
        }, 500);
    }
}

//      
class TwoTouchHandler {
    constructor() {
        this.reset();
    }
    reset() {
        this._active = false;
        this._firstTwoTouches = undefined;
    }
    _start(points) {
    }
    //eslint-disable-line
    _move(points, pinchAround, e) {
        return {};
    }
    //eslint-disable-line
    touchstart(e, points, mapTouches) {
        //console.log(e.target, e.targetTouches.length ? e.targetTouches[0].target : null);
        //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined);
        if (this._firstTwoTouches || mapTouches.length < 2)
            return;
        this._firstTwoTouches = [
            mapTouches[0].identifier,
            mapTouches[1].identifier
        ];
        // implemented by child classes
        this._start([
            points[0],
            points[1]
        ]);
    }
    touchmove(e, points, mapTouches) {
        const firstTouches = this._firstTwoTouches;
        if (!firstTouches)
            return;
        e.preventDefault();
        const [idA, idB] = firstTouches;
        const a = getTouchById(mapTouches, points, idA);
        const b = getTouchById(mapTouches, points, idB);
        if (!a || !b)
            return;
        const pinchAround = this._aroundCenter ? null : a.add(b).div(2);
        // implemented by child classes
        return this._move([
            a,
            b
        ], pinchAround, e);
    }
    touchend(e, points, mapTouches) {
        if (!this._firstTwoTouches)
            return;
        const [idA, idB] = this._firstTwoTouches;
        const a = getTouchById(mapTouches, points, idA);
        const b = getTouchById(mapTouches, points, idB);
        if (a && b)
            return;
        if (this._active)
            suppressClick();
        this.reset();
    }
    touchcancel() {
        this.reset();
    }
    enable(options) {
        this._enabled = true;
        this._aroundCenter = !!options && options.around === 'center';
    }
    disable() {
        this._enabled = false;
        this.reset();
    }
    isEnabled() {
        return this._enabled;
    }
    isActive() {
        return this._active;
    }
}
function getTouchById(mapTouches, points, identifier) {
    for (let i = 0; i < mapTouches.length; i++) {
        if (mapTouches[i].identifier === identifier)
            return points[i];
    }
}
/* ZOOM */
const ZOOM_THRESHOLD = 0.1;
function getZoomDelta(distance, lastDistance) {
    return Math.log(distance / lastDistance) / Math.LN2;
}
class TouchZoomHandler extends TwoTouchHandler {
    reset() {
        super.reset();
        this._distance = 0;
        this._startDistance = 0;
    }
    _start(points) {
        this._startDistance = this._distance = points[0].dist(points[1]);
    }
    _move(points, pinchAround) {
        const lastDistance = this._distance;
        this._distance = points[0].dist(points[1]);
        if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD)
            return;
        this._active = true;
        return {
            zoomDelta: getZoomDelta(this._distance, lastDistance),
            pinchAround
        };
    }
}
/* ROTATE */
const ROTATION_THRESHOLD = 25;
// pixels along circumference of touch circle
function getBearingDelta(a, b) {
    return a.angleWith(b) * 180 / Math.PI;
}
class TouchRotateHandler extends TwoTouchHandler {
    reset() {
        super.reset();
        this._minDiameter = 0;
        this._startVector = undefined;
        this._vector = undefined;
    }
    _start(points) {
        this._startVector = this._vector = points[0].sub(points[1]);
        this._minDiameter = points[0].dist(points[1]);
    }
    _move(points, pinchAround) {
        const lastVector = this._vector;
        this._vector = points[0].sub(points[1]);
        if (!lastVector || !this._active && this._isBelowThreshold(this._vector))
            return;
        this._active = true;
        return {
            // $FlowFixMe[incompatible-call] - Flow doesn't infer that this._vectoris not null
            bearingDelta: getBearingDelta(this._vector, lastVector),
            pinchAround
        };
    }
    _isBelowThreshold(vector) {
        /*
         * The threshold before a rotation actually happens is configured in
         * pixels alongth circumference of the circle formed by the two fingers.
         * This makes the threshold in degrees larger when the fingers are close
         * together and smaller when the fingers are far apart.
         *
         * Use the smallest diameter from the whole gesture to reduce sensitivity
         * when pinching in and out.
         */
        this._minDiameter = Math.min(this._minDiameter, vector.mag());
        const circumference = Math.PI * this._minDiameter;
        const threshold = ROTATION_THRESHOLD / circumference * 360;
        const startVector = this._startVector;
        if (!startVector)
            return false;
        const bearingDeltaSinceStart = getBearingDelta(vector, startVector);
        return Math.abs(bearingDeltaSinceStart) < threshold;
    }
}
/* PITCH */
function isVertical(vector) {
    return Math.abs(vector.y) > Math.abs(vector.x);
}
const ALLOWED_SINGLE_TOUCH_TIME = 100;
/**
 * The `TouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers.
 *
 * @see [Example: Set pitch and bearing](https://docs.mapbox.com/mapbox-gl-js/example/set-perspective/)
*/
class TouchPitchHandler extends TwoTouchHandler {
    constructor(map) {
        super();
        this._map = map;
    }
    reset() {
        super.reset();
        this._valid = undefined;
        this._firstMove = undefined;
        this._lastPoints = undefined;
    }
    _start(points) {
        this._lastPoints = points;
        if (isVertical(points[0].sub(points[1]))) {
            // fingers are more horizontal than vertical
            this._valid = false;
        }
    }
    _move(points, center, e) {
        const lastPoints = this._lastPoints;
        if (!lastPoints)
            return;
        const vectorA = points[0].sub(lastPoints[0]);
        const vectorB = points[1].sub(lastPoints[1]);
        if (this._map._cooperativeGestures && !isFullscreen() && e.touches.length < 3)
            return;
        this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp);
        if (!this._valid)
            return;
        this._lastPoints = points;
        this._active = true;
        const yDeltaAverage = (vectorA.y + vectorB.y) / 2;
        const degreesPerPixelMoved = -0.5;
        return { pitchDelta: yDeltaAverage * degreesPerPixelMoved };
    }
    gestureBeginsVertically(vectorA, vectorB, timeStamp) {
        if (this._valid !== undefined)
            return this._valid;
        const threshold = 2;
        const movedA = vectorA.mag() >= threshold;
        const movedB = vectorB.mag() >= threshold;
        // neither finger has moved a meaningful amount, wait
        if (!movedA && !movedB)
            return;
        // One finger has moved and the other has not.
        // If enough time has passed, decide it is not a pitch.
        if (!movedA || !movedB) {
            if (this._firstMove == null) {
                this._firstMove = timeStamp;
            }
            if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) {
                // still waiting for a movement from the second finger
                return undefined;
            } else {
                return false;
            }
        }
        const isSameDirection = vectorA.y > 0 === vectorB.y > 0;
        return isVertical(vectorA) && isVertical(vectorB) && isSameDirection;
    }
}

//      
const defaultOptions$5 = {
    panStep: 100,
    bearingStep: 15,
    pitchStep: 10
};
/**
 * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using
 * the following keyboard shortcuts:
 *
 * - `=` / `+`: Increase the zoom level by 1.
 * - `Shift-=` / `Shift-+`: Increase the zoom level by 2.
 * - `-`: Decrease the zoom level by 1.
 * - `Shift--`: Decrease the zoom level by 2.
 * - Arrow keys: Pan by 100 pixels.
 * - `Shift+⇢`: Increase the rotation by 15 degrees.
 * - `Shift+⇠`: Decrease the rotation by 15 degrees.
 * - `Shift+⇡`: Increase the pitch by 10 degrees.
 * - `Shift+⇣`: Decrease the pitch by 10 degrees.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 * @see [Example: Navigate the map with game-like controls](https://docs.mapbox.com/mapbox-gl-js/example/game-controls/)
 * @see [Example: Display map navigation controls](https://docs.mapbox.com/mapbox-gl-js/example/navigation/)
 */
class KeyboardHandler {
    /**
    * @private
    */
    constructor() {
        const stepOptions = defaultOptions$5;
        this._panStep = stepOptions.panStep;
        this._bearingStep = stepOptions.bearingStep;
        this._pitchStep = stepOptions.pitchStep;
        this._rotationDisabled = false;
    }
    blur() {
        this.reset();
    }
    reset() {
        this._active = false;
    }
    keydown(e) {
        if (e.altKey || e.ctrlKey || e.metaKey)
            return;
        let zoomDir = 0;
        let bearingDir = 0;
        let pitchDir = 0;
        let xDir = 0;
        let yDir = 0;
        switch (e.keyCode) {
        case 61:
        case 107:
        case 171:
        case 187:
            zoomDir = 1;
            break;
        case 189:
        case 109:
        case 173:
            zoomDir = -1;
            break;
        case 37:
            if (e.shiftKey) {
                bearingDir = -1;
            } else {
                e.preventDefault();
                xDir = -1;
            }
            break;
        case 39:
            if (e.shiftKey) {
                bearingDir = 1;
            } else {
                e.preventDefault();
                xDir = 1;
            }
            break;
        case 38:
            if (e.shiftKey) {
                pitchDir = 1;
            } else {
                e.preventDefault();
                yDir = -1;
            }
            break;
        case 40:
            if (e.shiftKey) {
                pitchDir = -1;
            } else {
                e.preventDefault();
                yDir = 1;
            }
            break;
        default:
            return;
        }
        if (this._rotationDisabled) {
            bearingDir = 0;
            pitchDir = 0;
        }
        return {
            cameraAnimation: map => {
                const zoom = map.getZoom();
                map.easeTo({
                    duration: 300,
                    easeId: 'keyboardHandler',
                    easing: easeOut,
                    zoom: zoomDir ? Math.round(zoom) + zoomDir * (e.shiftKey ? 2 : 1) : zoom,
                    bearing: map.getBearing() + bearingDir * this._bearingStep,
                    pitch: map.getPitch() + pitchDir * this._pitchStep,
                    offset: [
                        -xDir * this._panStep,
                        -yDir * this._panStep
                    ],
                    center: map.getCenter()
                }, { originalEvent: e });
            }
        };
    }
    /**
     * Enables the "keyboard rotate and zoom" interaction.
     *
     * @example
     * map.keyboard.enable();
     */
    enable() {
        this._enabled = true;
    }
    /**
     * Disables the "keyboard rotate and zoom" interaction.
     *
     * @example
     * map.keyboard.disable();
     */
    disable() {
        this._enabled = false;
        this.reset();
    }
    /**
     * Returns a Boolean indicating whether the "keyboard rotate and zoom"
     * interaction is enabled.
     *
     * @returns {boolean} `true` if the "keyboard rotate and zoom"
     *     interaction is enabled.
     * @example
     * const isKeyboardEnabled = map.keyboard.isEnabled();
     */
    isEnabled() {
        return this._enabled;
    }
    /**
     * Returns true if the handler is enabled and has detected the start of a
     * zoom/rotate gesture.
     *
     * @returns {boolean} `true` if the handler is enabled and has detected the
     *     start of a zoom/rotate gesture.
     * @example
     * const isKeyboardActive = map.keyboard.isActive();
     */
    isActive() {
        return this._active;
    }
    /**
     * Disables the "keyboard pan/rotate" interaction, leaving the
     * "keyboard zoom" interaction enabled.
     *
     * @example
     * map.keyboard.disableRotation();
     */
    disableRotation() {
        this._rotationDisabled = true;
    }
    /**
     * Enables the "keyboard pan/rotate" interaction.
     *
     * @example
     * map.keyboard.enable();
     * map.keyboard.enableRotation();
     */
    enableRotation() {
        this._rotationDisabled = false;
    }
}
function easeOut(t) {
    return t * (2 - t);
}

// deltaY value for mouse scroll wheel identification
const wheelZoomDelta = 4.000244140625;
// These magic numbers control the rate of zoom. Trackpad events fire at a greater
// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick
const defaultZoomRate = 1 / 100;
const wheelZoomRate = 1 / 450;
// upper bound on how much we scale the map in any single render frame; this
// is used to limit zoom rate in the case of very fast scrolling
const maxScalePerFrame = 2;
/**
 * The `ScrollZoomHandler` allows the user to zoom the map by scrolling.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 * @see [Example: Disable scroll zoom](https://docs.mapbox.com/mapbox-gl-js/example/disable-scroll-zoom/)
 */
class ScrollZoomHandler {
    // used for delayed-handling of a single wheel movement
    // used to delay final '{move,zoom}end' events
    // used to display the scroll zoom blocker alert
    /**
     * @private
     */
    constructor(map, handler) {
        this._map = map;
        this._el = map.getCanvasContainer();
        this._handler = handler;
        this._delta = 0;
        this._lastDelta = 0;
        this._defaultZoomRate = defaultZoomRate;
        this._wheelZoomRate = wheelZoomRate;
        bindAll([
            '_onTimeout',
            '_addScrollZoomBlocker',
            '_showBlockerAlert'
        ], this);
    }
    /**
     * Sets the zoom rate of a trackpad.
     *
     * @param {number} [zoomRate=1/100] The rate used to scale trackpad movement to a zoom value.
     * @example
     * // Speed up trackpad zoom
     * map.scrollZoom.setZoomRate(1 / 25);
     */
    setZoomRate(zoomRate) {
        this._defaultZoomRate = zoomRate;
    }
    /**
    * Sets the zoom rate of a mouse wheel.
     *
    * @param {number} [wheelZoomRate=1/450] The rate used to scale mouse wheel movement to a zoom value.
    * @example
    * // Slow down zoom of mouse wheel
    * map.scrollZoom.setWheelZoomRate(1 / 600);
    */
    setWheelZoomRate(wheelZoomRate) {
        this._wheelZoomRate = wheelZoomRate;
    }
    /**
     * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled.
     *
     * @returns {boolean} `true` if the "scroll to zoom" interaction is enabled.
     * @example
     * const isScrollZoomEnabled = map.scrollZoom.isEnabled();
     */
    isEnabled() {
        return !!this._enabled;
    }
    /*
    * Active state is turned on and off with every scroll wheel event and is set back to false before the map
    * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in
    * progress.
    */
    isActive() {
        return this._active || this._finishTimeout !== undefined;
    }
    isZooming() {
        return !!this._zooming;
    }
    /**
     * Enables the "scroll to zoom" interaction.
     *
     * @param {Object} [options] Options object.
     * @param {string} [options.around] If "center" is passed, map will zoom around center of map.
     *
     * @example
     * map.scrollZoom.enable();
     * @example
     * map.scrollZoom.enable({around: 'center'});
     */
    enable(options) {
        if (this.isEnabled())
            return;
        this._enabled = true;
        this._aroundCenter = !!options && options.around === 'center';
        if (this._map._cooperativeGestures)
            this._addScrollZoomBlocker();
    }
    /**
     * Disables the "scroll to zoom" interaction.
     *
     * @example
     * map.scrollZoom.disable();
     */
    disable() {
        if (!this.isEnabled())
            return;
        this._enabled = false;
        if (this._map._cooperativeGestures) {
            clearTimeout(this._alertTimer);
            this._alertContainer.remove();
        }
    }
    wheel(e) {
        if (!this.isEnabled())
            return;
        if (this._map._cooperativeGestures) {
            if (!e.ctrlKey && !e.metaKey && !this.isZooming() && !isFullscreen()) {
                this._showBlockerAlert();
                return;
            } else if (this._alertContainer.style.visibility !== 'hidden') {
                // immediately hide alert if it is visible when ctrl or ⌘ is pressed while scroll zooming.
                this._alertContainer.style.visibility = 'hidden';
                clearTimeout(this._alertTimer);
            }
        }
        // Remove `any` cast when https://github.com/facebook/flow/issues/4879 is fixed.
        let value = e.deltaMode === window$1.WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;
        const now = exported$1.now(), timeDelta = now - (this._lastWheelEventTime || 0);
        this._lastWheelEventTime = now;
        if (value !== 0 && value % wheelZoomDelta === 0) {
            // This one is definitely a mouse wheel event.
            this._type = 'wheel';
        } else if (value !== 0 && Math.abs(value) < 4) {
            // This one is definitely a trackpad event because it is so small.
            this._type = 'trackpad';
        } else if (timeDelta > 400) {
            // This is likely a new scroll action.
            this._type = null;
            this._lastValue = value;
            // Start a timeout in case this was a singular event, and delay it by up to 40ms.
            // $FlowFixMe[method-unbinding]
            this._timeout = setTimeout(this._onTimeout, 40, e);
        } else if (!this._type) {
            // This is a repeating event, but we don't know the type of event just yet.
            // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode.
            this._type = Math.abs(timeDelta * value) < 200 ? 'trackpad' : 'wheel';
            // Make sure our delayed event isn't fired again, because we accumulate
            // the previous event (which was less than 40ms ago) into this event.
            if (this._timeout) {
                clearTimeout(this._timeout);
                this._timeout = null;
                value += this._lastValue;
            }
        }
        // Slow down zoom if shift key is held for more precise zooming
        if (e.shiftKey && value)
            value = value / 4;
        // Only fire the callback if we actually know what type of scrolling device the user uses.
        if (this._type) {
            this._lastWheelEvent = e;
            this._delta -= value;
            if (!this._active) {
                this._start(e);
            }
        }
        e.preventDefault();
    }
    _onTimeout(initialEvent) {
        this._type = 'wheel';
        this._delta -= this._lastValue;
        if (!this._active) {
            this._start(initialEvent);
        }
    }
    _start(e) {
        if (!this._delta)
            return;
        if (this._frameId) {
            this._frameId = null;
        }
        this._active = true;
        if (!this.isZooming()) {
            this._zooming = true;
        }
        if (this._finishTimeout) {
            clearTimeout(this._finishTimeout);
            delete this._finishTimeout;
        }
        const pos = mousePos(this._el, e);
        this._aroundPoint = this._aroundCenter ? this._map.transform.centerPoint : pos;
        this._aroundCoord = this._map.transform.pointCoordinate3D(this._aroundPoint);
        this._targetZoom = undefined;
        if (!this._frameId) {
            this._frameId = true;
            this._handler._triggerRenderFrame();
        }
    }
    renderFrame() {
        if (!this._frameId)
            return;
        this._frameId = null;
        if (!this.isActive())
            return;
        const tr = this._map.transform;
        // If projection wraps and center crosses the antimeridian, reset previous mouse scroll easing settings to resolve https://github.com/mapbox/mapbox-gl-js/issues/11910
        if (this._type === 'wheel' && tr.projection.wrap && (tr._center.lng >= 180 || tr._center.lng <= -180)) {
            this._prevEase = null;
            this._easing = null;
            this._lastWheelEvent = null;
            this._lastWheelEventTime = 0;
        }
        const startingZoom = () => {
            return tr._terrainEnabled() && this._aroundCoord ? tr.computeZoomRelativeTo(this._aroundCoord) : tr.zoom;
        };
        // if we've had scroll events since the last render frame, consume the
        // accumulated delta, and update the target zoom level accordingly
        if (this._delta !== 0) {
            // For trackpad events and single mouse wheel ticks, use the default zoom rate
            const zoomRate = this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta ? this._wheelZoomRate : this._defaultZoomRate;
            // Scale by sigmoid of scroll wheel delta.
            let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));
            if (this._delta < 0 && scale !== 0) {
                scale = 1 / scale;
            }
            const startZoom = startingZoom();
            const startScale = Math.pow(2, startZoom);
            const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : startScale;
            this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale)));
            // if this is a mouse wheel, refresh the starting zoom and easing
            // function we're using to smooth out the zooming between wheel
            // events
            if (this._type === 'wheel') {
                this._startZoom = startZoom;
                this._easing = this._smoothOutEasing(200);
            }
            this._lastDelta = this._delta;
            this._delta = 0;
        }
        const targetZoom = typeof this._targetZoom === 'number' ? this._targetZoom : startingZoom();
        const startZoom = this._startZoom;
        const easing = this._easing;
        let finished = false;
        let zoom;
        if (this._type === 'wheel' && startZoom && easing) {
            const t = Math.min((exported$1.now() - this._lastWheelEventTime) / 200, 1);
            const k = easing(t);
            zoom = number(startZoom, targetZoom, k);
            if (t < 1) {
                if (!this._frameId) {
                    this._frameId = true;
                }
            } else {
                finished = true;
            }
        } else {
            zoom = targetZoom;
            finished = true;
        }
        this._active = true;
        if (finished) {
            this._active = false;
            this._finishTimeout = setTimeout(() => {
                this._zooming = false;
                this._handler._triggerRenderFrame();
                delete this._targetZoom;
                delete this._finishTimeout;
            }, 200);
        }
        let zoomDelta = zoom - startingZoom();
        if (zoomDelta * this._lastDelta < 0) {
            // prevent recenter zoom in opposite direction from zoom
            zoomDelta = 0;
        }
        return {
            noInertia: true,
            needsRenderFrame: !finished,
            zoomDelta,
            around: this._aroundPoint,
            aroundCoord: this._aroundCoord,
            originalEvent: this._lastWheelEvent
        };
    }
    _smoothOutEasing(duration) {
        let easing = ease;
        if (this._prevEase) {
            const ease = this._prevEase, t = (exported$1.now() - ease.start) / ease.duration, speed = ease.easing(t + 0.01) - ease.easing(t),
                // Quick hack to make new bezier that is continuous with last
                x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01, y = Math.sqrt(0.27 * 0.27 - x * x);
            easing = bezier$1(x, y, 0.25, 1);
        }
        this._prevEase = {
            start: exported$1.now(),
            duration,
            easing
        };
        return easing;
    }
    blur() {
        this.reset();
    }
    reset() {
        this._active = false;
    }
    _addScrollZoomBlocker() {
        if (this._map && !this._alertContainer) {
            this._alertContainer = create$a('div', 'mapboxgl-scroll-zoom-blocker', this._map._container);
            if (/(Mac|iPad)/i.test(window$1.navigator.userAgent)) {
                this._alertContainer.textContent = this._map._getUIString('ScrollZoomBlocker.CmdMessage');
            } else {
                this._alertContainer.textContent = this._map._getUIString('ScrollZoomBlocker.CtrlMessage');
            }
            // dynamically set the font size of the scroll zoom blocker alert message
            this._alertContainer.style.fontSize = `${ Math.max(10, Math.min(24, Math.floor(this._el.clientWidth * 0.05))) }px`;
        }
    }
    _showBlockerAlert() {
        this._alertContainer.style.visibility = 'visible';
        this._alertContainer.classList.add('mapboxgl-scroll-zoom-blocker-show');
        this._alertContainer.setAttribute('role', 'alert');
        clearTimeout(this._alertTimer);
        this._alertTimer = setTimeout(() => {
            this._alertContainer.classList.remove('mapboxgl-scroll-zoom-blocker-show');
            this._alertContainer.setAttribute('role', 'null');
        }, 200);
    }
}

//      
/**
 * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by
 * double clicking or double tapping.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 */
class DoubleClickZoomHandler {
    /**
     * @private
    */
    constructor(clickZoom, TapZoom) {
        this._clickZoom = clickZoom;
        this._tapZoom = TapZoom;
    }
    /**
     * Enables the "double click to zoom" interaction.
     *
     * @example
     * map.doubleClickZoom.enable();
     */
    enable() {
        this._clickZoom.enable();
        this._tapZoom.enable();
    }
    /**
     * Disables the "double click to zoom" interaction.
     *
     * @example
     * map.doubleClickZoom.disable();
     */
    disable() {
        this._clickZoom.disable();
        this._tapZoom.disable();
    }
    /**
     * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled.
     *
     * @returns {boolean} Returns `true` if the "double click to zoom" interaction is enabled.
     * @example
     * const isDoubleClickZoomEnabled = map.doubleClickZoom.isEnabled();
     */
    isEnabled() {
        return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();
    }
    /**
     * Returns a Boolean indicating whether the "double click to zoom" interaction is active (currently being used).
     *
     * @returns {boolean} Returns `true` if the "double click to zoom" interaction is active.
     * @example
     * const isDoubleClickZoomActive = map.doubleClickZoom.isActive();
     */
    isActive() {
        return this._clickZoom.isActive() || this._tapZoom.isActive();
    }
}

//      
class ClickZoomHandler {
    constructor() {
        this.reset();
    }
    reset() {
        this._active = false;
    }
    blur() {
        this.reset();
    }
    dblclick(e, point) {
        e.preventDefault();
        return {
            cameraAnimation: map => {
                map.easeTo({
                    duration: 300,
                    zoom: map.getZoom() + (e.shiftKey ? -1 : 1),
                    around: map.unproject(point)
                }, { originalEvent: e });
            }
        };
    }
    enable() {
        this._enabled = true;
    }
    disable() {
        this._enabled = false;
        this.reset();
    }
    isEnabled() {
        return this._enabled;
    }
    isActive() {
        return this._active;
    }
}

//      
class TapDragZoomHandler {
    constructor() {
        this._tap = new TapRecognizer({
            numTouches: 1,
            numTaps: 1
        });
        this.reset();
    }
    reset() {
        this._active = false;
        this._swipePoint = undefined;
        this._swipeTouch = 0;
        this._tapTime = 0;
        this._tap.reset();
    }
    touchstart(e, points, mapTouches) {
        if (this._swipePoint)
            return;
        if (this._tapTime && e.timeStamp - this._tapTime > MAX_TAP_INTERVAL) {
            this.reset();
        }
        if (!this._tapTime) {
            this._tap.touchstart(e, points, mapTouches);
        } else if (mapTouches.length > 0) {
            this._swipePoint = points[0];
            this._swipeTouch = mapTouches[0].identifier;
        }
    }
    touchmove(e, points, mapTouches) {
        if (!this._tapTime) {
            this._tap.touchmove(e, points, mapTouches);
        } else if (this._swipePoint) {
            if (mapTouches[0].identifier !== this._swipeTouch) {
                return;
            }
            const newSwipePoint = points[0];
            const dist = newSwipePoint.y - this._swipePoint.y;
            this._swipePoint = newSwipePoint;
            e.preventDefault();
            this._active = true;
            return { zoomDelta: dist / 128 };
        }
    }
    touchend(e, points, mapTouches) {
        if (!this._tapTime) {
            const point = this._tap.touchend(e, points, mapTouches);
            if (point) {
                this._tapTime = e.timeStamp;
            }
        } else if (this._swipePoint) {
            if (mapTouches.length === 0) {
                this.reset();
            }
        }
    }
    touchcancel() {
        this.reset();
    }
    enable() {
        this._enabled = true;
    }
    disable() {
        this._enabled = false;
        this.reset();
    }
    isEnabled() {
        return this._enabled;
    }
    isActive() {
        return this._active;
    }
}

//      
/**
 * The `DragPanHandler` allows the user to pan the map by clicking and dragging
 * the cursor.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 * @see [Example: Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
 */
class DragPanHandler {
    /**
     * @private
    */
    constructor(el, mousePan, touchPan) {
        this._el = el;
        this._mousePan = mousePan;
        this._touchPan = touchPan;
    }
    /**
     * Enables the "drag to pan" interaction and accepts options to control the behavior of the panning inertia.
     *
     * @param {Object} [options] Options object.
     * @param {number} [options.linearity=0] Factor used to scale the drag velocity.
     * @param {Function} [options.easing] Optional easing function applied to {@link Map#panTo} when applying the drag. Defaults to bezier function using [@mapbox/unitbezier](https://github.com/mapbox/unitbezier).
     * @param {number} [options.maxSpeed=1400] The maximum value of the drag velocity.
     * @param {number} [options.deceleration=2500] The rate at which the speed reduces after the pan ends.
     *
     * @example
     * map.dragPan.enable();
     * @example
     * map.dragPan.enable({
     *     linearity: 0.3,
     *     easing: t => t,
     *     maxSpeed: 1400,
     *     deceleration: 2500
     * });
     * @see [Example: Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
     */
    enable(options) {
        this._inertiaOptions = options || {};
        this._mousePan.enable();
        this._touchPan.enable();
        this._el.classList.add('mapboxgl-touch-drag-pan');
    }
    /**
     * Disables the "drag to pan" interaction.
     *
     * @example
     * map.dragPan.disable();
     */
    disable() {
        this._mousePan.disable();
        this._touchPan.disable();
        this._el.classList.remove('mapboxgl-touch-drag-pan');
    }
    /**
     * Returns a Boolean indicating whether the "drag to pan" interaction is enabled.
     *
     * @returns {boolean} Returns `true` if the "drag to pan" interaction is enabled.
     * @example
     * const isDragPanEnabled = map.dragPan.isEnabled();
     */
    isEnabled() {
        return this._mousePan.isEnabled() && this._touchPan.isEnabled();
    }
    /**
     * Returns a Boolean indicating whether the "drag to pan" interaction is active (currently being used).
     *
     * @returns {boolean} Returns `true` if the "drag to pan" interaction is active.
     * @example
     * const isDragPanActive = map.dragPan.isActive();
     */
    isActive() {
        return this._mousePan.isActive() || this._touchPan.isActive();
    }
}

//      
/**
 * The `DragRotateHandler` allows the user to rotate the map by clicking and
 * dragging the cursor while holding the right mouse button or `ctrl` key.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 * @see [Example: Disable map rotation](https://docs.mapbox.com/mapbox-gl-js/example/disable-rotation/)
 */
class DragRotateHandler {
    /**
     * @param {Object} [options]
     * @param {number} [options.bearingSnap] The threshold, measured in degrees, that determines when the map's
     *   bearing will snap to north.
     * @param {bool} [options.pitchWithRotate=true] Control the map pitch in addition to the bearing
     * @private
     */
    constructor(options, mouseRotate, mousePitch) {
        this._pitchWithRotate = options.pitchWithRotate;
        this._mouseRotate = mouseRotate;
        this._mousePitch = mousePitch;
    }
    /**
     * Enables the "drag to rotate" interaction.
     *
     * @example
     * map.dragRotate.enable();
     */
    enable() {
        this._mouseRotate.enable();
        if (this._pitchWithRotate)
            this._mousePitch.enable();
    }
    /**
     * Disables the "drag to rotate" interaction.
     *
     * @example
     * map.dragRotate.disable();
     */
    disable() {
        this._mouseRotate.disable();
        this._mousePitch.disable();
    }
    /**
     * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled.
     *
     * @returns {boolean} `true` if the "drag to rotate" interaction is enabled.
     * @example
     * const isDragRotateEnabled = map.dragRotate.isEnabled();
     */
    isEnabled() {
        return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled());
    }
    /**
     * Returns a Boolean indicating whether the "drag to rotate" interaction is active (currently being used).
     *
     * @returns {boolean} Returns `true` if the "drag to rotate" interaction is active.
     * @example
     * const isDragRotateActive = map.dragRotate.isActive();
     */
    isActive() {
        return this._mouseRotate.isActive() || this._mousePitch.isActive();
    }
}

//      
/**
 * The `TouchZoomRotateHandler` allows the user to zoom and rotate the map by
 * pinching on a touchscreen.
 *
 * They can zoom with one finger by double tapping and dragging. On the second tap,
 * hold the finger down and drag up or down to zoom in or out.
 *
 * @see [Example: Toggle interactions](https://docs.mapbox.com/mapbox-gl-js/example/toggle-interaction-handlers/)
 */
class TouchZoomRotateHandler {
    /**
     * @private
    */
    constructor(el, touchZoom, touchRotate, tapDragZoom) {
        this._el = el;
        this._touchZoom = touchZoom;
        this._touchRotate = touchRotate;
        this._tapDragZoom = tapDragZoom;
        this._rotationDisabled = false;
        this._enabled = true;
    }
    /**
     * Enables the "pinch to rotate and zoom" interaction.
     *
     * @param {Object} [options] Options object.
     * @param {string} [options.around] If "center" is passed, map will zoom around the center.
     *
     * @example
     * map.touchZoomRotate.enable();
     * @example
     * map.touchZoomRotate.enable({around: 'center'});
     */
    enable(options) {
        this._touchZoom.enable(options);
        if (!this._rotationDisabled)
            this._touchRotate.enable(options);
        this._tapDragZoom.enable();
        this._el.classList.add('mapboxgl-touch-zoom-rotate');
    }
    /**
     * Disables the "pinch to rotate and zoom" interaction.
     *
     * @example
     * map.touchZoomRotate.disable();
     */
    disable() {
        this._touchZoom.disable();
        this._touchRotate.disable();
        this._tapDragZoom.disable();
        this._el.classList.remove('mapboxgl-touch-zoom-rotate');
    }
    /**
     * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled.
     *
     * @returns {boolean} `true` if the "pinch to rotate and zoom" interaction is enabled.
     * @example
     * const isTouchZoomRotateEnabled = map.touchZoomRotate.isEnabled();
     */
    isEnabled() {
        return this._touchZoom.isEnabled() && (this._rotationDisabled || this._touchRotate.isEnabled()) && this._tapDragZoom.isEnabled();
    }
    /**
     * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture.
     *
     * @returns {boolean} `true` if enabled and a zoom/rotate gesture was detected.
     * @example
     * const isTouchZoomRotateActive = map.touchZoomRotate.isActive();
     */
    isActive() {
        return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();
    }
    /**
     * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom"
     * interaction enabled.
     *
     * @example
     * map.touchZoomRotate.disableRotation();
     */
    disableRotation() {
        this._rotationDisabled = true;
        this._touchRotate.disable();
    }
    /**
     * Enables the "pinch to rotate" interaction.
     *
     * @example
     * map.touchZoomRotate.enable();
     * map.touchZoomRotate.enableRotation();
     */
    enableRotation() {
        this._rotationDisabled = false;
        if (this._touchZoom.isEnabled())
            this._touchRotate.enable();
    }
}

//      
const isMoving = p => p.zoom || p.drag || p.pitch || p.rotate;
class RenderFrameEvent extends Event {
}
class TrackingEllipsoid {
    constructor() {
        // a, b, c in the equation x²/a² + y²/b² + z²/c² = 1
        this.constants = [
            1,
            1,
            0.01
        ];
        this.radius = 0;
    }
    setup(center, pointOnSurface) {
        const centerToSurface = vec3_1.sub([], pointOnSurface, center);
        if (centerToSurface[2] < 0) {
            this.radius = vec3_1.length(vec3_1.div([], centerToSurface, this.constants));
        } else {
            // The point on surface is above the center. This can happen for example when the camera is
            // below the clicked point (like a mountain) Use slightly shorter radius for less aggressive movement
            this.radius = vec3_1.length([
                centerToSurface[0],
                centerToSurface[1],
                0
            ]);
        }
    }
    // Cast a ray from the center of the ellipsoid and the intersection point.
    projectRay(dir) {
        // Perform the intersection test against a unit sphere
        vec3_1.div(dir, dir, this.constants);
        vec3_1.normalize(dir, dir);
        vec3_1.mul(dir, dir, this.constants);
        const intersection = vec3_1.scale([], dir, this.radius);
        if (intersection[2] > 0) {
            // The intersection point is above horizon so special handling is required.
            // Otherwise direction of the movement would be inverted due to the ellipsoid shape
            const h = vec3_1.scale([], [
                0,
                0,
                1
            ], vec3_1.dot(intersection, [
                0,
                0,
                1
            ]));
            const r = vec3_1.scale([], vec3_1.normalize([], [
                intersection[0],
                intersection[1],
                0
            ]), this.radius);
            const p = vec3_1.add([], intersection, vec3_1.scale([], vec3_1.sub([], vec3_1.add([], r, h), intersection), 2));
            intersection[0] = p[0];
            intersection[1] = p[1];
        }
        return intersection;
    }
}
// Handlers interpret dom events and return camera changes that should be
// applied to the map (`HandlerResult`s). The camera changes are all deltas.
// The handler itself should have no knowledge of the map's current state.
// This makes it easier to merge multiple results and keeps handlers simpler.
// For example, if there is a mousedown and mousemove, the mousePan handler
// would return a `panDelta` on the mousemove.
// All handler methods that are called with events can optionally return a `HandlerResult`.
function hasChange(result) {
    return result.panDelta && result.panDelta.mag() || result.zoomDelta || result.bearingDelta || result.pitchDelta;
}
class HandlerManager {
    constructor(map, options) {
        this._map = map;
        this._el = this._map.getCanvasContainer();
        this._handlers = [];
        this._handlersById = {};
        this._changes = [];
        this._inertia = new HandlerInertia(map);
        this._bearingSnap = options.bearingSnap;
        this._previousActiveHandlers = {};
        this._trackingEllipsoid = new TrackingEllipsoid();
        this._dragOrigin = null;
        // Track whether map is currently moving, to compute start/move/end events
        this._eventsInProgress = {};
        this._addDefaultHandlers(options);
        bindAll([
            'handleEvent',
            'handleWindowEvent'
        ], this);
        const el = this._el;
        this._listeners = [
            // This needs to be `passive: true` so that a double tap fires two
            // pairs of touchstart/end events in iOS Safari 13. If this is set to
            // `passive: false` then the second pair of events is only fired if
            // preventDefault() is called on the first touchstart. Calling preventDefault()
            // undesirably prevents click events.
            [
                el,
                'touchstart',
                { passive: true }
            ],
            // This needs to be `passive: false` so that scrolls and pinches can be
            // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12.
            [
                el,
                'touchmove',
                { passive: false }
            ],
            [
                el,
                'touchend',
                undefined
            ],
            [
                el,
                'touchcancel',
                undefined
            ],
            [
                el,
                'mousedown',
                undefined
            ],
            [
                el,
                'mousemove',
                undefined
            ],
            [
                el,
                'mouseup',
                undefined
            ],
            // Bind window-level event listeners for move and up/end events. In the absence of
            // the pointer capture API, which is not supported by all necessary platforms,
            // window-level event listeners give us the best shot at capturing events that
            // fall outside the map canvas element. Use `{capture: true}` for the move event
            // to prevent map move events from being fired during a drag.
            [
                window$1.document,
                'mousemove',
                { capture: true }
            ],
            [
                window$1.document,
                'mouseup',
                undefined
            ],
            [
                el,
                'mouseover',
                undefined
            ],
            [
                el,
                'mouseout',
                undefined
            ],
            [
                el,
                'dblclick',
                undefined
            ],
            [
                el,
                'click',
                undefined
            ],
            [
                el,
                'keydown',
                { capture: false }
            ],
            [
                el,
                'keyup',
                undefined
            ],
            [
                el,
                'wheel',
                { passive: false }
            ],
            [
                el,
                'contextmenu',
                undefined
            ],
            [
                window$1,
                'blur',
                undefined
            ]
        ];
        for (const [target, type, listenerOptions] of this._listeners) {
            // $FlowFixMe[method-unbinding]
            const listener = target === window$1.document ? this.handleWindowEvent : this.handleEvent;
            target.addEventListener(type, listener, listenerOptions);
        }
    }
    destroy() {
        for (const [target, type, listenerOptions] of this._listeners) {
            // $FlowFixMe[method-unbinding]
            const listener = target === window$1.document ? this.handleWindowEvent : this.handleEvent;
            target.removeEventListener(type, listener, listenerOptions);
        }
    }
    _addDefaultHandlers(options) {
        const map = this._map;
        const el = map.getCanvasContainer();
        // $FlowFixMe[method-unbinding]
        this._add('mapEvent', new MapEventHandler(map, options));
        const boxZoom = map.boxZoom = new BoxZoomHandler(map, options);
        // $FlowFixMe[method-unbinding]
        this._add('boxZoom', boxZoom);
        const tapZoom = new TapZoomHandler();
        const clickZoom = new ClickZoomHandler();
        map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);
        // $FlowFixMe[method-unbinding]
        this._add('tapZoom', tapZoom);
        // $FlowFixMe[method-unbinding]
        this._add('clickZoom', clickZoom);
        const tapDragZoom = new TapDragZoomHandler();
        // $FlowFixMe[method-unbinding]
        this._add('tapDragZoom', tapDragZoom);
        const touchPitch = map.touchPitch = new TouchPitchHandler(map);
        // $FlowFixMe[method-unbinding]
        this._add('touchPitch', touchPitch);
        const mouseRotate = new MouseRotateHandler(options);
        const mousePitch = new MousePitchHandler(options);
        map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch);
        // $FlowFixMe[method-unbinding]
        this._add('mouseRotate', mouseRotate, ['mousePitch']);
        // $FlowFixMe[method-unbinding]
        this._add('mousePitch', mousePitch, ['mouseRotate']);
        const mousePan = new MousePanHandler(options);
        const touchPan = new TouchPanHandler(map, options);
        map.dragPan = new DragPanHandler(el, mousePan, touchPan);
        // $FlowFixMe[method-unbinding]
        this._add('mousePan', mousePan);
        // $FlowFixMe[method-unbinding]
        this._add('touchPan', touchPan, [
            'touchZoom',
            'touchRotate'
        ]);
        const touchRotate = new TouchRotateHandler();
        const touchZoom = new TouchZoomHandler();
        map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);
        // $FlowFixMe[method-unbinding]
        this._add('touchRotate', touchRotate, [
            'touchPan',
            'touchZoom'
        ]);
        // $FlowFixMe[method-unbinding]
        this._add('touchZoom', touchZoom, [
            'touchPan',
            'touchRotate'
        ]);
        // $FlowFixMe[method-unbinding]
        this._add('blockableMapEvent', new BlockableMapEventHandler(map));
        const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this);
        // $FlowFixMe[method-unbinding]
        this._add('scrollZoom', scrollZoom, ['mousePan']);
        const keyboard = map.keyboard = new KeyboardHandler();
        // $FlowFixMe[method-unbinding]
        this._add('keyboard', keyboard);
        for (const name of [
                'boxZoom',
                'doubleClickZoom',
                'tapDragZoom',
                'touchPitch',
                'dragRotate',
                'dragPan',
                'touchZoomRotate',
                'scrollZoom',
                'keyboard'
            ]) {
            if (options.interactive && options[name]) {
                map[name].enable(options[name]);
            }
        }
    }
    _add(handlerName, handler, allowed) {
        this._handlers.push({
            handlerName,
            handler,
            allowed
        });
        this._handlersById[handlerName] = handler;
    }
    stop(allowEndAnimation) {
        // do nothing if this method was triggered by a gesture update
        if (this._updatingCamera)
            return;
        for (const {handler} of this._handlers) {
            handler.reset();
        }
        this._inertia.clear();
        this._fireEvents({}, {}, allowEndAnimation);
        this._changes = [];
        this._originalZoom = undefined;
    }
    isActive() {
        for (const {handler} of this._handlers) {
            if (handler.isActive())
                return true;
        }
        return false;
    }
    isZooming() {
        return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();
    }
    isRotating() {
        return !!this._eventsInProgress.rotate;
    }
    isMoving() {
        return !!isMoving(this._eventsInProgress) || this.isZooming();
    }
    _isDragging() {
        return !!this._eventsInProgress.drag;
    }
    _blockedByActive(activeHandlers, allowed, myName) {
        for (const name in activeHandlers) {
            if (name === myName)
                continue;
            if (!allowed || allowed.indexOf(name) < 0) {
                return true;
            }
        }
        return false;
    }
    handleWindowEvent(e) {
        this.handleEvent(e, `${ e.type }Window`);
    }
    _getMapTouches(touches) {
        const mapTouches = [];
        for (const t of touches) {
            const target = t.target;
            if (this._el.contains(target)) {
                mapTouches.push(t);
            }
        }
        return mapTouches;
    }
    handleEvent(e, eventName) {
        this._updatingCamera = true;
        const isRenderFrame = e.type === 'renderFrame';
        const inputEvent = isRenderFrame ? undefined : e;
        /*
         * We don't call e.preventDefault() for any events by default.
         * Handlers are responsible for calling it where necessary.
         */
        const mergedHandlerResult = { needsRenderFrame: false };
        const eventsInProgress = {};
        const activeHandlers = {};
        const mapTouches = e.touches ? this._getMapTouches(e.touches) : undefined;
        const points = mapTouches ? touchPos(this._el, mapTouches) : isRenderFrame ? undefined : // renderFrame event doesn't have any points
        mousePos(this._el, e);
        for (const {handlerName, handler, allowed} of this._handlers) {
            if (!handler.isEnabled())
                continue;
            let data;
            if (this._blockedByActive(activeHandlers, allowed, handlerName)) {
                handler.reset();
            } else {
                if (handler[eventName || e.type]) {
                    data = handler[eventName || e.type](e, points, mapTouches);
                    this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);
                    if (data && data.needsRenderFrame) {
                        this._triggerRenderFrame();
                    }
                }
            }
            if (data || handler.isActive()) {
                activeHandlers[handlerName] = handler;
            }
        }
        const deactivatedHandlers = {};
        for (const name in this._previousActiveHandlers) {
            if (!activeHandlers[name]) {
                deactivatedHandlers[name] = inputEvent;
            }
        }
        this._previousActiveHandlers = activeHandlers;
        if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {
            this._changes.push([
                mergedHandlerResult,
                eventsInProgress,
                deactivatedHandlers
            ]);
            this._triggerRenderFrame();
        }
        if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) {
            this._map._stop(true);
        }
        this._updatingCamera = false;
        const {cameraAnimation} = mergedHandlerResult;
        if (cameraAnimation) {
            this._inertia.clear();
            this._fireEvents({}, {}, true);
            this._changes = [];
            cameraAnimation(this._map);
        }
    }
    mergeHandlerResult(mergedHandlerResult, eventsInProgress, handlerResult, name, e) {
        if (!handlerResult)
            return;
        extend$1(mergedHandlerResult, handlerResult);
        const eventData = {
            handlerName: name,
            originalEvent: handlerResult.originalEvent || e
        };
        // track which handler changed which camera property
        if (handlerResult.zoomDelta !== undefined) {
            eventsInProgress.zoom = eventData;
        }
        if (handlerResult.panDelta !== undefined) {
            eventsInProgress.drag = eventData;
        }
        if (handlerResult.pitchDelta !== undefined) {
            eventsInProgress.pitch = eventData;
        }
        if (handlerResult.bearingDelta !== undefined) {
            eventsInProgress.rotate = eventData;
        }
    }
    _applyChanges() {
        const combined = {};
        const combinedEventsInProgress = {};
        const combinedDeactivatedHandlers = {};
        for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) {
            if (change.panDelta)
                combined.panDelta = (combined.panDelta || new Point$2(0, 0))._add(change.panDelta);
            if (change.zoomDelta)
                combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;
            if (change.bearingDelta)
                combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;
            if (change.pitchDelta)
                combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;
            if (change.around !== undefined)
                combined.around = change.around;
            if (change.aroundCoord !== undefined)
                combined.aroundCoord = change.aroundCoord;
            if (change.pinchAround !== undefined)
                combined.pinchAround = change.pinchAround;
            if (change.noInertia)
                combined.noInertia = change.noInertia;
            extend$1(combinedEventsInProgress, eventsInProgress);
            extend$1(combinedDeactivatedHandlers, deactivatedHandlers);
        }
        this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);
        this._changes = [];
    }
    _updateMapTransform(combinedResult, combinedEventsInProgress, deactivatedHandlers) {
        const map = this._map;
        const tr = map.transform;
        const eventStarted = type => {
            const newEvent = combinedEventsInProgress[type];
            return newEvent && !this._eventsInProgress[type];
        };
        const eventEnded = type => {
            const event = this._eventsInProgress[type];
            return event && !this._handlersById[event.handlerName].isActive();
        };
        const toVec3 = p => [
            p.x,
            p.y,
            p.z
        ];
        if (eventEnded('drag') && !hasChange(combinedResult)) {
            const preZoom = tr.zoom;
            tr.cameraElevationReference = 'sea';
            if (this._originalZoom != null && tr._orthographicProjectionAtLowPitch && tr.projection.name !== 'globe' && tr.pitch === 0) {
                // keep constant zoom from drag gesture start.
                tr.cameraElevationReference = 'ground';
                tr.zoom = this._originalZoom;
            } else {
                tr.recenterOnTerrain();
                tr.cameraElevationReference = 'ground';
            }
            // Map zoom might change during the pan operation due to terrain elevation.
            if (preZoom !== tr.zoom)
                this._map._update(true);
        }
        // Catches double click and double tap zooms when camera is constrained over terrain
        if (tr._isCameraConstrained)
            map._stop(true);
        if (!hasChange(combinedResult)) {
            this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
            return;
        }
        let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, aroundCoord, pinchAround} = combinedResult;
        if (tr._isCameraConstrained) {
            // Catches wheel zoom events when camera is constrained over terrain
            if (zoomDelta > 0)
                zoomDelta = 0;
            tr._isCameraConstrained = false;
        }
        if (pinchAround !== undefined) {
            around = pinchAround;
        }
        if ((zoomDelta || eventStarted('drag')) && around) {
            this._dragOrigin = toVec3(tr.pointCoordinate3D(around));
            this._originalZoom = tr.zoom;
            // Construct the tracking ellipsoid every time user changes the zoom or drag origin.
            // Direction of the ray will define size of the shape and hence defining the available range of movement
            this._trackingEllipsoid.setup(tr._camera.position, this._dragOrigin);
        }
        // All movement of the camera is done relative to the sea level
        tr.cameraElevationReference = 'sea';
        // stop any ongoing camera animations (easeTo, flyTo)
        map._stop(true);
        around = around || map.transform.centerPoint;
        if (bearingDelta)
            tr.bearing += bearingDelta;
        if (pitchDelta)
            tr.pitch += pitchDelta;
        tr._updateCameraState();
        // Compute Mercator 3D camera offset based on screenspace panDelta
        const panVec = [
            0,
            0,
            0
        ];
        if (panDelta) {
            if (tr.projection.name === 'mercator') {
                const startPoint = this._trackingEllipsoid.projectRay(tr.screenPointToMercatorRay(around).dir);
                const endPoint = this._trackingEllipsoid.projectRay(tr.screenPointToMercatorRay(around.sub(panDelta)).dir);
                panVec[0] = endPoint[0] - startPoint[0];
                panVec[1] = endPoint[1] - startPoint[1];
            } else {
                const startPoint = tr.pointCoordinate(around);
                if (tr.projection.name === 'globe') {
                    // Compute pan vector directly in pixel coordinates for the globe.
                    // Rotate the globe a bit faster when dragging near poles to compensate
                    // different pixel-per-meter ratios (ie. pixel-to-physical-rotation is lower)
                    panDelta = panDelta.rotate(-tr.angle);
                    const scale = tr._pixelsPerMercatorPixel / tr.worldSize;
                    panVec[0] = -panDelta.x * mercatorScale(latFromMercatorY(startPoint.y)) * scale;
                    panVec[1] = -panDelta.y * mercatorScale(tr.center.lat) * scale;
                } else {
                    const endPoint = tr.pointCoordinate(around.sub(panDelta));
                    if (startPoint && endPoint) {
                        panVec[0] = endPoint.x - startPoint.x;
                        panVec[1] = endPoint.y - startPoint.y;
                    }
                }
            }
        }
        const originalZoom = tr.zoom;
        // Compute Mercator 3D camera offset based on screenspace requested ZoomDelta
        const zoomVec = [
            0,
            0,
            0
        ];
        if (zoomDelta) {
            // Zoom value has to be computed relative to a secondary map plane that is created from the terrain position below the cursor.
            // This way the zoom interpolation can be kept linear and independent of the (possible) terrain elevation
            const pickedPosition = aroundCoord ? toVec3(aroundCoord) : toVec3(tr.pointCoordinate3D(around));
            const aroundRay = { dir: vec3_1.normalize([], vec3_1.sub([], pickedPosition, tr._camera.position)) };
            if (aroundRay.dir[2] < 0) {
                // Special handling is required if the ray created from the cursor is heading up.
                // This scenario is possible if user is trying to zoom towards a feature like a hill or a mountain.
                // Convert zoomDelta to a movement vector as if the camera would be orbiting around the picked point
                const movement = tr.zoomDeltaToMovement(pickedPosition, zoomDelta);
                vec3_1.scale(zoomVec, aroundRay.dir, movement);
            }
        }
        // Mutate camera state via CameraAPI
        const translation = vec3_1.add(panVec, panVec, zoomVec);
        tr._translateCameraConstrained(translation);
        if (zoomDelta && Math.abs(tr.zoom - originalZoom) > 0.0001) {
            tr.recenterOnTerrain();
        }
        tr.cameraElevationReference = 'ground';
        this._map._update();
        if (!combinedResult.noInertia)
            this._inertia.record(combinedResult);
        this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
    }
    _fireEvents(newEventsInProgress, deactivatedHandlers, allowEndAnimation) {
        const wasMoving = isMoving(this._eventsInProgress);
        const nowMoving = isMoving(newEventsInProgress);
        const startEvents = {};
        for (const eventName in newEventsInProgress) {
            const {originalEvent} = newEventsInProgress[eventName];
            if (!this._eventsInProgress[eventName]) {
                startEvents[`${ eventName }start`] = originalEvent;
            }
            this._eventsInProgress[eventName] = newEventsInProgress[eventName];
        }
        // fire start events only after this._eventsInProgress has been updated
        if (!wasMoving && nowMoving) {
            this._fireEvent('movestart', nowMoving.originalEvent);
        }
        for (const name in startEvents) {
            this._fireEvent(name, startEvents[name]);
        }
        if (nowMoving) {
            this._fireEvent('move', nowMoving.originalEvent);
        }
        for (const eventName in newEventsInProgress) {
            const {originalEvent} = newEventsInProgress[eventName];
            this._fireEvent(eventName, originalEvent);
        }
        const endEvents = {};
        let originalEndEvent;
        for (const eventName in this._eventsInProgress) {
            const {handlerName, originalEvent} = this._eventsInProgress[eventName];
            if (!this._handlersById[handlerName].isActive()) {
                delete this._eventsInProgress[eventName];
                originalEndEvent = deactivatedHandlers[handlerName] || originalEvent;
                endEvents[`${ eventName }end`] = originalEndEvent;
            }
        }
        for (const name in endEvents) {
            this._fireEvent(name, endEvents[name]);
        }
        const stillMoving = isMoving(this._eventsInProgress);
        if (allowEndAnimation && (wasMoving || nowMoving) && !stillMoving) {
            this._updatingCamera = true;
            const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);
            const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap;
            if (inertialEase) {
                if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) {
                    inertialEase.bearing = 0;
                }
                this._map.easeTo(inertialEase, { originalEvent: originalEndEvent });
            } else {
                this._map.fire(new Event('moveend', { originalEvent: originalEndEvent }));
                if (shouldSnapToNorth(this._map.getBearing())) {
                    this._map.resetNorth();
                }
            }
            this._updatingCamera = false;
        }
    }
    _fireEvent(type, e) {
        this._map.fire(new Event(type, e ? { originalEvent: e } : {}));
    }
    _requestFrame() {
        this._map.triggerRepaint();
        return this._map._renderTaskQueue.add(timeStamp => {
            this._frameId = undefined;
            this.handleEvent(new RenderFrameEvent('renderFrame', { timeStamp }));
            this._applyChanges();
        });
    }
    _triggerRenderFrame() {
        if (this._frameId === undefined) {
            this._frameId = this._requestFrame();
        }
    }
}

//      
/**
 * A helper type: converts all Object type values to non-maybe types.
 */
/**
 * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location,
 * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current
 * camera value for that property will remain unchanged.
 *
 * @typedef {Object} CameraOptions
 * @property {LngLatLike} center The location to place at the screen center.
 * @property {number} zoom The desired zoom level.
 * @property {number} bearing The desired bearing in degrees. The bearing is the compass direction that
 *     is "up". For example, `bearing: 90` orients the map so that east is up.
 * @property {number} pitch The desired pitch in degrees. The pitch is the angle towards the horizon
 *     measured in degrees with a range between 0 and 85 degrees. For example, pitch: 0 provides the appearance
 *     of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon.
 *     Increasing the pitch value is often used to display 3D objects.
 * @property {LngLatLike} around The location serving as the origin for a change in `zoom`, `pitch` and/or `bearing`.
 *     This location will remain at the same screen position following the transform.
 *     This is useful for drawing attention to a location that is not in the screen center.
 *     `center` is ignored if `around` is included.
 * @property {PaddingOptions} padding Dimensions in pixels applied on each side of the viewport for shifting the vanishing point.
 * @example
 * // set the map's initial perspective with CameraOptions
 * const map = new mapboxgl.Map({
 *     container: 'map',
 *     style: 'mapbox://styles/mapbox/streets-v11',
 *     center: [-73.5804, 45.53483],
 *     pitch: 60,
 *     bearing: -60,
 *     zoom: 10
 * });
 * @see [Example: Set pitch and bearing](https://docs.mapbox.com/mapbox-gl-js/example/set-perspective/)
 * @see [Example: Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/)
 * @see [Example: Fly to a location](https://docs.mapbox.com/mapbox-gl-js/example/flyto/)
 * @see [Example: Display buildings in 3D](https://docs.mapbox.com/mapbox-gl-js/example/3d-buildings/)
 */
/**
 * Options common to map movement methods that involve animation, such as {@link Map#panBy} and
 * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties
 * are optional.
 *
 * @typedef {Object} AnimationOptions
 * @property {number} duration The animation's duration, measured in milliseconds.
 * @property {Function} easing A function taking a time in the range 0..1 and returning a number where 0 is
 *     the initial state and 1 is the final state.
 * @property {PointLike} offset The target center's offset relative to real map container center at the end of animation.
 * @property {boolean} animate If `false`, no animation will occur.
 * @property {boolean} essential If `true`, then the animation is considered essential and will not be affected by
 *     [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion).
 * @property {boolean} preloadOnly If `true`, it will trigger tiles loading across the animation path, but no animation will occur.
 * @property {number} curve The zooming "curve" that will occur along the
 *     flight path. A high value maximizes zooming for an exaggerated animation, while a low
 *     value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average
 *     value selected by participants in the user study discussed in
 *     [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of
 *     `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A
 *     value of 1 would produce a circular motion. If `minZoom` is specified, this option will be ignored.
 * @property {number} minZoom The zero-based zoom level at the peak of the flight path. If
 *     this option is specified, `curve` will be ignored.
 * @property {number} speed The average speed of the animation defined in relation to
 *     `curve`. A speed of 1.2 means that the map appears to move along the flight path
 *     by 1.2 times `curve` screenfuls every second. A _screenful_ is the map's visible span.
 *     It does not correspond to a fixed physical distance, but varies by zoom level.
 * @property {number} screenSpeed The average speed of the animation measured in screenfuls
 *     per second, assuming a linear timing curve. If `speed` is specified, this option is ignored.
 * @property {number} maxDuration The animation's maximum duration, measured in milliseconds.
 *     If duration exceeds maximum duration, it resets to 0.
 * @see [Example: Slowly fly to a location](https://docs.mapbox.com/mapbox-gl-js/example/flyto-options/)
 * @see [Example: Customize camera animations](https://docs.mapbox.com/mapbox-gl-js/example/camera-animation/)
 * @see [Example: Navigate the map with game-like controls](https://docs.mapbox.com/mapbox-gl-js/example/game-controls/)
*/
const freeCameraNotSupportedWarning = 'map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.';
/**
 * Options for setting padding on calls to methods such as {@link Map#fitBounds}, {@link Map#fitScreenCoordinates}, and {@link Map#setPadding}. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be
 * non-negative integers.
 *
 * @typedef {Object} PaddingOptions
 * @property {number} top Padding in pixels from the top of the map canvas.
 * @property {number} bottom Padding in pixels from the bottom of the map canvas.
 * @property {number} left Padding in pixels from the left of the map canvas.
 * @property {number} right Padding in pixels from the right of the map canvas.
 *
 * @example
 * const bbox = [[-79, 43], [-73, 45]];
 * map.fitBounds(bbox, {
 *     padding: {top: 10, bottom: 25, left: 15, right: 5}
 * });
 *
 * @example
 * const bbox = [[-79, 43], [-73, 45]];
 * map.fitBounds(bbox, {
 *     padding: 20
 * });
 * @see [Example: Fit to the bounds of a LineString](https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/)
 * @see [Example: Fit a map to a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/fitbounds/)
 */
class Camera extends Evented {
    constructor(transform, options) {
        super();
        this._moving = false;
        this._zooming = false;
        this.transform = transform;
        this._bearingSnap = options.bearingSnap;
        this._respectPrefersReducedMotion = options.respectPrefersReducedMotion !== false;
        bindAll(['_renderFrameCallback'], this);    //addAssertions(this);
    }
    /** @section {Camera}
     * @method
     * @instance
     * @memberof Map */
    /**
     * Returns the map's geographical centerpoint.
     *
     * @memberof Map#
     * @returns {LngLat} The map's geographical centerpoint.
     * @example
     * // Return a LngLat object such as {lng: 0, lat: 0}.
     * const center = map.getCenter();
     * // Access longitude and latitude values directly.
     * const {lng, lat} = map.getCenter();
     * @see [Tutorial: Use Mapbox GL JS in a React app](https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/#store-the-new-coordinates)
     */
    getCenter() {
        return new LngLat$1(this.transform.center.lng, this.transform.center.lat);
    }
    /**
     * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.
     *
     * @memberof Map#
     * @param {LngLatLike} center The centerpoint to set.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setCenter([-74, 38]);
     */
    setCenter(center, eventData) {
        return this.jumpTo({ center }, eventData);
    }
    /**
     * Pans the map by the specified offset.
     *
     * @memberof Map#
     * @param {PointLike} offset The `x` and `y` coordinates by which to pan the map.
     * @param {AnimationOptions | null} options An options object describing the destination and animation of the transition. We do not recommend using `options.offset` since this value will override the value of the `offset` parameter.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} `this` Returns itself to allow for method chaining.
     * @example
     * map.panBy([-74, 38]);
     * @example
     * // panBy with an animation of 5 seconds.
     * map.panBy([-74, 38], {duration: 5000});
     * @see [Example: Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)
     */
    panBy(offset, options, eventData) {
        offset = Point$2.convert(offset).mult(-1);
        return this.panTo(this.transform.center, extend$1({ offset }, options), eventData);
    }
    /**
     * Pans the map to the specified location with an animated transition.
     *
     * @memberof Map#
     * @param {LngLatLike} lnglat The location to pan the map to.
     * @param {AnimationOptions | null} options Options describing the destination and animation of the transition.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.panTo([-74, 38]);
     * @example
     * // Specify that the panTo animation should last 5000 milliseconds.
     * map.panTo([-74, 38], {duration: 5000});
     * @see [Example: Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/)
     */
    panTo(lnglat, options, eventData) {
        return this.easeTo(extend$1({ center: lnglat }, options), eventData);
    }
    /**
     * Returns the map's current zoom level.
     *
     * @memberof Map#
     * @returns {number} The map's current zoom level.
     * @example
     * map.getZoom();
     */
    getZoom() {
        return this.transform.zoom;
    }
    /**
     * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.
     *
     * @memberof Map#
     * @param {number} zoom The zoom level to set (0-20).
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Zoom to the zoom level 5 without an animated transition
     * map.setZoom(5);
     */
    setZoom(zoom, eventData) {
        this.jumpTo({ zoom }, eventData);
        return this;
    }
    /**
     * Zooms the map to the specified zoom level, with an animated transition.
     *
     * @memberof Map#
     * @param {number} zoom The zoom level to transition to.
     * @param {AnimationOptions | null} options Options object.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Zoom to the zoom level 5 without an animated transition
     * map.zoomTo(5);
     * // Zoom to the zoom level 8 with an animated transition
     * map.zoomTo(8, {
     *     duration: 2000,
     *     offset: [100, 50]
     * });
     */
    zoomTo(zoom, options, eventData) {
        return this.easeTo(extend$1({ zoom }, options), eventData);
    }
    /**
     * Increases the map's zoom level by 1.
     *
     * @memberof Map#
     * @param {AnimationOptions | null} options Options object.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // zoom the map in one level with a custom animation duration
     * map.zoomIn({duration: 1000});
     */
    zoomIn(options, eventData) {
        this.zoomTo(this.getZoom() + 1, options, eventData);
        return this;
    }
    /**
     * Decreases the map's zoom level by 1.
     *
     * @memberof Map#
     * @param {AnimationOptions | null} options Options object.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // zoom the map out one level with a custom animation offset
     * map.zoomOut({offset: [80, 60]});
     */
    zoomOut(options, eventData) {
        this.zoomTo(this.getZoom() - 1, options, eventData);
        return this;
    }
    /**
     * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing
     * of 90° orients the map so that east is up.
     *
     * @memberof Map#
     * @returns {number} The map's current bearing.
     * @example
     * const bearing = map.getBearing();
     * @see [Example: Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)
     */
    getBearing() {
        return this.transform.bearing;
    }
    /**
     * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing
     * of 90° orients the map so that east is up.
     *
     * Equivalent to `jumpTo({bearing: bearing})`.
     *
     * @memberof Map#
     * @param {number} bearing The desired bearing.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Rotate the map to 90 degrees.
     * map.setBearing(90);
     */
    setBearing(bearing, eventData) {
        this.jumpTo({ bearing }, eventData);
        return this;
    }
    /**
     * Returns the current padding applied around the map viewport.
     *
     * @memberof Map#
     * @returns {PaddingOptions} The current padding around the map viewport.
     * @example
     * const padding = map.getPadding();
     */
    getPadding() {
        return this.transform.padding;
    }
    /**
     * Sets the padding in pixels around the viewport.
     *
     * Equivalent to `jumpTo({padding: padding})`.
     *
     * @memberof Map#
     * @param {PaddingOptions} padding The desired padding. Format: {left: number, right: number, top: number, bottom: number}.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Sets a left padding of 300px, and a top padding of 50px
     * map.setPadding({left: 300, top: 50});
     */
    setPadding(padding, eventData) {
        this.jumpTo({ padding }, eventData);
        return this;
    }
    /**
     * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction
     * that is \"up\"; for example, a bearing of 90° orients the map so that east is up.
     *
     * @memberof Map#
     * @param {number} bearing The desired bearing.
     * @param {EasingOptions | null} options Options describing the destination and animation of the transition.
     *     Accepts {@link CameraOptions} and {@link AnimationOptions}.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.rotateTo(30);
     * @example
     * // rotateTo with an animation of 2 seconds.
     * map.rotateTo(30, {duration: 2000});
     */
    rotateTo(bearing, options, eventData) {
        return this.easeTo(extend$1({ bearing }, options), eventData);
    }
    /**
     * Rotates the map so that north is up (0° bearing), with an animated transition.
     *
     * @memberof Map#
     * @param {EasingOptions | null} options Options describing the destination and animation of the transition.
     *     Accepts {@link CameraOptions} and {@link AnimationOptions}.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // resetNorth with an animation of 2 seconds.
     * map.resetNorth({duration: 2000});
     */
    resetNorth(options, eventData) {
        this.rotateTo(0, extend$1({ duration: 1000 }, options), eventData);
        return this;
    }
    /**
     * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.
     *
     * @memberof Map#
     * @param {EasingOptions | null} options Options describing the destination and animation of the transition.
     *     Accepts {@link CameraOptions} and {@link AnimationOptions}.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // resetNorthPitch with an animation of 2 seconds.
     * map.resetNorthPitch({duration: 2000});
     */
    resetNorthPitch(options, eventData) {
        this.easeTo(extend$1({
            bearing: 0,
            pitch: 0,
            duration: 1000
        }, options), eventData);
        return this;
    }
    /**
     * Snaps the map so that north is up (0° bearing), if the current bearing is
     * close enough to it (within the `bearingSnap` threshold).
     *
     * @memberof Map#
     * @param {EasingOptions | null} options Options describing the destination and animation of the transition.
     *     Accepts {@link CameraOptions} and {@link AnimationOptions}.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // snapToNorth with an animation of 2 seconds.
     * map.snapToNorth({duration: 2000});
     */
    snapToNorth(options, eventData) {
        if (Math.abs(this.getBearing()) < this._bearingSnap) {
            return this.resetNorth(options, eventData);
        }
        return this;
    }
    /**
     * Returns the map's current [pitch](https://docs.mapbox.com/help/glossary/camera/) (tilt).
     *
     * @memberof Map#
     * @returns {number} The map's current pitch, measured in degrees away from the plane of the screen.
     * @example
     * const pitch = map.getPitch();
     */
    getPitch() {
        return this.transform.pitch;
    }
    /**
     * Sets the map's [pitch](https://docs.mapbox.com/help/glossary/camera/) (tilt). Equivalent to `jumpTo({pitch: pitch})`.
     *
     * @memberof Map#
     * @param {number} pitch The pitch to set, measured in degrees away from the plane of the screen (0-60).
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:pitchstart
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // setPitch with an animation of 2 seconds.
     * map.setPitch(80, {duration: 2000});
     */
    setPitch(pitch, eventData) {
        this.jumpTo({ pitch }, eventData);
        return this;
    }
    /**
     * Returns a {@link CameraOptions} object for the highest zoom level
     * up to and including `Map#getMaxZoom()` that fits the bounds
     * in the viewport at the specified bearing.
     *
     * @memberof Map#
     * @param {LngLatBoundsLike} bounds Calculate the center for these bounds in the viewport and use
     *     the highest zoom level up to and including `Map#getMaxZoom()` that fits
     *     in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.
     * @param {CameraOptions | null} options Options object.
     * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.
     * @param {number} [options.bearing=0] Desired map bearing at end of animation, in degrees.
     * @param {number} [options.pitch=0] Desired map pitch at end of animation, in degrees.
     * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.
     * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds.
     * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with
     *     `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined.
     * @example
     * const bbox = [[-79, 43], [-73, 45]];
     * const newCameraTransform = map.cameraForBounds(bbox, {
     *     padding: {top: 10, bottom:25, left: 15, right: 5}
     * });
     */
    cameraForBounds(bounds, options) {
        bounds = LngLatBounds.convert(bounds);
        const bearing = options && options.bearing || 0;
        const pitch = options && options.pitch || 0;
        const lnglat0 = bounds.getNorthWest();
        const lnglat1 = bounds.getSouthEast();
        return this._cameraForBounds(this.transform, lnglat0, lnglat1, bearing, pitch, options);
    }
    _extendCameraOptions(options) {
        const defaultPadding = {
            top: 0,
            bottom: 0,
            right: 0,
            left: 0
        };
        options = extend$1({
            padding: defaultPadding,
            offset: [
                0,
                0
            ],
            maxZoom: this.transform.maxZoom
        }, options);
        if (typeof options.padding === 'number') {
            const p = options.padding;
            options.padding = {
                top: p,
                bottom: p,
                right: p,
                left: p
            };
        }
        options.padding = extend$1(defaultPadding, options.padding);
        return options;
    }
    _minimumAABBFrustumDistance(tr, aabb) {
        const aabbW = aabb.max[0] - aabb.min[0];
        const aabbH = aabb.max[1] - aabb.min[1];
        const aabbAspectRatio = aabbW / aabbH;
        const selectXAxis = aabbAspectRatio > tr.aspect;
        const minimumDistance = selectXAxis ? aabbW / (2 * Math.tan(tr.fovX * 0.5) * tr.aspect) : aabbH / (2 * Math.tan(tr.fovY * 0.5) * tr.aspect);
        return minimumDistance;
    }
    _cameraForBoundsOnGlobe(transform, p0, p1, bearing, pitch, options) {
        const tr = transform.clone();
        const eOptions = this._extendCameraOptions(options);
        tr.bearing = bearing;
        tr.pitch = pitch;
        const coord0 = LngLat$1.convert(p0);
        const coord1 = LngLat$1.convert(p1);
        const midLat = (coord0.lat + coord1.lat) * 0.5;
        const midLng = (coord0.lng + coord1.lng) * 0.5;
        const origin = latLngToECEF(midLat, midLng);
        const zAxis = vec3_1.normalize([], origin);
        const xAxis = vec3_1.normalize([], vec3_1.cross([], zAxis, [
            0,
            1,
            0
        ]));
        const yAxis = vec3_1.cross([], xAxis, zAxis);
        const aabbOrientation = [
            xAxis[0],
            xAxis[1],
            xAxis[2],
            0,
            yAxis[0],
            yAxis[1],
            yAxis[2],
            0,
            zAxis[0],
            zAxis[1],
            zAxis[2],
            0,
            0,
            0,
            0,
            1
        ];
        const ecefCoords = [
            origin,
            latLngToECEF(coord0.lat, coord0.lng),
            latLngToECEF(coord1.lat, coord0.lng),
            latLngToECEF(coord1.lat, coord1.lng),
            latLngToECEF(coord0.lat, coord1.lng),
            latLngToECEF(midLat, coord0.lng),
            latLngToECEF(midLat, coord1.lng),
            latLngToECEF(coord0.lat, midLng),
            latLngToECEF(coord1.lat, midLng)
        ];
        let aabb = Aabb.fromPoints(ecefCoords.map(p => [
            vec3_1.dot(xAxis, p),
            vec3_1.dot(yAxis, p),
            vec3_1.dot(zAxis, p)
        ]));
        const center = vec3_1.transformMat4([], aabb.center, aabbOrientation);
        if (vec3_1.squaredLength(center) === 0) {
            vec3_1.set(center, 0, 0, 1);
        }
        vec3_1.normalize(center, center);
        vec3_1.scale(center, center, GLOBE_RADIUS);
        tr.center = ecefToLatLng(center);
        const worldToCamera = tr.getWorldToCameraMatrix();
        const cameraToWorld = mat4_1.invert(new Float64Array(16), worldToCamera);
        aabb = Aabb.applyTransform(aabb, mat4_1.multiply([], worldToCamera, aabbOrientation));
        vec3_1.transformMat4(center, center, worldToCamera);
        const aabbHalfExtentZ = (aabb.max[2] - aabb.min[2]) * 0.5;
        const frustumDistance = this._minimumAABBFrustumDistance(tr, aabb);
        const offsetZ = vec3_1.scale([], [
            0,
            0,
            1
        ], aabbHalfExtentZ);
        const aabbClosestPoint = vec3_1.add(offsetZ, center, offsetZ);
        const offsetDistance = frustumDistance + (tr.pitch === 0 ? 0 : vec3_1.distance(center, aabbClosestPoint));
        const globeCenter = tr.globeCenterInViewSpace;
        const normal = vec3_1.sub([], center, [
            globeCenter[0],
            globeCenter[1],
            globeCenter[2]
        ]);
        vec3_1.normalize(normal, normal);
        vec3_1.scale(normal, normal, offsetDistance);
        const cameraPosition = vec3_1.add([], center, normal);
        vec3_1.transformMat4(cameraPosition, cameraPosition, cameraToWorld);
        const meterPerECEF = earthRadius / GLOBE_RADIUS;
        const altitudeECEF = vec3_1.length(cameraPosition);
        const altitudeMeter = altitudeECEF * meterPerECEF - earthRadius;
        const mercatorZ = mercatorZfromAltitude(Math.max(altitudeMeter, Number.EPSILON), 0);
        const zoom = Math.min(tr.zoomFromMercatorZAdjusted(mercatorZ), eOptions.maxZoom);
        const halfZoomTransition = (GLOBE_ZOOM_THRESHOLD_MIN + GLOBE_ZOOM_THRESHOLD_MAX) * 0.5;
        if (zoom > halfZoomTransition) {
            tr.setProjection({ name: 'mercator' });
            tr.zoom = zoom;
            return this._cameraForBounds(tr, p0, p1, bearing, pitch, options);
        }
        return {
            center: tr.center,
            zoom,
            bearing,
            pitch
        };
    }
    /** @section {Querying features} */
    /**
     * Queries the currently loaded data for elevation at a geographical location. The elevation is returned in `meters` relative to mean sea-level.
     * Returns `null` if `terrain` is disabled or if terrain data for the location hasn't been loaded yet.
     *
     * In order to guarantee that the terrain data is loaded ensure that the geographical location is visible and wait for the `idle` event to occur.
     *
     * @memberof Map#
     * @param {LngLatLike} lnglat The geographical location at which to query.
     * @param {ElevationQueryOptions} [options] Options object.
     * @param {boolean} [options.exaggerated=true] When `true` returns the terrain elevation with the value of `exaggeration` from the style already applied.
     *     When `false`, returns the raw value of the underlying data without styling applied.
     * @returns {number | null} The elevation in meters.
     * @example
     * const coordinate = [-122.420679, 37.772537];
     * const elevation = map.queryTerrainElevation(coordinate);
     * @see [Example: Query terrain elevation](https://docs.mapbox.com/mapbox-gl-js/example/query-terrain-elevation/)
     */
    queryTerrainElevation(lnglat, options) {
        const elevation = this.transform.elevation;
        if (elevation) {
            options = extend$1({}, { exaggerated: true }, options);
            return elevation.getAtPoint(MercatorCoordinate.fromLngLat(lnglat), null, options.exaggerated);
        }
        return null;
    }
    /**
     * Calculate the center of these two points in the viewport and use
     * the highest zoom level up to and including `Map#getMaxZoom()` that fits
     * the points in the viewport at the specified bearing.
     * @memberof Map#
     * @param {LngLatLike} p0 First point
     * @param {LngLatLike} p1 Second point
     * @param {number} bearing Desired map bearing at end of animation, in degrees
     * @param {number} pitch Desired map pitch at end of animation, in degrees
     * @param {CameraOptions | null} options
     * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.
     * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.
     * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds.
     * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with
     *      `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined.
     * @private
     * @example
     * var p0 = [-79, 43];
     * var p1 = [-73, 45];
     * var bearing = 90;
     * var newCameraTransform = map._cameraForBounds(p0, p1, bearing, pitch, {
     *   padding: {top: 10, bottom:25, left: 15, right: 5}
     * });
     */
    _cameraForBounds(transform, p0, p1, bearing, pitch, options) {
        if (transform.projection.name === 'globe') {
            return this._cameraForBoundsOnGlobe(transform, p0, p1, bearing, pitch, options);
        }
        const tr = transform.clone();
        const eOptions = this._extendCameraOptions(options);
        const edgePadding = tr.padding;
        tr.bearing = bearing;
        tr.pitch = pitch;
        const coord0 = LngLat$1.convert(p0);
        const coord1 = LngLat$1.convert(p1);
        const coord2 = new LngLat$1(coord0.lng, coord1.lat);
        const coord3 = new LngLat$1(coord1.lng, coord0.lat);
        const p0world = tr.project(coord0);
        const p1world = tr.project(coord1);
        const z0 = this.queryTerrainElevation(coord0);
        const z1 = this.queryTerrainElevation(coord1);
        const z2 = this.queryTerrainElevation(coord2);
        const z3 = this.queryTerrainElevation(coord3);
        const worldCoords = [
            [
                p0world.x,
                p0world.y,
                Math.min(z0 || 0, z1 || 0, z2 || 0, z3 || 0)
            ],
            [
                p1world.x,
                p1world.y,
                Math.max(z0 || 0, z1 || 0, z2 || 0, z3 || 0)
            ]
        ];
        let aabb = Aabb.fromPoints(worldCoords);
        const worldToCamera = tr.getWorldToCameraMatrix();
        const cameraToWorld = mat4_1.invert(new Float64Array(16), worldToCamera);
        aabb = Aabb.applyTransform(aabb, worldToCamera);
        const size = vec3_1.sub([], aabb.max, aabb.min);
        const screenPadL = edgePadding.left || 0;
        const screenPadR = edgePadding.right || 0;
        const screenPadB = edgePadding.bottom || 0;
        const screenPadT = edgePadding.top || 0;
        const {
            left: padL,
            right: padR,
            top: padT,
            bottom: padB
        } = eOptions.padding;
        const halfScreenPadX = (screenPadL + screenPadR) * 0.5;
        const halfScreenPadY = (screenPadT + screenPadB) * 0.5;
        const scaleX = (tr.width - (screenPadL + screenPadR + padL + padR)) / size[0];
        const scaleY = (tr.height - (screenPadB + screenPadT + padB + padT)) / size[1];
        const zoomRef = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), eOptions.maxZoom);
        const scaleRatio = tr.scale / tr.zoomScale(zoomRef);
        aabb = new Aabb([
            aabb.min[0] - (padL + halfScreenPadX) * scaleRatio,
            aabb.min[1] - (padB + halfScreenPadY) * scaleRatio,
            aabb.min[2]
        ], [
            aabb.max[0] + (padR + halfScreenPadX) * scaleRatio,
            aabb.max[1] + (padT + halfScreenPadY) * scaleRatio,
            aabb.max[2]
        ]);
        const aabbHalfExtentZ = size[2] * 0.5;
        const frustumDistance = this._minimumAABBFrustumDistance(tr, aabb);
        const normalZ = [
            0,
            0,
            1,
            0
        ];
        vec4_1.transformMat4(normalZ, normalZ, worldToCamera);
        vec4_1.normalize(normalZ, normalZ);
        const offset = vec3_1.scale([], normalZ, frustumDistance + aabbHalfExtentZ);
        const cameraPosition = vec3_1.add([], aabb.center, offset);
        const centerOffset = typeof eOptions.offset.x === 'number' && typeof eOptions.offset.y === 'number' ? new Point$2(eOptions.offset.x, eOptions.offset.y) : Point$2.convert(eOptions.offset);
        const rotatedOffset = centerOffset.rotate(-degToRad(bearing));
        aabb.center[0] -= rotatedOffset.x * scaleRatio;
        aabb.center[1] += rotatedOffset.y * scaleRatio;
        vec3_1.transformMat4(aabb.center, aabb.center, cameraToWorld);
        vec3_1.transformMat4(cameraPosition, cameraPosition, cameraToWorld);
        const mercator = [
            aabb.center[0],
            aabb.center[1],
            cameraPosition[2] * tr.pixelsPerMeter
        ];
        vec3_1.scale(mercator, mercator, 1 / tr.worldSize);
        const lng = lngFromMercatorX(mercator[0]);
        const lat = latFromMercatorY(mercator[1]);
        const zoom = Math.min(tr._zoomFromMercatorZ(mercator[2]), eOptions.maxZoom);
        const center = new LngLat$1(lng, lat);
        const halfZoomTransition = (GLOBE_ZOOM_THRESHOLD_MIN + GLOBE_ZOOM_THRESHOLD_MAX) * 0.5;
        if (tr.mercatorFromTransition && zoom < halfZoomTransition) {
            tr.setProjection({ name: 'globe' });
            tr.zoom = zoom;
            return this._cameraForBounds(tr, p0, p1, bearing, pitch, options);
        }
        return {
            center,
            zoom,
            bearing,
            pitch
        };
    }
    /**
     * Pans and zooms the map to contain its visible area within the specified geographical bounds.
     * If a padding is set on the map, the bounds are fit to the inset.
     *
     * @memberof Map#
     * @param {LngLatBoundsLike} bounds Center these bounds in the viewport and use the highest
     *     zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport.
     * @param {Object} [options] Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.
     * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.
     * @param {number} [options.pitch=0] Desired map pitch at end of animation, in degrees.
     * @param {number} [options.bearing=0] Desired map bearing at end of animation, in degrees.
     * @param {boolean} [options.linear=false] If `true`, the map transitions using
     *     {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See
     *     those functions and {@link AnimationOptions} for information about options available.
     * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}.
     * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.
     * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.
     * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * const bbox = [[-79, 43], [-73, 45]];
     * map.fitBounds(bbox, {
     *     padding: {top: 10, bottom:25, left: 15, right: 5}
     * });
     * @see [Example: Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/)
     */
    fitBounds(bounds, options, eventData) {
        const cameraPlacement = this.cameraForBounds(bounds, options);
        return this._fitInternal(cameraPlacement, options, eventData);
    }
    /**
     * Pans, rotates and zooms the map to to fit the box made by points p0 and p1
     * once the map is rotated to the specified bearing. To zoom without rotating,
     * pass in the current map bearing.
     *
     * @memberof Map#
     * @param {PointLike} p0 First point on screen, in pixel coordinates.
     * @param {PointLike} p1 Second point on screen, in pixel coordinates.
     * @param {number} bearing Desired map bearing at end of animation, in degrees.
     * @param {EasingOptions | null} options Options object.
     *     Accepts {@link CameraOptions} and {@link AnimationOptions}.
     * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.
     * @param {boolean} [options.linear=false] If `true`, the map transitions using
     *     {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See
     *     those functions and {@link AnimationOptions} for information about options available.
     * @param {number} [options.pitch=0] Desired map pitch at end of animation, in degrees.
     * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}.
     * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.
     * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:moveend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * const p0 = [220, 400];
     * const p1 = [500, 900];
     * map.fitScreenCoordinates(p0, p1, map.getBearing(), {
     *     padding: {top: 10, bottom:25, left: 15, right: 5}
     * });
     * @see Used by {@link BoxZoomHandler}
     */
    fitScreenCoordinates(p0, p1, bearing, options, eventData) {
        const screen0 = Point$2.convert(p0);
        const screen1 = Point$2.convert(p1);
        const min = new Point$2(Math.min(screen0.x, screen1.x), Math.min(screen0.y, screen1.y));
        const max = new Point$2(Math.max(screen0.x, screen1.x), Math.max(screen0.y, screen1.y));
        if (this.transform.projection.name === 'mercator' && this.transform.anyCornerOffEdge(screen0, screen1)) {
            return this;
        }
        const lnglat0 = this.transform.pointLocation3D(min);
        const lnglat1 = this.transform.pointLocation3D(max);
        const lnglat2 = this.transform.pointLocation3D(new Point$2(min.x, max.y));
        const lnglat3 = this.transform.pointLocation3D(new Point$2(max.x, min.y));
        const p0coord = [
            Math.min(lnglat0.lng, lnglat1.lng, lnglat2.lng, lnglat3.lng),
            Math.min(lnglat0.lat, lnglat1.lat, lnglat2.lat, lnglat3.lat)
        ];
        const p1coord = [
            Math.max(lnglat0.lng, lnglat1.lng, lnglat2.lng, lnglat3.lng),
            Math.max(lnglat0.lat, lnglat1.lat, lnglat2.lat, lnglat3.lat)
        ];
        const pitch = options && options.pitch ? options.pitch : this.getPitch();
        const cameraPlacement = this._cameraForBounds(this.transform, p0coord, p1coord, bearing, pitch, options);
        return this._fitInternal(cameraPlacement, options, eventData);
    }
    _fitInternal(calculatedOptions, options, eventData) {
        // cameraForBounds warns + returns undefined if unable to fit:
        if (!calculatedOptions)
            return this;
        options = extend$1(calculatedOptions, options);
        // Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly.
        delete options.padding;
        return options.linear ? this.easeTo(options, eventData) : this.flyTo(options, eventData);
    }
    /**
     * Changes any combination of center, zoom, bearing, and pitch, without
     * an animated transition. The map will retain its current values for any
     * details not specified in `options`.
     *
     * @memberof Map#
     * @param {CameraOptions} options Options object.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:pitchstart
     * @fires Map.event:rotate
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:pitch
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @fires Map.event:pitchend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // jump to coordinates at current zoom
     * map.jumpTo({center: [0, 0]});
     * // jump with zoom, pitch, and bearing options
     * map.jumpTo({
     *     center: [0, 0],
     *     zoom: 8,
     *     pitch: 45,
     *     bearing: 90
     * });
     * @see [Example: Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/)
     * @see [Example: Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/)
     */
    jumpTo(options, eventData) {
        this.stop();
        const tr = options.preloadOnly ? this.transform.clone() : this.transform;
        let zoomChanged = false, bearingChanged = false, pitchChanged = false;
        if ('zoom' in options && tr.zoom !== +options.zoom) {
            zoomChanged = true;
            tr.zoom = +options.zoom;
        }
        if (options.center !== undefined) {
            tr.center = LngLat$1.convert(options.center);
        }
        if ('bearing' in options && tr.bearing !== +options.bearing) {
            bearingChanged = true;
            tr.bearing = +options.bearing;
        }
        if ('pitch' in options && tr.pitch !== +options.pitch) {
            pitchChanged = true;
            tr.pitch = +options.pitch;
        }
        if (options.padding != null && !tr.isPaddingEqual(options.padding)) {
            // $FlowFixMe[incompatible-type] - Flow can't infer that padding is not null here
            tr.padding = options.padding;
        }
        if (options.preloadOnly) {
            this._preloadTiles(tr);
            return this;
        }
        this.fire(new Event('movestart', eventData)).fire(new Event('move', eventData));
        if (zoomChanged) {
            this.fire(new Event('zoomstart', eventData)).fire(new Event('zoom', eventData)).fire(new Event('zoomend', eventData));
        }
        if (bearingChanged) {
            this.fire(new Event('rotatestart', eventData)).fire(new Event('rotate', eventData)).fire(new Event('rotateend', eventData));
        }
        if (pitchChanged) {
            this.fire(new Event('pitchstart', eventData)).fire(new Event('pitch', eventData)).fire(new Event('pitchend', eventData));
        }
        return this.fire(new Event('moveend', eventData));
    }
    /**
     * Returns position and orientation of the camera entity.
     *
     * This method is not supported for projections other than mercator.
     *
     * @memberof Map#
     * @returns {FreeCameraOptions} The camera state.
     * @example
     * const camera = map.getFreeCameraOptions();
     *
     * const position = [138.72649, 35.33974];
     * const altitude = 3000;
     *
     * camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
     * camera.lookAtPoint([138.73036, 35.36197]);
     *
     * map.setFreeCameraOptions(camera);
     */
    getFreeCameraOptions() {
        if (!this.transform.projection.supportsFreeCamera) {
            warnOnce(freeCameraNotSupportedWarning);
        }
        return this.transform.getFreeCameraOptions();
    }
    /**
     * `FreeCameraOptions` provides more direct access to the underlying camera entity.
     * For backwards compatibility the state set using this API must be representable with
     * `CameraOptions` as well. Parameters are clamped into a valid range or discarded as invalid
     * if the conversion to the pitch and bearing presentation is ambiguous. For example orientation
     * can be invalid if it leads to the camera being upside down, the quaternion has zero length,
     * or the pitch is over the maximum pitch limit.
     *
     * This method is not supported for projections other than mercator.
     *
     * @memberof Map#
     * @param {FreeCameraOptions} options `FreeCameraOptions` object.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:pitchstart
     * @fires Map.event:rotate
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:pitch
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @fires Map.event:pitchend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * const camera = map.getFreeCameraOptions();
     *
     * const position = [138.72649, 35.33974];
     * const altitude = 3000;
     *
     * camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
     * camera.lookAtPoint([138.73036, 35.36197]);
     *
     * map.setFreeCameraOptions(camera);
     */
    setFreeCameraOptions(options, eventData) {
        const tr = this.transform;
        if (!tr.projection.supportsFreeCamera) {
            warnOnce(freeCameraNotSupportedWarning);
            return this;
        }
        this.stop();
        const prevZoom = tr.zoom;
        const prevPitch = tr.pitch;
        const prevBearing = tr.bearing;
        tr.setFreeCameraOptions(options);
        const zoomChanged = prevZoom !== tr.zoom;
        const pitchChanged = prevPitch !== tr.pitch;
        const bearingChanged = prevBearing !== tr.bearing;
        this.fire(new Event('movestart', eventData)).fire(new Event('move', eventData));
        if (zoomChanged) {
            this.fire(new Event('zoomstart', eventData)).fire(new Event('zoom', eventData)).fire(new Event('zoomend', eventData));
        }
        if (bearingChanged) {
            this.fire(new Event('rotatestart', eventData)).fire(new Event('rotate', eventData)).fire(new Event('rotateend', eventData));
        }
        if (pitchChanged) {
            this.fire(new Event('pitchstart', eventData)).fire(new Event('pitch', eventData)).fire(new Event('pitchend', eventData));
        }
        this.fire(new Event('moveend', eventData));
        return this;
    }
    /**
     * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition
     * between old and new values. The map will retain its current values for any
     * details not specified in `options`.
     *
     * Note: The transition will happen instantly if the user has enabled
     * the `reduced motion` accessibility feature enabled in their operating system,
     * unless `options` includes `essential: true`.
     *
     * @memberof Map#
     * @param {EasingOptions} options Options describing the destination and animation of the transition.
     *     Accepts {@link CameraOptions} and {@link AnimationOptions}.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:pitchstart
     * @fires Map.event:rotate
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:pitch
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @fires Map.event:pitchend
     * @returns {Map} `this` Returns itself to allow for method chaining.
     * @example
     * // Ease with default options to null island for 5 seconds.
     * map.easeTo({center: [0, 0], zoom: 9, duration: 5000});
     * @example
     * // Using easeTo options.
     * map.easeTo({
     *     center: [0, 0],
     *     zoom: 9,
     *     speed: 0.2,
     *     curve: 1,
     *     duration: 5000,
     *     easing(t) {
     *         return t;
     *     }
     * });
     * @see [Example: Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)
     */
    easeTo(options, eventData) {
        this._stop(false, options.easeId);
        options = extend$1({
            offset: [
                0,
                0
            ],
            duration: 500,
            easing: ease
        }, options);
        if (options.animate === false || this._prefersReducedMotion(options))
            options.duration = 0;
        const tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding(), zoom = 'zoom' in options ? +options.zoom : startZoom, bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = 'pitch' in options ? +options.pitch : startPitch, padding = 'padding' in options ? options.padding : tr.padding;
        const offsetAsPoint = Point$2.convert(options.offset);
        let pointAtOffset;
        let from;
        let delta;
        if (tr.projection.name === 'globe') {
            // Pixel coordinates will be applied directly to translate the globe
            const centerCoord = MercatorCoordinate.fromLngLat(tr.center);
            const rotatedOffset = offsetAsPoint.rotate(-tr.angle);
            centerCoord.x += rotatedOffset.x / tr.worldSize;
            centerCoord.y += rotatedOffset.y / tr.worldSize;
            const locationAtOffset = centerCoord.toLngLat();
            const center = LngLat$1.convert(options.center || locationAtOffset);
            this._normalizeCenter(center);
            pointAtOffset = tr.centerPoint.add(rotatedOffset);
            from = new Point$2(centerCoord.x, centerCoord.y).mult(tr.worldSize);
            delta = new Point$2(mercatorXfromLng(center.lng), mercatorYfromLat(center.lat)).mult(tr.worldSize).sub(from);
        } else {
            pointAtOffset = tr.centerPoint.add(offsetAsPoint);
            const locationAtOffset = tr.pointLocation(pointAtOffset);
            const center = LngLat$1.convert(options.center || locationAtOffset);
            this._normalizeCenter(center);
            from = tr.project(locationAtOffset);
            delta = tr.project(center).sub(from);
        }
        const finalScale = tr.zoomScale(zoom - startZoom);
        let around, aroundPoint;
        if (options.around) {
            around = LngLat$1.convert(options.around);
            aroundPoint = tr.locationPoint(around);
        }
        const zoomChanged = this._zooming || zoom !== startZoom;
        const bearingChanged = this._rotating || startBearing !== bearing;
        const pitchChanged = this._pitching || pitch !== startPitch;
        const paddingChanged = !tr.isPaddingEqual(padding);
        const frame = tr => k => {
            if (zoomChanged) {
                tr.zoom = number(startZoom, zoom, k);
            }
            if (bearingChanged) {
                tr.bearing = number(startBearing, bearing, k);
            }
            if (pitchChanged) {
                tr.pitch = number(startPitch, pitch, k);
            }
            if (paddingChanged) {
                tr.interpolatePadding(startPadding, padding, k);
                // When padding is being applied, Transform#centerPoint is changing continuously,
                // thus we need to recalculate offsetPoint every fra,e
                pointAtOffset = tr.centerPoint.add(offsetAsPoint);
            }
            if (around) {
                tr.setLocationAtPoint(around, aroundPoint);
            } else {
                const scale = tr.zoomScale(tr.zoom - startZoom);
                const base = zoom > startZoom ? Math.min(2, finalScale) : Math.max(0.5, finalScale);
                const speedup = Math.pow(base, 1 - k);
                const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale));
                tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
            }
            if (!options.preloadOnly) {
                this._fireMoveEvents(eventData);
            }
            return tr;
        };
        if (options.preloadOnly) {
            const predictedTransforms = this._emulate(frame, options.duration, tr);
            this._preloadTiles(predictedTransforms);
            return this;
        }
        const currently = {
            moving: this._moving,
            zooming: this._zooming,
            rotating: this._rotating,
            pitching: this._pitching
        };
        this._zooming = zoomChanged;
        this._rotating = bearingChanged;
        this._pitching = pitchChanged;
        this._padding = paddingChanged;
        this._easeId = options.easeId;
        this._prepareEase(eventData, options.noMoveStart, currently);
        this._ease(frame(tr), interruptingEaseId => {
            if (tr.cameraElevationReference === 'sea')
                tr.recenterOnTerrain();
            this._afterEase(eventData, interruptingEaseId);
        }, options);
        return this;
    }
    _prepareEase(eventData, noMoveStart, currently = {}) {
        this._moving = true;
        this.transform.cameraElevationReference = 'sea';
        if (this.transform._orthographicProjectionAtLowPitch && this.transform.pitch === 0 && this.transform.projection.name !== 'globe') {
            // Run easeTo on ground elevation reference. EaseTo is otherwise always on sea elevation reference,
            // triggering changes in center to camera distance and bumpy camera movement for ortho mode.
            this.transform.cameraElevationReference = 'ground';
        }
        if (!noMoveStart && !currently.moving) {
            this.fire(new Event('movestart', eventData));
        }
        if (this._zooming && !currently.zooming) {
            this.fire(new Event('zoomstart', eventData));
        }
        if (this._rotating && !currently.rotating) {
            this.fire(new Event('rotatestart', eventData));
        }
        if (this._pitching && !currently.pitching) {
            this.fire(new Event('pitchstart', eventData));
        }
    }
    _fireMoveEvents(eventData) {
        this.fire(new Event('move', eventData));
        if (this._zooming) {
            this.fire(new Event('zoom', eventData));
        }
        if (this._rotating) {
            this.fire(new Event('rotate', eventData));
        }
        if (this._pitching) {
            this.fire(new Event('pitch', eventData));
        }
    }
    _afterEase(eventData, easeId) {
        // if this easing is being stopped to start another easing with
        // the same id then don't fire any events to avoid extra start/stop events
        if (this._easeId && easeId && this._easeId === easeId) {
            return;
        }
        this._easeId = undefined;
        this.transform.cameraElevationReference = 'ground';
        const wasZooming = this._zooming;
        const wasRotating = this._rotating;
        const wasPitching = this._pitching;
        this._moving = false;
        this._zooming = false;
        this._rotating = false;
        this._pitching = false;
        this._padding = false;
        if (wasZooming) {
            this.fire(new Event('zoomend', eventData));
        }
        if (wasRotating) {
            this.fire(new Event('rotateend', eventData));
        }
        if (wasPitching) {
            this.fire(new Event('pitchend', eventData));
        }
        this.fire(new Event('moveend', eventData));
    }
    /**
     * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that
     * evokes flight. The animation seamlessly incorporates zooming and panning to help
     * the user maintain their bearings even after traversing a great distance.
     *
     * If a user has the `reduced motion` accessibility feature enabled in their
     * operating system, the animation will be skipped and this will behave
     * equivalently to `jumpTo`, unless 'options' includes `essential: true`.
     *
     * @memberof Map#
     * @param {Object} options Options describing the destination and animation of the transition.
     *     Accepts {@link CameraOptions}, {@link AnimationOptions},
     *     and the following additional options.
     * @param {number} [options.curve=1.42] The zooming "curve" that will occur along the
     *     flight path. A high value maximizes zooming for an exaggerated animation, while a low
     *     value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average
     *     value selected by participants in the user study discussed in
     *     [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of
     *     `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A
     *     value of 1 would produce a circular motion. If `options.minZoom` is specified, this option will be ignored.
     * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If
     *     this option is specified, `options.curve` will be ignored.
     * @param {number} [options.speed=1.2] The average speed of the animation defined in relation to
     *     `options.curve`. A speed of 1.2 means that the map appears to move along the flight path
     *     by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span.
     *     It does not correspond to a fixed physical distance, but varies by zoom level.
     * @param {number} [options.screenSpeed] The average speed of the animation measured in screenfuls
     *     per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored.
     * @param {number} [options.maxDuration] The animation's maximum duration, measured in milliseconds.
     *     If duration exceeds maximum duration, it resets to 0.
     * @param {Object | null} eventData Additional properties to be added to event objects of events triggered by this method.
     * @fires Map.event:movestart
     * @fires Map.event:zoomstart
     * @fires Map.event:pitchstart
     * @fires Map.event:move
     * @fires Map.event:zoom
     * @fires Map.event:rotate
     * @fires Map.event:pitch
     * @fires Map.event:moveend
     * @fires Map.event:zoomend
     * @fires Map.event:pitchend
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // fly with default options to null island
     * map.flyTo({center: [0, 0], zoom: 9});
     * // using flyTo options
     * map.flyTo({
     *     center: [0, 0],
     *     zoom: 9,
     *     speed: 0.2,
     *     curve: 1,
     *     easing(t) {
     *         return t;
     *     }
     * });
     * @see [Example: Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/)
     * @see [Example: Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/)
     * @see [Example: Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/)
     */
    flyTo(options, eventData) {
        // Fall through to jumpTo if user has set prefers-reduced-motion
        if (this._prefersReducedMotion(options)) {
            const coercedOptions = pick(options, [
                'center',
                'zoom',
                'bearing',
                'pitch',
                'around'
            ]);
            return this.jumpTo(coercedOptions, eventData);
        }
        // This method implements an “optimal path” animation, as detailed in:
        //
        // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS
        //   ’03. pp. 15–22. <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.
        //
        // Where applicable, local variable documentation begins with the associated variable or
        // function in van Wijk (2003).
        this.stop();
        options = extend$1({
            offset: [
                0,
                0
            ],
            speed: 1.2,
            curve: 1.42,
            easing: ease
        }, options);
        const tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding();
        const zoom = 'zoom' in options ? clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom;
        const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;
        const pitch = 'pitch' in options ? +options.pitch : startPitch;
        const padding = 'padding' in options ? options.padding : tr.padding;
        const scale = tr.zoomScale(zoom - startZoom);
        const offsetAsPoint = Point$2.convert(options.offset);
        let pointAtOffset = tr.centerPoint.add(offsetAsPoint);
        const locationAtOffset = tr.pointLocation(pointAtOffset);
        const center = LngLat$1.convert(options.center || locationAtOffset);
        this._normalizeCenter(center);
        const from = tr.project(locationAtOffset);
        const delta = tr.project(center).sub(from);
        let rho = options.curve;
        // w₀: Initial visible span, measured in pixels at the initial scale.
        const w0 = Math.max(tr.width, tr.height),
            // w₁: Final visible span, measured in pixels with respect to the initial scale.
            w1 = w0 / scale,
            // Length of the flight path as projected onto the ground plane, measured in pixels from
            // the world image origin at the initial scale.
            u1 = delta.mag();
        if ('minZoom' in options) {
            const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom);
            // w<sub>m</sub>: Maximum visible span, measured in pixels with respect to the initial
            // scale.
            const wMax = w0 / tr.zoomScale(minZoom - startZoom);
            rho = Math.sqrt(wMax / u1 * 2);
        }
        // ρ²
        const rho2 = rho * rho;
        /**
         * rᵢ: Returns the zoom-out factor at one end of the animation.
         *
         * @param i 0 for the ascent or 1 for the descent.
         * @private
         */
        function r(i) {
            const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1);
            return Math.log(Math.sqrt(b * b + 1) - b);
        }
        function sinh(n) {
            return (Math.exp(n) - Math.exp(-n)) / 2;
        }
        function cosh(n) {
            return (Math.exp(n) + Math.exp(-n)) / 2;
        }
        function tanh(n) {
            return sinh(n) / cosh(n);
        }
        // r₀: Zoom-out factor during ascent.
        const r0 = r(0);
        // w(s): Returns the visible span on the ground, measured in pixels with respect to the
        // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°.
        let w = function (s) {
            return cosh(r0) / cosh(r0 + rho * s);
        };
        // u(s): Returns the distance along the flight path as projected onto the ground plane,
        // measured in pixels from the world image origin at the initial scale.
        let u = function (s) {
            return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1;
        };
        // S: Total length of the flight path, measured in ρ-screenfuls.
        let S = (r(1) - r0) / rho;
        // When u₀ = u₁, the optimal path doesn’t require both ascent and descent.
        if (Math.abs(u1) < 0.000001 || !isFinite(S)) {
            // Perform a more or less instantaneous transition if the path is too short.
            if (Math.abs(w0 - w1) < 0.000001)
                return this.easeTo(options, eventData);
            const k = w1 < w0 ? -1 : 1;
            S = Math.abs(Math.log(w1 / w0)) / rho;
            u = function () {
                return 0;
            };
            w = function (s) {
                return Math.exp(k * rho * s);
            };
        }
        if ('duration' in options) {
            options.duration = +options.duration;
        } else {
            const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed;
            options.duration = 1000 * S / V;
        }
        if (options.maxDuration && options.duration > options.maxDuration) {
            options.duration = 0;
        }
        const zoomChanged = true;
        const bearingChanged = startBearing !== bearing;
        const pitchChanged = pitch !== startPitch;
        const paddingChanged = !tr.isPaddingEqual(padding);
        const frame = tr => k => {
            // s: The distance traveled along the flight path, measured in ρ-screenfuls.
            const s = k * S;
            const scale = 1 / w(s);
            tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale);
            if (bearingChanged) {
                tr.bearing = number(startBearing, bearing, k);
            }
            if (pitchChanged) {
                tr.pitch = number(startPitch, pitch, k);
            }
            if (paddingChanged) {
                tr.interpolatePadding(startPadding, padding, k);
                // When padding is being applied, Transform#centerPoint is changing continuously,
                // thus we need to recalculate offsetPoint every frame
                pointAtOffset = tr.centerPoint.add(offsetAsPoint);
            }
            const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale));
            tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
            tr._updateCameraOnTerrain();
            if (!options.preloadOnly) {
                this._fireMoveEvents(eventData);
            }
            return tr;
        };
        if (options.preloadOnly) {
            const predictedTransforms = this._emulate(frame, options.duration, tr);
            this._preloadTiles(predictedTransforms);
            return this;
        }
        this._zooming = zoomChanged;
        this._rotating = bearingChanged;
        this._pitching = pitchChanged;
        this._padding = paddingChanged;
        this._prepareEase(eventData, false);
        this._ease(frame(tr), () => this._afterEase(eventData), options);
        return this;
    }
    isEasing() {
        return !!this._easeFrameId;
    }
    /**
     * Stops any animated transition underway.
     *
     * @memberof Map#
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.stop();
     */
    stop() {
        return this._stop();
    }
    _stop(allowGestures, easeId) {
        if (this._easeFrameId) {
            this._cancelRenderFrame(this._easeFrameId);
            this._easeFrameId = undefined;
            this._onEaseFrame = undefined;
        }
        if (this._onEaseEnd) {
            // The _onEaseEnd function might emit events which trigger new
            // animation, which sets a new _onEaseEnd. Ensure we don't delete
            // it unintentionally.
            const onEaseEnd = this._onEaseEnd;
            this._onEaseEnd = undefined;
            onEaseEnd.call(this, easeId);
        }
        if (!allowGestures) {
            const handlers = this.handlers;
            if (handlers)
                handlers.stop(false);
        }
        return this;
    }
    _ease(frame, finish, options) {
        if (options.animate === false || options.duration === 0) {
            frame(1);
            finish();
        } else {
            this._easeStart = exported$1.now();
            this._easeOptions = options;
            this._onEaseFrame = frame;
            this._onEaseEnd = finish;
            // $FlowFixMe[method-unbinding]
            this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
        }
    }
    // Callback for map._requestRenderFrame
    _renderFrameCallback() {
        const t = Math.min((exported$1.now() - this._easeStart) / this._easeOptions.duration, 1);
        const frame = this._onEaseFrame;
        if (frame)
            frame(this._easeOptions.easing(t));
        if (t < 1) {
            // $FlowFixMe[method-unbinding]
            this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
        } else {
            this.stop();
        }
    }
    // convert bearing so that it's numerically close to the current one so that it interpolates properly
    _normalizeBearing(bearing, currentBearing) {
        bearing = wrap$1(bearing, -180, 180);
        const diff = Math.abs(bearing - currentBearing);
        if (Math.abs(bearing - 360 - currentBearing) < diff)
            bearing -= 360;
        if (Math.abs(bearing + 360 - currentBearing) < diff)
            bearing += 360;
        return bearing;
    }
    // If a path crossing the antimeridian would be shorter, extend the final coordinate so that
    // interpolating between the two endpoints will cross it.
    _normalizeCenter(center) {
        const tr = this.transform;
        if (!tr.renderWorldCopies || tr.maxBounds)
            return;
        const delta = center.lng - tr.center.lng;
        center.lng += delta > 180 ? -360 : delta < -180 ? 360 : 0;
    }
    _prefersReducedMotion(options) {
        const essential = options && options.essential;
        const prefersReducedMotion = this._respectPrefersReducedMotion && exported$1.prefersReducedMotion;
        return prefersReducedMotion && !essential;
    }
    // emulates frame function for some transform
    _emulate(frame, duration, initialTransform) {
        const frameRate = 15;
        const numFrames = Math.ceil(duration * frameRate / 1000);
        const transforms = [];
        const emulateFrame = frame(initialTransform.clone());
        for (let i = 0; i <= numFrames; i++) {
            const transform = emulateFrame(i / numFrames);
            transforms.push(transform.clone());
        }
        return transforms;
    }
}

//      
/**
 * An `AttributionControl` control presents the map's [attribution information](https://docs.mapbox.com/help/how-mapbox-works/attribution/).
 * Add this control to a map using {@link Map#addControl}.
 *
 * @implements {IControl}
 * @param {Object} [options]
 * @param {boolean} [options.compact] If `true`, force a compact attribution that shows the full attribution on mouse hover. If `false`, force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide. **Attribution should not be collapsed if it can comfortably fit on the map. `compact` should only be used to modify default attribution when map size makes it impossible to fit [default attribution](https://docs.mapbox.com/help/how-mapbox-works/attribution/) and when the automatic compact resizing for default settings are not sufficient**.
 * @param {string | Array<string>} [options.customAttribution] String or strings to show in addition to any other attributions. You can also set a custom attribution when initializing your map with {@link https://docs.mapbox.com/mapbox-gl-js/api/map/#map-parameters the customAttribution option}.
 * @example
 * const map = new mapboxgl.Map({attributionControl: false})
 *     .addControl(new mapboxgl.AttributionControl({
 *         customAttribution: 'Map design by me'
 *     }));
 */
class AttributionControl {
    constructor(options = {}) {
        this.options = options;
        bindAll([
            '_toggleAttribution',
            '_updateEditLink',
            '_updateData',
            '_updateCompact'
        ], this);
    }
    getDefaultPosition() {
        return 'bottom-right';
    }
    onAdd(map) {
        const compact = this.options && this.options.compact;
        this._map = map;
        this._container = create$a('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib');
        this._compactButton = create$a('button', 'mapboxgl-ctrl-attrib-button', this._container);
        create$a('span', `mapboxgl-ctrl-icon`, this._compactButton).setAttribute('aria-hidden', 'true');
        this._compactButton.type = 'button';
        // $FlowFixMe[method-unbinding]
        this._compactButton.addEventListener('click', this._toggleAttribution);
        this._setElementTitle(this._compactButton, 'ToggleAttribution');
        this._innerContainer = create$a('div', 'mapboxgl-ctrl-attrib-inner', this._container);
        if (compact) {
            this._container.classList.add('mapboxgl-compact');
        }
        this._updateAttributions();
        this._updateEditLink();
        // $FlowFixMe[method-unbinding]
        this._map.on('styledata', this._updateData);
        // $FlowFixMe[method-unbinding]
        this._map.on('sourcedata', this._updateData);
        // $FlowFixMe[method-unbinding]
        this._map.on('moveend', this._updateEditLink);
        if (compact === undefined) {
            // $FlowFixMe[method-unbinding]
            this._map.on('resize', this._updateCompact);
            this._updateCompact();
        }
        return this._container;
    }
    onRemove() {
        this._container.remove();
        // $FlowFixMe[method-unbinding]
        this._map.off('styledata', this._updateData);
        // $FlowFixMe[method-unbinding]
        this._map.off('sourcedata', this._updateData);
        // $FlowFixMe[method-unbinding]
        this._map.off('moveend', this._updateEditLink);
        // $FlowFixMe[method-unbinding]
        this._map.off('resize', this._updateCompact);
        this._map = undefined;
        this._attribHTML = undefined;
    }
    _setElementTitle(element, title) {
        const str = this._map._getUIString(`AttributionControl.${ title }`);
        element.setAttribute('aria-label', str);
        element.removeAttribute('title');
        if (element.firstElementChild)
            element.firstElementChild.setAttribute('title', str);
    }
    _toggleAttribution() {
        if (this._container.classList.contains('mapboxgl-compact-show')) {
            this._container.classList.remove('mapboxgl-compact-show');
            this._compactButton.setAttribute('aria-expanded', 'false');
        } else {
            this._container.classList.add('mapboxgl-compact-show');
            this._compactButton.setAttribute('aria-expanded', 'true');
        }
    }
    _updateEditLink() {
        let editLink = this._editLink;
        if (!editLink) {
            editLink = this._editLink = this._container.querySelector('.mapbox-improve-map');
        }
        const params = [
            {
                key: 'owner',
                value: this.styleOwner
            },
            {
                key: 'id',
                value: this.styleId
            },
            {
                key: 'access_token',
                value: this._map._requestManager._customAccessToken || config.ACCESS_TOKEN
            }
        ];
        if (editLink) {
            const paramString = params.reduce((acc, next, i) => {
                if (next.value) {
                    acc += `${ next.key }=${ next.value }${ i < params.length - 1 ? '&' : '' }`;
                }
                return acc;
            }, `?`);
            editLink.href = `${ config.FEEDBACK_URL }/${ paramString }#${ getHashString(this._map, true) }`;
            editLink.rel = 'noopener nofollow';
            this._setElementTitle(editLink, 'MapFeedback');
        }
    }
    _updateData(e) {
        if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style')) {
            this._updateAttributions();
            this._updateEditLink();
        }
    }
    _updateAttributions() {
        if (!this._map.style)
            return;
        let attributions = [];
        if (this._map.style.stylesheet) {
            const stylesheet = this._map.style.stylesheet;
            this.styleOwner = stylesheet.owner;
            this.styleId = stylesheet.id;
        }
        const sourceCaches = this._map.style._mergedSourceCaches;
        for (const id in sourceCaches) {
            const sourceCache = sourceCaches[id];
            if (sourceCache.used) {
                const source = sourceCache.getSource();
                if (source.attribution && attributions.indexOf(source.attribution) < 0) {
                    // $FlowFixMe[incompatible-call] - Flow can't infer that attribution is a string
                    attributions.push(source.attribution);
                }
            }
        }
        // remove any entries that are substrings of another entry.
        // first sort by length so that substrings come first
        attributions.sort((a, b) => a.length - b.length);
        attributions = attributions.filter((attrib, i) => {
            for (let j = i + 1; j < attributions.length; j++) {
                if (attributions[j].indexOf(attrib) >= 0) {
                    return false;
                }
            }
            return true;
        });
        if (this.options.customAttribution) {
            if (Array.isArray(this.options.customAttribution)) {
                attributions = [
                    ...this.options.customAttribution,
                    ...attributions
                ];
            } else {
                attributions.unshift(this.options.customAttribution);
            }
        }
        // check if attribution string is different to minimize DOM changes
        const attribHTML = attributions.join(' | ');
        if (attribHTML === this._attribHTML)
            return;
        this._attribHTML = attribHTML;
        if (attributions.length) {
            this._innerContainer.innerHTML = attribHTML;
            this._container.classList.remove('mapboxgl-attrib-empty');
        } else {
            this._container.classList.add('mapboxgl-attrib-empty');
        }
        // remove old DOM node from _editLink
        this._editLink = null;
    }
    _updateCompact() {
        if (this._map.getCanvasContainer().offsetWidth <= 640) {
            this._container.classList.add('mapboxgl-compact');
        } else {
            this._container.classList.remove('mapboxgl-compact', 'mapboxgl-compact-show');
        }
    }
}

//      
/**
 * A `LogoControl` is a control that adds the Mapbox watermark
 * to the map as required by the [terms of service](https://www.mapbox.com/tos/) for Mapbox
 * vector tiles and core styles.
 * Add this control to a map using {@link Map#addControl}.
 *
 * @implements {IControl}
 * @private
**/
class LogoControl {
    constructor() {
        bindAll([
            '_updateLogo',
            '_updateCompact'
        ], this);
    }
    onAdd(map) {
        this._map = map;
        this._container = create$a('div', 'mapboxgl-ctrl');
        const anchor = create$a('a', 'mapboxgl-ctrl-logo');
        anchor.target = '_blank';
        anchor.rel = 'noopener nofollow';
        anchor.href = 'https://www.mapbox.com/';
        anchor.setAttribute('aria-label', this._map._getUIString('LogoControl.Title'));
        anchor.setAttribute('rel', 'noopener nofollow');
        this._container.appendChild(anchor);
        this._container.style.display = 'none';
        // $FlowFixMe[method-unbinding]
        this._map.on('sourcedata', this._updateLogo);
        this._updateLogo();
        // $FlowFixMe[method-unbinding]
        this._map.on('resize', this._updateCompact);
        this._updateCompact();
        return this._container;
    }
    onRemove() {
        this._container.remove();
        // $FlowFixMe[method-unbinding]
        this._map.off('sourcedata', this._updateLogo);
        // $FlowFixMe[method-unbinding]
        this._map.off('resize', this._updateCompact);
    }
    getDefaultPosition() {
        return 'bottom-left';
    }
    _updateLogo(e) {
        if (!e || e.sourceDataType === 'metadata') {
            this._container.style.display = this._logoRequired() ? 'block' : 'none';
        }
    }
    _logoRequired() {
        if (!this._map.style)
            return true;
        const sourceCaches = this._map.style._sourceCaches;
        if (Object.entries(sourceCaches).length === 0)
            return true;
        for (const id in sourceCaches) {
            const source = sourceCaches[id].getSource();
            if (source.hasOwnProperty('mapbox_logo') && !source.mapbox_logo) {
                return false;
            }
        }
        return true;
    }
    _updateCompact() {
        const containerChildren = this._container.children;
        if (containerChildren.length) {
            const anchor = containerChildren[0];
            if (this._map.getCanvasContainer().offsetWidth < 250) {
                anchor.classList.add('mapboxgl-compact');
            } else {
                anchor.classList.remove('mapboxgl-compact');
            }
        }
    }
}

// can't mark opaque due to https://github.com/flowtype/flow-remove-types/pull/61
class TaskQueue {
    constructor() {
        this._queue = [];
        this._id = 0;
        this._cleared = false;
        this._currentlyRunning = false;
    }
    add(callback) {
        const id = ++this._id;
        const queue = this._queue;
        queue.push({
            callback,
            id,
            cancelled: false
        });
        return id;
    }
    remove(id) {
        const running = this._currentlyRunning;
        const queue = running ? this._queue.concat(running) : this._queue;
        for (const task of queue) {
            if (task.id === id) {
                task.cancelled = true;
                return;
            }
        }
    }
    run(timeStamp = 0) {
        const queue = this._currentlyRunning = this._queue;
        // Tasks queued by callbacks in the current queue should be executed
        // on the next run, not the current run.
        this._queue = [];
        for (const task of queue) {
            if (task.cancelled)
                continue;
            task.callback(timeStamp);
            if (this._cleared)
                break;
        }
        this._cleared = false;
        this._currentlyRunning = false;
    }
    clear() {
        if (this._currentlyRunning) {
            this._cleared = true;
        }
        this._queue = [];
    }
}

//      
/**
 * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted
 * n × 360° east or west for some n ≥ 0 such that:
 *
 * * the projected location of the result is on screen, if possible, and secondarily:
 * * the difference between the projected location of the result and the prior position
 *   is minimized.
 *
 * The object is to preserve perceived object constancy for Popups and Markers as much as
 * possible; they should avoid shifting large distances across the screen, even when the
 * map center changes by ±360° due to automatic wrapping, and when about to go off screen,
 * should wrap just enough to avoid doing so.
 *
 * @private
 */
function smartWrap (lngLat, priorPos, transform) {
    lngLat = new LngLat$1(lngLat.lng, lngLat.lat);
    // First, try shifting one world in either direction, and see if either is closer to the
    // prior position. Don't shift away if it new position is further from center.
    // This preserves object constancy when the map center is auto-wrapped during animations,
    // but don't allow it to run away on horizon (points towards horizon get closer and closer).
    if (priorPos) {
        const left = new LngLat$1(lngLat.lng - 360, lngLat.lat);
        const right = new LngLat$1(lngLat.lng + 360, lngLat.lat);
        // Unless offscreen, keep the marker within same wrap distance to center. This is to prevent
        // running it to infinity `lng` near horizon when bearing is ~90°.
        const withinWrap = Math.ceil(Math.abs(lngLat.lng - transform.center.lng) / 360) * 360;
        const delta = transform.locationPoint(lngLat).distSqr(priorPos);
        const offscreen = priorPos.x < 0 || priorPos.y < 0 || priorPos.x > transform.width || priorPos.y > transform.height;
        if (transform.locationPoint(left).distSqr(priorPos) < delta && (offscreen || Math.abs(left.lng - transform.center.lng) < withinWrap)) {
            lngLat = left;
        } else if (transform.locationPoint(right).distSqr(priorPos) < delta && (offscreen || Math.abs(right.lng - transform.center.lng) < withinWrap)) {
            lngLat = right;
        }
    }
    // Second, wrap toward the center until the new position is on screen, or we can't get
    // any closer.
    while (Math.abs(lngLat.lng - transform.center.lng) > 180) {
        const pos = transform.locationPoint(lngLat);
        if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) {
            break;
        }
        if (lngLat.lng > transform.center.lng) {
            lngLat.lng -= 360;
        } else {
            lngLat.lng += 360;
        }
    }
    return lngLat;
}

//      
const anchorTranslate = {
    'center': 'translate(-50%,-50%)',
    'top': 'translate(-50%,0)',
    'top-left': 'translate(0,0)',
    'top-right': 'translate(-100%,0)',
    'bottom': 'translate(-50%,-100%)',
    'bottom-left': 'translate(0,-100%)',
    'bottom-right': 'translate(-100%,-100%)',
    'left': 'translate(0,-50%)',
    'right': 'translate(-100%,-50%)'
};

//      
/**
 * Creates a marker component.
 *
 * @param {Object} [options]
 * @param {HTMLElement} [options.element] DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.
 * @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}.
 *     Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`.
 * @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.
 * @param {string} [options.color='#3FB1CE'] The color to use for the default marker if `options.element` is not provided. The default is light blue.
 * @param {number} [options.scale=1] The scale to use for the default marker if `options.element` is not provided. The default scale corresponds to a height of `41px` and a width of `27px`.
 * @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.
 * @param {number} [options.clickTolerance=0] The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map's `clickTolerance`.
 * @param {number} [options.rotation=0] The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise.
 * @param {string} [options.pitchAlignment='auto'] `'map'` aligns the `Marker` to the plane of the map. `'viewport'` aligns the `Marker` to the plane of the viewport. `'auto'` automatically matches the value of `rotationAlignment`.
 * @param {string} [options.rotationAlignment='auto'] The alignment of the marker's rotation.`'map'` is aligned with the map plane, consistent with the cardinal directions as the map rotates. `'viewport'` is screenspace-aligned. `'horizon'` is aligned according to the nearest horizon, on non-globe projections it is equivalent to `'viewport'`. `'auto'` is equivalent to `'viewport'`.
 * @param {number} [options.occludedOpacity=0.2] The opacity of a marker that's occluded by 3D terrain.
 * @param {string} [options.className] Space-separated CSS class names to add to marker element.
 * @example
 * // Create a new marker.
 * const marker = new mapboxgl.Marker()
 *     .setLngLat([30.5, 50.5])
 *     .addTo(map);
 * @example
 * // Set marker options.
 * const marker = new mapboxgl.Marker({
 *     color: "#FFFFFF",
 *     draggable: true
 * }).setLngLat([30.5, 50.5])
 *     .addTo(map);
 * @see [Example: Add custom icons with Markers](https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/)
 * @see [Example: Create a draggable Marker](https://www.mapbox.com/mapbox-gl-js/example/drag-a-marker/)
 */
class Marker extends Evented {
    // used for handling drag events
    // original tabindex of _element
    constructor(options, legacyOptions) {
        super();
        // For backward compatibility -- the constructor used to accept the element as a
        // required first argument, before it was made optional.
        if (options instanceof window$1.HTMLElement || legacyOptions) {
            options = extend$1({ element: options }, legacyOptions);
        }
        bindAll([
            '_update',
            '_onMove',
            '_onUp',
            '_addDragHandler',
            '_onMapClick',
            '_onKeyPress',
            '_clearFadeTimer'
        ], this);
        this._anchor = options && options.anchor || 'center';
        this._color = options && options.color || '#3FB1CE';
        this._scale = options && options.scale || 1;
        this._draggable = options && options.draggable || false;
        this._clickTolerance = options && options.clickTolerance || 0;
        this._isDragging = false;
        this._state = 'inactive';
        this._rotation = options && options.rotation || 0;
        this._rotationAlignment = options && options.rotationAlignment || 'auto';
        this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment || 'auto';
        this._updateMoving = () => this._update(true);
        this._occludedOpacity = options && options.occludedOpacity || 0.2;
        if (!options || !options.element) {
            this._defaultMarker = true;
            this._element = create$a('div');
            // create default map marker SVG
            const DEFAULT_HEIGHT = 41;
            const DEFAULT_WIDTH = 27;
            const svg = createSVG('svg', {
                display: 'block',
                height: `${ DEFAULT_HEIGHT * this._scale }px`,
                width: `${ DEFAULT_WIDTH * this._scale }px`,
                viewBox: `0 0 ${ DEFAULT_WIDTH } ${ DEFAULT_HEIGHT }`
            }, this._element);
            const gradient = createSVG('radialGradient', { id: 'shadowGradient' }, createSVG('defs', {}, svg));
            createSVG('stop', {
                offset: '10%',
                'stop-opacity': 0.4
            }, gradient);
            createSVG('stop', {
                offset: '100%',
                'stop-opacity': 0.05
            }, gradient);
            createSVG('ellipse', {
                cx: 13.5,
                cy: 34.8,
                rx: 10.5,
                ry: 5.25,
                fill: 'url(#shadowGradient)'
            }, svg);
            // shadow
            createSVG('path', {
                // marker shape
                fill: this._color,
                d: 'M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z'
            }, svg);
            createSVG('path', {
                // border
                opacity: 0.25,
                d: 'M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z'
            }, svg);
            createSVG('circle', {
                fill: 'white',
                cx: 13.5,
                cy: 13.5,
                r: 5.5
            }, svg);
            // circle
            // if no element and no offset option given apply an offset for the default marker
            // the -14 as the y value of the default marker offset was determined as follows
            //
            // the marker tip is at the center of the shadow ellipse from the default svg
            // the y value of the center of the shadow ellipse relative to the svg top left is 34.8
            // offset to the svg center "height (41 / 2)" gives 34.8 - (41 / 2) and rounded for an integer pixel offset gives 14
            // negative is used to move the marker up from the center so the tip is at the Marker lngLat
            this._offset = Point$2.convert(options && options.offset || [
                0,
                -14
            ]);
        } else {
            this._element = options.element;
            this._offset = Point$2.convert(options && options.offset || [
                0,
                0
            ]);
        }
        if (!this._element.hasAttribute('aria-label')) {
            this._element.setAttribute('aria-label', 'Map marker');
        }
        if (!this._element.hasAttribute('role')) {
            this._element.setAttribute('role', 'img');
        }
        this._element.classList.add('mapboxgl-marker');
        this._element.addEventListener('dragstart', e => {
            e.preventDefault();
        });
        this._element.addEventListener('mousedown', e => {
            // prevent focusing on click
            e.preventDefault();
        });
        const classList = this._element.classList;
        for (const key in anchorTranslate) {
            classList.remove(`mapboxgl-marker-anchor-${ key }`);
        }
        classList.add(`mapboxgl-marker-anchor-${ this._anchor }`);
        const classNames = options && options.className ? options.className.trim().split(/\s+/) : [];
        classList.add(...classNames);
        this._popup = null;
    }
    /**
     * Attaches the `Marker` to a `Map` object.
     *
     * @param {Map} map The Mapbox GL JS map to add the marker to.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * const marker = new mapboxgl.Marker()
     *     .setLngLat([30.5, 50.5])
     *     .addTo(map); // add the marker to the map
     */
    addTo(map) {
        if (map === this._map) {
            return this;
        }
        this.remove();
        this._map = map;
        map.getCanvasContainer().appendChild(this._element);
        map.on('move', this._updateMoving);
        // $FlowFixMe[method-unbinding]
        map.on('moveend', this._update);
        // $FlowFixMe[method-unbinding]
        map.on('remove', this._clearFadeTimer);
        map._addMarker(this);
        this.setDraggable(this._draggable);
        this._update();
        // If we attached the `click` listener to the marker element, the popup
        // would close once the event propogated to `map` due to the
        // `Popup#_onClickClose` listener.
        // $FlowFixMe[method-unbinding]
        map.on('click', this._onMapClick);
        return this;
    }
    /**
     * Removes the marker from a map.
     *
     * @example
     * const marker = new mapboxgl.Marker().addTo(map);
     * marker.remove();
     * @returns {Marker} Returns itself to allow for method chaining.
     */
    remove() {
        const map = this._map;
        if (map) {
            // $FlowFixMe[method-unbinding]
            map.off('click', this._onMapClick);
            map.off('move', this._updateMoving);
            // $FlowFixMe[method-unbinding]
            map.off('moveend', this._update);
            // $FlowFixMe[method-unbinding]
            map.off('mousedown', this._addDragHandler);
            // $FlowFixMe[method-unbinding]
            map.off('touchstart', this._addDragHandler);
            // $FlowFixMe[method-unbinding]
            map.off('mouseup', this._onUp);
            // $FlowFixMe[method-unbinding]
            map.off('touchend', this._onUp);
            // $FlowFixMe[method-unbinding]
            map.off('mousemove', this._onMove);
            // $FlowFixMe[method-unbinding]
            map.off('touchmove', this._onMove);
            // $FlowFixMe[method-unbinding]
            map.off('remove', this._clearFadeTimer);
            map._removeMarker(this);
            this._map = undefined;
        }
        this._clearFadeTimer();
        this._element.remove();
        if (this._popup)
            this._popup.remove();
        return this;
    }
    /**
     * Get the marker's geographical location.
     *
     * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously
     * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep
     * the marker on screen.
     *
     * @returns {LngLat} A {@link LngLat} describing the marker's location.
    * @example
    * // Store the marker's longitude and latitude coordinates in a variable
    * const lngLat = marker.getLngLat();
    * // Print the marker's longitude and latitude values in the console
    * console.log(`Longitude: ${lngLat.lng}, Latitude: ${lngLat.lat}`);
    * @see [Example: Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/)
    */
    getLngLat() {
        return this._lngLat;
    }
    /**
    * Set the marker's geographical position and move it.
     *
    * @param {LngLat} lnglat A {@link LngLat} describing where the marker should be located.
    * @returns {Marker} Returns itself to allow for method chaining.
    * @example
    * // Create a new marker, set the longitude and latitude, and add it to the map.
    * new mapboxgl.Marker()
    *     .setLngLat([-65.017, -16.457])
    *     .addTo(map);
    * @see [Example: Add custom icons with Markers](https://docs.mapbox.com/mapbox-gl-js/example/custom-marker-icons/)
    * @see [Example: Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/)
    * @see [Example: Add a marker using a place name](https://docs.mapbox.com/mapbox-gl-js/example/marker-from-geocode/)
    */
    setLngLat(lnglat) {
        this._lngLat = LngLat$1.convert(lnglat);
        this._pos = null;
        if (this._popup)
            this._popup.setLngLat(this._lngLat);
        this._update(true);
        return this;
    }
    /**
     * Returns the `Marker`'s HTML element.
     *
     * @returns {HTMLElement} Returns the marker element.
     * @example
     * const element = marker.getElement();
     */
    getElement() {
        return this._element;
    }
    /**
     * Binds a {@link Popup} to the {@link Marker}.
     *
     * @param {Popup | null} popup An instance of the {@link Popup} class. If undefined or null, any popup
     *     set on this {@link Marker} instance is unset.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * const marker = new mapboxgl.Marker()
     *     .setLngLat([0, 0])
     *     .setPopup(new mapboxgl.Popup().setHTML("<h1>Hello World!</h1>")) // add popup
     *     .addTo(map);
     * @see [Example: Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/)
     */
    setPopup(popup) {
        if (this._popup) {
            this._popup.remove();
            this._popup = null;
            this._element.removeAttribute('role');
            // $FlowFixMe[method-unbinding]
            this._element.removeEventListener('keypress', this._onKeyPress);
            if (!this._originalTabIndex) {
                this._element.removeAttribute('tabindex');
            }
        }
        if (popup) {
            if (!('offset' in popup.options)) {
                const markerHeight = 41 - 5.8 / 2;
                const markerRadius = 13.5;
                const linearOffset = Math.sqrt(Math.pow(markerRadius, 2) / 2);
                popup.options.offset = this._defaultMarker ? {
                    'top': [
                        0,
                        0
                    ],
                    'top-left': [
                        0,
                        0
                    ],
                    'top-right': [
                        0,
                        0
                    ],
                    'bottom': [
                        0,
                        -markerHeight
                    ],
                    'bottom-left': [
                        linearOffset,
                        (markerHeight - markerRadius + linearOffset) * -1
                    ],
                    'bottom-right': [
                        -linearOffset,
                        (markerHeight - markerRadius + linearOffset) * -1
                    ],
                    'left': [
                        markerRadius,
                        (markerHeight - markerRadius) * -1
                    ],
                    'right': [
                        -markerRadius,
                        (markerHeight - markerRadius) * -1
                    ]
                } : this._offset;
            }
            this._popup = popup;
            popup._marker = this;
            if (this._lngLat)
                this._popup.setLngLat(this._lngLat);
            this._element.setAttribute('role', 'button');
            this._originalTabIndex = this._element.getAttribute('tabindex');
            if (!this._originalTabIndex) {
                this._element.setAttribute('tabindex', '0');
            }
            // $FlowFixMe[method-unbinding]
            this._element.addEventListener('keypress', this._onKeyPress);
            this._element.setAttribute('aria-expanded', 'false');
        }
        return this;
    }
    _onKeyPress(e) {
        const code = e.code;
        const legacyCode = e.charCode || e.keyCode;
        if (code === 'Space' || code === 'Enter' || legacyCode === 32 || legacyCode === 13    // space or enter
) {
            this.togglePopup();
        }
    }
    _onMapClick(e) {
        const targetElement = e.originalEvent.target;
        const element = this._element;
        if (this._popup && (targetElement === element || element.contains(targetElement))) {
            this.togglePopup();
        }
    }
    /**
     * Returns the {@link Popup} instance that is bound to the {@link Marker}.
     *
     * @returns {Popup} Returns the popup.
     * @example
     * const marker = new mapboxgl.Marker()
     *     .setLngLat([0, 0])
     *     .setPopup(new mapboxgl.Popup().setHTML("<h1>Hello World!</h1>"))
     *     .addTo(map);
     *
     * console.log(marker.getPopup()); // return the popup instance
     */
    getPopup() {
        return this._popup;
    }
    /**
     * Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}.
     *
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * const marker = new mapboxgl.Marker()
     *     .setLngLat([0, 0])
     *     .setPopup(new mapboxgl.Popup().setHTML("<h1>Hello World!</h1>"))
     *     .addTo(map);
     *
     * marker.togglePopup(); // toggle popup open or closed
     */
    togglePopup() {
        const popup = this._popup;
        if (!popup) {
            return this;
        } else if (popup.isOpen()) {
            popup.remove();
            this._element.setAttribute('aria-expanded', 'false');
        } else if (this._map) {
            popup.addTo(this._map);
            this._element.setAttribute('aria-expanded', 'true');
        }
        return this;
    }
    _behindTerrain() {
        const map = this._map;
        const pos = this._pos;
        if (!map || !pos)
            return false;
        const unprojected = map.unproject(pos);
        const camera = map.getFreeCameraOptions();
        if (!camera.position)
            return false;
        const cameraLngLat = camera.position.toLngLat();
        const toClosestSurface = cameraLngLat.distanceTo(unprojected);
        const toMarker = cameraLngLat.distanceTo(this._lngLat);
        return toClosestSurface < toMarker * 0.9;
    }
    _evaluateOpacity() {
        const map = this._map;
        if (!map)
            return;
        const pos = this._pos;
        if (!pos || pos.x < 0 || pos.x > map.transform.width || pos.y < 0 || pos.y > map.transform.height) {
            this._clearFadeTimer();
            return;
        }
        const mapLocation = map.unproject(pos);
        let opacity;
        if (map._showingGlobe() && isLngLatBehindGlobe(map.transform, this._lngLat)) {
            opacity = 0;
        } else {
            opacity = 1 - map._queryFogOpacity(mapLocation);
            if (map.transform._terrainEnabled() && map.getTerrain() && this._behindTerrain()) {
                opacity *= this._occludedOpacity;
            }
        }
        this._element.style.opacity = `${ opacity }`;
        this._element.style.pointerEvents = opacity > 0 ? 'auto' : 'none';
        if (this._popup) {
            this._popup._setOpacity(opacity);
        }
        this._fadeTimer = null;
    }
    _clearFadeTimer() {
        if (this._fadeTimer) {
            clearTimeout(this._fadeTimer);
            this._fadeTimer = null;
        }
    }
    _updateDOM() {
        const pos = this._pos;
        const map = this._map;
        if (!pos || !map) {
            return;
        }
        const offset = this._offset.mult(this._scale);
        this._element.style.transform = `
            translate(${ pos.x }px,${ pos.y }px)
            ${ anchorTranslate[this._anchor] }
            ${ this._calculateXYTransform() } ${ this._calculateZTransform() }
            translate(${ offset.x }px,${ offset.y }px)
        `;
    }
    _calculateXYTransform() {
        const pos = this._pos;
        const map = this._map;
        const alignment = this.getPitchAlignment();
        // `viewport', 'auto' and invalid arugments do no pitch transformation.
        if (!map || !pos || alignment !== 'map') {
            return ``;
        }
        // 'map' alignment on a flat map
        if (!map._showingGlobe()) {
            const pitch = map.getPitch();
            return pitch ? `rotateX(${ pitch }deg)` : '';
        }
        // 'map' alignment on globe
        const tilt = radToDeg(globeTiltAtLngLat(map.transform, this._lngLat));
        const posFromCenter = pos.sub(globeCenterToScreenPoint(map.transform));
        const manhattanDistance = Math.abs(posFromCenter.x) + Math.abs(posFromCenter.y);
        if (manhattanDistance === 0) {
            return '';
        }
        const tiltOverDist = tilt / manhattanDistance;
        const yTilt = posFromCenter.x * tiltOverDist;
        const xTilt = -posFromCenter.y * tiltOverDist;
        return `rotateX(${ xTilt }deg) rotateY(${ yTilt }deg)`;
    }
    _calculateZTransform() {
        const pos = this._pos;
        const map = this._map;
        if (!map || !pos) {
            return '';
        }
        let rotation = 0;
        const alignment = this.getRotationAlignment();
        if (alignment === 'map') {
            if (map._showingGlobe()) {
                const north = map.project(new LngLat$1(this._lngLat.lng, this._lngLat.lat + 0.001));
                const south = map.project(new LngLat$1(this._lngLat.lng, this._lngLat.lat - 0.001));
                const diff = south.sub(north);
                rotation = radToDeg(Math.atan2(diff.y, diff.x)) - 90;
            } else {
                rotation = -map.getBearing();
            }
        } else if (alignment === 'horizon') {
            const ALIGN_TO_HORIZON_BELOW_ZOOM = 4;
            const ALIGN_TO_SCREEN_ABOVE_ZOOM = 6;
            const smooth = smoothstep(ALIGN_TO_HORIZON_BELOW_ZOOM, ALIGN_TO_SCREEN_ABOVE_ZOOM, map.getZoom());
            const centerPoint = globeCenterToScreenPoint(map.transform);
            centerPoint.y += smooth * map.transform.height;
            const rel = pos.sub(centerPoint);
            const angle = radToDeg(Math.atan2(rel.y, rel.x));
            const up = angle > 90 ? angle - 270 : angle + 90;
            rotation = up * (1 - smooth);
        }
        rotation += this._rotation;
        return rotation ? `rotateZ(${ rotation }deg)` : '';
    }
    _update(delaySnap) {
        window$1.cancelAnimationFrame(this._updateFrameId);
        const map = this._map;
        if (!map)
            return;
        if (map.transform.renderWorldCopies) {
            this._lngLat = smartWrap(this._lngLat, this._pos, map.transform);
        }
        this._pos = map.project(this._lngLat);
        // because rounding the coordinates at every `move` event causes stuttered zooming
        // we only round them when _update is called with `moveend` or when its called with
        // no arguments (when the Marker is initialized or Marker#setLngLat is invoked).
        if (delaySnap === true) {
            this._updateFrameId = window$1.requestAnimationFrame(() => {
                if (this._element && this._pos && this._anchor) {
                    this._pos = this._pos.round();
                    this._updateDOM();
                }
            });
        } else {
            this._pos = this._pos.round();
        }
        map._requestDomTask(() => {
            if (!this._map)
                return;
            if (this._element && this._pos && this._anchor) {
                this._updateDOM();
            }
            if ((map._showingGlobe() || map.getTerrain() || map.getFog()) && !this._fadeTimer) {
                // $FlowFixMe[method-unbinding]
                this._fadeTimer = setTimeout(this._evaluateOpacity.bind(this), 60);
            }
        });
    }
    /**
     * Get the marker's offset.
     *
     * @returns {Point} The marker's screen coordinates in pixels.
     * @example
     * const offset = marker.getOffset();
     */
    getOffset() {
        return this._offset;
    }
    /**
     * Sets the offset of the marker.
     *
     * @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.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * marker.setOffset([0, 1]);
     */
    setOffset(offset) {
        this._offset = Point$2.convert(offset);
        this._update();
        return this;
    }
    /**
     * Adds a CSS class to the marker element.
     *
     * @param {string} className Non-empty string with CSS class name to add to marker element.
     * @returns {Marker} Returns itself to allow for method chaining.
     *
     * @example
     * const marker = new mapboxgl.Marker();
     * marker.addClassName('some-class');
     */
    addClassName(className) {
        this._element.classList.add(className);
        return this;
    }
    /**
     * Removes a CSS class from the marker element.
     *
     * @param {string} className Non-empty string with CSS class name to remove from marker element.
     *
     * @returns {Marker} Returns itself to allow for method chaining.
     *
     * @example
     * const marker = new mapboxgl.Marker({className: 'some classes'});
     * marker.removeClassName('some');
     */
    removeClassName(className) {
        this._element.classList.remove(className);
        return this;
    }
    /**
     * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class.
     *
     * @param {string} className Non-empty string with CSS class name to add/remove.
     *
     * @returns {boolean} If the class was removed return `false`. If the class was added, then return `true`.
     *
     * @example
     * const marker = new mapboxgl.Marker();
     * marker.toggleClassName('highlighted');
     */
    toggleClassName(className) {
        return this._element.classList.toggle(className);
    }
    _onMove(e) {
        const map = this._map;
        if (!map)
            return;
        const startPos = this._pointerdownPos;
        const posDelta = this._positionDelta;
        if (!startPos || !posDelta)
            return;
        if (!this._isDragging) {
            const clickTolerance = this._clickTolerance || map._clickTolerance;
            if (e.point.dist(startPos) < clickTolerance)
                return;
            this._isDragging = true;
        }
        this._pos = e.point.sub(posDelta);
        this._lngLat = map.unproject(this._pos);
        this.setLngLat(this._lngLat);
        // suppress click event so that popups don't toggle on drag
        this._element.style.pointerEvents = 'none';
        // make sure dragstart only fires on the first move event after mousedown.
        // this can't be on mousedown because that event doesn't necessarily
        // imply that a drag is about to happen.
        if (this._state === 'pending') {
            this._state = 'active';
            /**
             * Fired when dragging starts.
             *
             * @event dragstart
             * @memberof Marker
             * @instance
             * @type {Object}
             * @property {Marker} marker The object that is being dragged.
             */
            this.fire(new Event('dragstart'));
        }
        /**
         * Fired while dragging.
         *
         * @event drag
         * @memberof Marker
         * @instance
         * @type {Object}
         * @property {Marker} marker The object that is being dragged.
         */
        this.fire(new Event('drag'));
    }
    _onUp() {
        // revert to normal pointer event handling
        this._element.style.pointerEvents = 'auto';
        this._positionDelta = null;
        this._pointerdownPos = null;
        this._isDragging = false;
        const map = this._map;
        if (map) {
            // $FlowFixMe[method-unbinding]
            map.off('mousemove', this._onMove);
            // $FlowFixMe[method-unbinding]
            map.off('touchmove', this._onMove);
        }
        // only fire dragend if it was preceded by at least one drag event
        if (this._state === 'active') {
            /**
            * Fired when the marker is finished being dragged.
            *
            * @event dragend
            * @memberof Marker
            * @instance
            * @type {Object}
            * @property {Marker} marker The object that was dragged.
            */
            this.fire(new Event('dragend'));
        }
        this._state = 'inactive';
    }
    _addDragHandler(e) {
        const map = this._map;
        const pos = this._pos;
        if (!map || !pos)
            return;
        if (this._element.contains(e.originalEvent.target)) {
            e.preventDefault();
            // We need to calculate the pixel distance between the click point
            // and the marker position, with the offset accounted for. Then we
            // can subtract this distance from the mousemove event's position
            // to calculate the new marker position.
            // If we don't do this, the marker 'jumps' to the click position
            // creating a jarring UX effect.
            this._positionDelta = e.point.sub(pos);
            this._pointerdownPos = e.point;
            this._state = 'pending';
            // $FlowFixMe[method-unbinding]
            map.on('mousemove', this._onMove);
            // $FlowFixMe[method-unbinding]
            map.on('touchmove', this._onMove);
            // $FlowFixMe[method-unbinding]
            map.once('mouseup', this._onUp);
            // $FlowFixMe[method-unbinding]
            map.once('touchend', this._onUp);
        }
    }
    /**
     * Sets the `draggable` property and functionality of the marker.
     *
     * @param {boolean} [shouldBeDraggable=false] Turns drag functionality on/off.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * marker.setDraggable(true);
     */
    setDraggable(shouldBeDraggable) {
        this._draggable = !!shouldBeDraggable;
        // convert possible undefined value to false
        // handle case where map may not exist yet
        // for example, when setDraggable is called before addTo
        const map = this._map;
        if (map) {
            if (shouldBeDraggable) {
                // $FlowFixMe[method-unbinding]
                map.on('mousedown', this._addDragHandler);
                // $FlowFixMe[method-unbinding]
                map.on('touchstart', this._addDragHandler);
            } else {
                // $FlowFixMe[method-unbinding]
                map.off('mousedown', this._addDragHandler);
                // $FlowFixMe[method-unbinding]
                map.off('touchstart', this._addDragHandler);
            }
        }
        return this;
    }
    /**
     * Returns true if the marker can be dragged.
     *
     * @returns {boolean} True if the marker is draggable.
     * @example
     * const isMarkerDraggable = marker.isDraggable();
     */
    isDraggable() {
        return this._draggable;
    }
    /**
     * Sets the `rotation` property of the marker.
     *
     * @param {number} [rotation=0] The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * marker.setRotation(45);
     */
    setRotation(rotation) {
        this._rotation = rotation || 0;
        this._update();
        return this;
    }
    /**
     * Returns the current rotation angle of the marker (in degrees).
     *
     * @returns {number} The current rotation angle of the marker.
     * @example
     * const rotation = marker.getRotation();
     */
    getRotation() {
        return this._rotation;
    }
    /**
     * Sets the `rotationAlignment` property of the marker.
     *
     * @param {string} [alignment='auto'] Sets the `rotationAlignment` property of the marker.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * marker.setRotationAlignment('viewport');
     */
    setRotationAlignment(alignment) {
        this._rotationAlignment = alignment || 'auto';
        this._update();
        return this;
    }
    /**
     * Returns the current `rotationAlignment` property of the marker.
     *
     * @returns {string} The current rotational alignment of the marker.
     * @example
     * const alignment = marker.getRotationAlignment();
     */
    getRotationAlignment() {
        if (this._rotationAlignment === 'auto')
            return 'viewport';
        if (this._rotationAlignment === 'horizon' && this._map && !this._map._showingGlobe())
            return 'viewport';
        return this._rotationAlignment;
    }
    /**
     * Sets the `pitchAlignment` property of the marker.
     *
     * @param {string} [alignment] Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * marker.setPitchAlignment('map');
     */
    setPitchAlignment(alignment) {
        this._pitchAlignment = alignment || 'auto';
        this._update();
        return this;
    }
    /**
     * Returns the current `pitchAlignment` behavior of the marker.
     *
     * @returns {string} The current pitch alignment of the marker.
     * @example
     * const alignment = marker.getPitchAlignment();
     */
    getPitchAlignment() {
        if (this._pitchAlignment === 'auto') {
            return this.getRotationAlignment();
        }
        return this._pitchAlignment;
    }
    /**
     * Sets the `occludedOpacity` property of the marker.
     * This opacity is used on the marker when the marker is occluded by terrain.
     *
     * @param {number} [opacity=0.2] Sets the `occludedOpacity` property of the marker.
     * @returns {Marker} Returns itself to allow for method chaining.
     * @example
     * marker.setOccludedOpacity(0.3);
     */
    setOccludedOpacity(opacity) {
        this._occludedOpacity = opacity || 0.2;
        this._update();
        return this;
    }
    /**
     * Returns the current `occludedOpacity` of the marker.
     *
     * @returns {number} The opacity of a terrain occluded marker.
     * @example
     * const opacity = marker.getOccludedOpacity();
     */
    getOccludedOpacity() {
        return this._occludedOpacity;
    }
}

//      
const defaultOptions$4 = {
    closeButton: true,
    closeOnClick: true,
    focusAfterOpen: true,
    className: '',
    maxWidth: '240px'
};
const focusQuerySelector = [
    'a[href]',
    '[tabindex]:not([tabindex=\'-1\'])',
    '[contenteditable]:not([contenteditable=\'false\'])',
    'button:not([disabled])',
    'input:not([disabled])',
    'select:not([disabled])',
    'textarea:not([disabled])'
].join(', ');
/**
 * A popup component.
 *
 * @param {Object} [options]
 * @param {boolean} [options.closeButton=true] If `true`, a close button will appear in the
 *     top right corner of the popup.
 * @param {boolean} [options.closeOnClick=true] If `true`, the popup will close when the
 *     map is clicked.
 * @param {boolean} [options.closeOnMove=false] If `true`, the popup will close when the
 *     map moves.
 * @param {boolean} [options.focusAfterOpen=true] If `true`, the popup will try to focus the
 *     first focusable element inside the popup.
 * @param {string} [options.anchor] - A string indicating the part of the popup that should
 *     be positioned closest to the coordinate, set via {@link Popup#setLngLat}.
 *     Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`,
 *     `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset, the anchor will be
 *     dynamically set to ensure the popup falls within the map container with a preference
 *     for `'bottom'`.
 * @param {number | PointLike | Object} [options.offset] -
 *     A pixel offset applied to the popup's location specified as:
 *     - a single number specifying a distance from the popup's location
 *     - a {@link PointLike} specifying a constant offset
 *     - an object of {@link Point}s specifing an offset for each anchor position.
 *
 *     Negative offsets indicate left and up.
 * @param {string} [options.className] Space-separated CSS class names to add to popup container.
 * @param {string} [options.maxWidth='240px'] -
 *     A string that sets the CSS property of the popup's maximum width (for example, `'300px'`).
 *     To ensure the popup resizes to fit its content, set this property to `'none'`.
 *     See the MDN documentation for the list of [available values](https://developer.mozilla.org/en-US/docs/Web/CSS/max-width).
 * @example
 * const markerHeight = 50;
 * const markerRadius = 10;
 * const linearOffset = 25;
 * const popupOffsets = {
 *     'top': [0, 0],
 *     'top-left': [0, 0],
 *     'top-right': [0, 0],
 *     'bottom': [0, -markerHeight],
 *     'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
 *     'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
 *     'left': [markerRadius, (markerHeight - markerRadius) * -1],
 *     'right': [-markerRadius, (markerHeight - markerRadius) * -1]
 * };
 * const popup = new mapboxgl.Popup({offset: popupOffsets, className: 'my-class'})
 *     .setLngLat(e.lngLat)
 *     .setHTML("<h1>Hello World!</h1>")
 *     .setMaxWidth("300px")
 *     .addTo(map);
 * @see [Example: Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)
 * @see [Example: Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
 * @see [Example: Display a popup on click](https://www.mapbox.com/mapbox-gl-js/example/popup-on-click/)
 * @see [Example: Attach a popup to a marker instance](https://www.mapbox.com/mapbox-gl-js/example/set-popup/)
 */
class Popup extends Evented {
    constructor(options) {
        super();
        this.options = extend$1(Object.create(defaultOptions$4), options);
        bindAll([
            '_update',
            '_onClose',
            'remove',
            '_onMouseEvent'
        ], this);
        this._classList = new Set(options && options.className ? options.className.trim().split(/\s+/) : []);
    }
    /**
     * Adds the popup to a map.
     *
     * @param {Map} map The Mapbox GL JS map to add the popup to.
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * new mapboxgl.Popup()
     *     .setLngLat([0, 0])
     *     .setHTML("<h1>Null Island</h1>")
     *     .addTo(map);
     * @see [Example: Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/)
     * @see [Example: Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
     * @see [Example: Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)
     * @see [Example: Show polygon information on click](https://docs.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/)
     */
    addTo(map) {
        if (this._map)
            this.remove();
        this._map = map;
        if (this.options.closeOnClick) {
            // $FlowFixMe[method-unbinding]
            map.on('preclick', this._onClose);
        }
        if (this.options.closeOnMove) {
            // $FlowFixMe[method-unbinding]
            map.on('move', this._onClose);
        }
        // $FlowFixMe[method-unbinding]
        map.on('remove', this.remove);
        this._update();
        map._addPopup(this);
        this._focusFirstElement();
        if (this._trackPointer) {
            // $FlowFixMe[method-unbinding]
            map.on('mousemove', this._onMouseEvent);
            // $FlowFixMe[method-unbinding]
            map.on('mouseup', this._onMouseEvent);
            map._canvasContainer.classList.add('mapboxgl-track-pointer');
        } else {
            // $FlowFixMe[method-unbinding]
            map.on('move', this._update);
        }
        /**
         * Fired when the popup is opened manually or programatically.
         *
         * @event open
         * @memberof Popup
         * @instance
         * @type {Object}
         * @property {Popup} popup Object that was opened.
         *
         * @example
         * // Create a popup
         * const popup = new mapboxgl.Popup();
         * // Set an event listener that will fire
         * // any time the popup is opened
         * popup.on('open', () => {
         *     console.log('popup was opened');
         * });
         */
        this.fire(new Event('open'));
        return this;
    }
    /**
     * Checks if a popup is open.
     *
     * @returns {boolean} `true` if the popup is open, `false` if it is closed.
     * @example
     * const isPopupOpen = popup.isOpen();
     */
    isOpen() {
        return !!this._map;
    }
    /**
     * Removes the popup from the map it has been added to.
     *
     * @example
     * const popup = new mapboxgl.Popup().addTo(map);
     * popup.remove();
     * @returns {Popup} Returns itself to allow for method chaining.
     */
    remove() {
        if (this._content) {
            this._content.remove();
        }
        if (this._container) {
            this._container.remove();
            this._container = undefined;
        }
        const map = this._map;
        if (map) {
            // $FlowFixMe[method-unbinding]
            map.off('move', this._update);
            // $FlowFixMe[method-unbinding]
            map.off('move', this._onClose);
            // $FlowFixMe[method-unbinding]
            map.off('preclick', this._onClose);
            // $FlowFixMe[method-unbinding]
            map.off('click', this._onClose);
            // $FlowFixMe[method-unbinding]
            map.off('remove', this.remove);
            // $FlowFixMe[method-unbinding]
            map.off('mousemove', this._onMouseEvent);
            // $FlowFixMe[method-unbinding]
            map.off('mouseup', this._onMouseEvent);
            // $FlowFixMe[method-unbinding]
            map.off('drag', this._onMouseEvent);
            if (map._canvasContainer) {
                map._canvasContainer.classList.remove('mapboxgl-track-pointer');
            }
            map._removePopup(this);
            this._map = undefined;
        }
        /**
         * Fired when the popup is closed manually or programatically.
         *
         * @event close
         * @memberof Popup
         * @instance
         * @type {Object}
         * @property {Popup} popup Object that was closed.
         *
         * @example
         * // Create a popup
         * const popup = new mapboxgl.Popup();
         * // Set an event listener that will fire
         * // any time the popup is closed
         * popup.on('close', () => {
         *     console.log('popup was closed');
         * });
         */
        this.fire(new Event('close'));
        return this;
    }
    /**
     * Returns the geographical location of the popup's anchor.
     *
     * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously
     * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep
     * the popup on screen.
     *
     * @returns {LngLat} The geographical location of the popup's anchor.
     * @example
     * const lngLat = popup.getLngLat();
     */
    getLngLat() {
        return this._lngLat;
    }
    /**
     * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.
     *
     * @param {LngLatLike} lnglat The geographical location to set as the popup's anchor.
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * popup.setLngLat([-122.4194, 37.7749]);
     */
    setLngLat(lnglat) {
        this._lngLat = LngLat$1.convert(lnglat);
        this._pos = null;
        this._trackPointer = false;
        this._update();
        const map = this._map;
        if (map) {
            // $FlowFixMe[method-unbinding]
            map.on('move', this._update);
            // $FlowFixMe[method-unbinding]
            map.off('mousemove', this._onMouseEvent);
            map._canvasContainer.classList.remove('mapboxgl-track-pointer');
        }
        return this;
    }
    /**
     * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior.
     * For most use cases, set `closeOnClick` and `closeButton` to `false`.
     *
     * @example
     * const popup = new mapboxgl.Popup({closeOnClick: false, closeButton: false})
     *     .setHTML("<h1>Hello World!</h1>")
     *     .trackPointer()
     *     .addTo(map);
     * @returns {Popup} Returns itself to allow for method chaining.
     */
    trackPointer() {
        this._trackPointer = true;
        this._pos = null;
        this._update();
        const map = this._map;
        if (map) {
            // $FlowFixMe[method-unbinding]
            map.off('move', this._update);
            // $FlowFixMe[method-unbinding]
            map.on('mousemove', this._onMouseEvent);
            // $FlowFixMe[method-unbinding]
            map.on('drag', this._onMouseEvent);
            map._canvasContainer.classList.add('mapboxgl-track-pointer');
        }
        return this;
    }
    /**
     * Returns the `Popup`'s HTML element.
     *
     * @example
     * // Change the `Popup` element's font size
     * const popup = new mapboxgl.Popup()
     *     .setLngLat([-96, 37.8])
     *     .setHTML("<p>Hello World!</p>")
     *     .addTo(map);
     * const popupElem = popup.getElement();
     * popupElem.style.fontSize = "25px";
     * @returns {HTMLElement} Returns container element.
     */
    getElement() {
        return this._container;
    }
    /**
     * Sets the popup's content to a string of text.
     *
     * This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM,
     * so it cannot insert raw HTML. Use this method for security against XSS
     * if the popup content is user-provided.
     *
     * @param {string} text Textual content for the popup.
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * const popup = new mapboxgl.Popup()
     *     .setLngLat(e.lngLat)
     *     .setText('Hello, world!')
     *     .addTo(map);
     */
    setText(text) {
        return this.setDOMContent(window$1.document.createTextNode(text));
    }
    /**
     * Sets the popup's content to the HTML provided as a string.
     *
     * This method does not perform HTML filtering or sanitization, and must be
     * used only with trusted content. Consider {@link Popup#setText} if
     * the content is an untrusted text string.
     *
     * @param {string} html A string representing HTML content for the popup.
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * const popup = new mapboxgl.Popup()
     *     .setLngLat(e.lngLat)
     *     .setHTML("<h1>Hello World!</h1>")
     *     .addTo(map);
     * @see [Example: Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/)
     * @see [Example: Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
     * @see [Example: Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)
     * @see [Example: Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/)
     */
    setHTML(html) {
        const frag = window$1.document.createDocumentFragment();
        const temp = window$1.document.createElement('body');
        let child;
        temp.innerHTML = html;
        while (true) {
            child = temp.firstChild;
            if (!child)
                break;
            frag.appendChild(child);
        }
        return this.setDOMContent(frag);
    }
    /**
     * Returns the popup's maximum width.
     *
     * @returns {string} The maximum width of the popup.
     * @example
     * const maxWidth = popup.getMaxWidth();
     */
    getMaxWidth() {
        return this._container && this._container.style.maxWidth;
    }
    /**
     * Sets the popup's maximum width. This is setting the CSS property `max-width`.
     * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width.
     *
     * @param {string} maxWidth A string representing the value for the maximum width.
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * popup.setMaxWidth('50');
     */
    setMaxWidth(maxWidth) {
        this.options.maxWidth = maxWidth;
        this._update();
        return this;
    }
    /**
     * Sets the popup's content to the element provided as a DOM node.
     *
     * @param {Element} htmlNode A DOM node to be used as content for the popup.
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * // create an element with the popup content
     * const div = window.document.createElement('div');
     * div.innerHTML = 'Hello, world!';
     * const popup = new mapboxgl.Popup()
     *     .setLngLat(e.lngLat)
     *     .setDOMContent(div)
     *     .addTo(map);
     */
    setDOMContent(htmlNode) {
        let content = this._content;
        if (content) {
            // Clear out children first.
            while (content.hasChildNodes()) {
                if (content.firstChild) {
                    content.removeChild(content.firstChild);
                }
            }
        } else {
            content = this._content = create$a('div', 'mapboxgl-popup-content', this._container || undefined);
        }
        // The close button should be the last tabbable element inside the popup for a good keyboard UX.
        content.appendChild(htmlNode);
        if (this.options.closeButton) {
            const button = this._closeButton = create$a('button', 'mapboxgl-popup-close-button', content);
            button.type = 'button';
            button.setAttribute('aria-label', 'Close popup');
            button.setAttribute('aria-hidden', 'true');
            button.innerHTML = '&#215;';
            // $FlowFixMe[method-unbinding]
            button.addEventListener('click', this._onClose);
        }
        this._update();
        this._focusFirstElement();
        return this;
    }
    /**
     * Adds a CSS class to the popup container element.
     *
     * @param {string} className Non-empty string with CSS class name to add to popup container.
     * @returns {Popup} Returns itself to allow for method chaining.
     *
     * @example
     * const popup = new mapboxgl.Popup();
     * popup.addClassName('some-class');
     */
    addClassName(className) {
        this._classList.add(className);
        this._updateClassList();
        return this;
    }
    /**
     * Removes a CSS class from the popup container element.
     *
     * @param {string} className Non-empty string with CSS class name to remove from popup container.
     *
     * @returns {Popup} Returns itself to allow for method chaining.
     * @example
     * const popup = new mapboxgl.Popup({className: 'some classes'});
     * popup.removeClassName('some');
     */
    removeClassName(className) {
        this._classList.delete(className);
        this._updateClassList();
        return this;
    }
    /* eslint-disable jsdoc/check-line-alignment */
    /**
     * Sets the popup's offset.
     *
     * @param {number | PointLike | Object} offset Sets the popup's offset. The `Object` is of the following structure
     *     {
     *         'center': ?PointLike,
     *         'top': ?PointLike,
     *         'bottom': ?PointLike,
     *         'left': ?PointLike,
     *         'right': ?PointLike,
     *         'top-left': ?PointLike,
     *         'top-right': ?PointLike,
     *         'bottom-left': ?PointLike,
     *         'bottom-right': ?PointLike
     *     }.
     *
     * @returns {Popup} `this`.
     * @example
     * popup.setOffset(10);
     */
    /* eslint-enable jsdoc/check-line-alignment */
    setOffset(offset) {
        this.options.offset = offset;
        this._update();
        return this;
    }
    /**
     * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.
     *
     * @param {string} className Non-empty string with CSS class name to add/remove.
     *
     * @returns {boolean} If the class was removed return `false`. If the class was added, then return `true`.
     *
     * @example
     * const popup = new mapboxgl.Popup();
     * popup.toggleClassName('highlighted');
     */
    toggleClassName(className) {
        let finalState;
        if (this._classList.delete(className)) {
            finalState = false;
        } else {
            this._classList.add(className);
            finalState = true;
        }
        this._updateClassList();
        return finalState;
    }
    _onMouseEvent(event) {
        this._update(event.point);
    }
    _getAnchor(bottomY) {
        if (this.options.anchor) {
            return this.options.anchor;
        }
        const map = this._map;
        const container = this._container;
        const pos = this._pos;
        if (!map || !container || !pos)
            return 'bottom';
        const width = container.offsetWidth;
        const height = container.offsetHeight;
        const isTop = pos.y + bottomY < height;
        const isBottom = pos.y > map.transform.height - height;
        const isLeft = pos.x < width / 2;
        const isRight = pos.x > map.transform.width - width / 2;
        if (isTop) {
            if (isLeft)
                return 'top-left';
            if (isRight)
                return 'top-right';
            return 'top';
        }
        if (isBottom) {
            if (isLeft)
                return 'bottom-left';
            if (isRight)
                return 'bottom-right';
        }
        if (isLeft)
            return 'left';
        if (isRight)
            return 'right';
        return 'bottom';
    }
    _updateClassList() {
        const container = this._container;
        if (!container)
            return;
        const classes = [...this._classList];
        classes.push('mapboxgl-popup');
        if (this._anchor) {
            classes.push(`mapboxgl-popup-anchor-${ this._anchor }`);
        }
        if (this._trackPointer) {
            classes.push('mapboxgl-popup-track-pointer');
        }
        container.className = classes.join(' ');
    }
    _update(cursor) {
        const hasPosition = this._lngLat || this._trackPointer;
        const map = this._map;
        const content = this._content;
        if (!map || !hasPosition || !content) {
            return;
        }
        let container = this._container;
        if (!container) {
            container = this._container = create$a('div', 'mapboxgl-popup', map.getContainer());
            this._tip = create$a('div', 'mapboxgl-popup-tip', container);
            container.appendChild(content);
        }
        if (this.options.maxWidth && container.style.maxWidth !== this.options.maxWidth) {
            container.style.maxWidth = this.options.maxWidth;
        }
        if (map.transform.renderWorldCopies && !this._trackPointer) {
            this._lngLat = smartWrap(this._lngLat, this._pos, map.transform);
        }
        if (!this._trackPointer || cursor) {
            const pos = this._pos = this._trackPointer && cursor ? cursor : map.project(this._lngLat);
            const offsetBottom = normalizeOffset(this.options.offset);
            const anchor = this._anchor = this._getAnchor(offsetBottom.y);
            const offset = normalizeOffset(this.options.offset, anchor);
            const offsetedPos = pos.add(offset).round();
            map._requestDomTask(() => {
                if (this._container && anchor) {
                    this._container.style.transform = `${ anchorTranslate[anchor] } translate(${ offsetedPos.x }px,${ offsetedPos.y }px)`;
                }
            });
        }
        if (!this._marker && map._showingGlobe()) {
            const opacity = isLngLatBehindGlobe(map.transform, this._lngLat) ? 0 : 1;
            this._setOpacity(opacity);
        }
        this._updateClassList();
    }
    _focusFirstElement() {
        if (!this.options.focusAfterOpen || !this._container)
            return;
        const firstFocusable = this._container.querySelector(focusQuerySelector);
        if (firstFocusable)
            firstFocusable.focus();
    }
    _onClose() {
        this.remove();
    }
    _setOpacity(opacity) {
        if (this._container) {
            this._container.style.opacity = `${ opacity }`;
        }
        if (this._content) {
            this._content.style.pointerEvents = opacity ? 'auto' : 'none';
        }
    }
}
// returns a normalized offset for a given anchor
function normalizeOffset(offset = new Point$2(0, 0), anchor = 'bottom') {
    if (typeof offset === 'number') {
        // input specifies a radius from which to calculate offsets at all positions
        const cornerOffset = Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));
        switch (anchor) {
        case 'top':
            return new Point$2(0, offset);
        case 'top-left':
            return new Point$2(cornerOffset, cornerOffset);
        case 'top-right':
            return new Point$2(-cornerOffset, cornerOffset);
        case 'bottom':
            return new Point$2(0, -offset);
        case 'bottom-left':
            return new Point$2(cornerOffset, -cornerOffset);
        case 'bottom-right':
            return new Point$2(-cornerOffset, -cornerOffset);
        case 'left':
            return new Point$2(offset, 0);
        case 'right':
            return new Point$2(-offset, 0);
        }
        return new Point$2(0, 0);
    }
    if (offset instanceof Point$2 || Array.isArray(offset)) {
        // input specifies a single offset to be applied to all positions
        return Point$2.convert(offset);
    }
    // input specifies an offset per position
    // $FlowFixMe we know offset is an object at this point but Flow can't refine it for some reason
    return Point$2.convert(offset[anchor] || [
        0,
        0
    ]);
}

//      
/**
 * An object for maintaining just enough state to ease a variable.
 *
 * @private
 */
class EasedVariable {
    constructor(initialValue) {
        this.jumpTo(initialValue);
    }
    /**
     * Evaluate the current value, given a timestamp.
     *
     * @param timeStamp {number} Time at which to evaluate.
     *
     * @returns {number} Evaluated value.
     */
    getValue(timeStamp) {
        if (timeStamp <= this._startTime)
            return this._start;
        if (timeStamp >= this._endTime)
            return this._end;
        const t = easeCubicInOut((timeStamp - this._startTime) / (this._endTime - this._startTime));
        return this._start * (1 - t) + this._end * t;
    }
    /**
     * Check if an ease is in progress.
     *
     * @param timeStamp {number} Current time stamp.
     *
     * @returns {boolean} Returns `true` if ease is in progress.
     */
    isEasing(timeStamp) {
        return timeStamp >= this._startTime && timeStamp <= this._endTime;
    }
    /**
     * Set the value without easing and cancel any in progress ease.
     *
     * @param value {number} New value.
     */
    jumpTo(value) {
        this._startTime = -Infinity;
        this._endTime = -Infinity;
        this._start = value;
        this._end = value;
    }
    /**
     * Cancel any in-progress ease and begin a new ease.
     *
     * @param value {number} New value to which to ease.
     * @param timeStamp {number} Current time stamp.
     * @param duration {number} Ease duration, in same units as timeStamp.
     */
    easeTo(value, timeStamp, duration) {
        this._start = this.getValue(timeStamp);
        this._end = value;
        this._startTime = timeStamp;
        this._endTime = timeStamp + duration;
    }
}

//      
const defaultLocale = {
    'AttributionControl.ToggleAttribution': 'Toggle attribution',
    'AttributionControl.MapFeedback': 'Map feedback',
    'FullscreenControl.Enter': 'Enter fullscreen',
    'FullscreenControl.Exit': 'Exit fullscreen',
    'GeolocateControl.FindMyLocation': 'Find my location',
    'GeolocateControl.LocationNotAvailable': 'Location not available',
    'LogoControl.Title': 'Mapbox logo',
    'Map.Title': 'Map',
    'NavigationControl.ResetBearing': 'Reset bearing to north',
    'NavigationControl.ZoomIn': 'Zoom in',
    'NavigationControl.ZoomOut': 'Zoom out',
    'ScrollZoomBlocker.CtrlMessage': 'Use ctrl + scroll to zoom the map',
    'ScrollZoomBlocker.CmdMessage': 'Use \u2318 + scroll to zoom the map',
    'TouchPanBlocker.Message': 'Use two fingers to move the map'
};

//      
/* eslint-disable no-use-before-define */
/* eslint-enable no-use-before-define */
const AVERAGE_ELEVATION_SAMPLING_INTERVAL = 500;
// ms
const AVERAGE_ELEVATION_EASE_TIME = 300;
// ms
const AVERAGE_ELEVATION_EASE_THRESHOLD = 1;
// meters
const AVERAGE_ELEVATION_CHANGE_THRESHOLD = 0.0001;
// meters
const defaultMinZoom = -2;
const defaultMaxZoom = 22;
// the default values, but also the valid range
const defaultMinPitch = 0;
const defaultMaxPitch = 85;
const defaultOptions$3 = {
    center: [
        0,
        0
    ],
    zoom: 0,
    bearing: 0,
    pitch: 0,
    minZoom: defaultMinZoom,
    maxZoom: defaultMaxZoom,
    minPitch: defaultMinPitch,
    maxPitch: defaultMaxPitch,
    interactive: true,
    scrollZoom: true,
    boxZoom: true,
    dragRotate: true,
    dragPan: true,
    keyboard: true,
    doubleClickZoom: true,
    touchZoomRotate: true,
    touchPitch: true,
    cooperativeGestures: false,
    performanceMetricsCollection: true,
    bearingSnap: 7,
    clickTolerance: 3,
    pitchWithRotate: true,
    hash: false,
    attributionControl: true,
    antialias: false,
    failIfMajorPerformanceCaveat: false,
    preserveDrawingBuffer: false,
    trackResize: true,
    renderWorldCopies: true,
    refreshExpiredTiles: true,
    minTileCacheSize: null,
    maxTileCacheSize: null,
    localIdeographFontFamily: 'sans-serif',
    localFontFamily: null,
    transformRequest: null,
    accessToken: null,
    fadeDuration: 300,
    respectPrefersReducedMotion: true,
    crossSourceCollisions: true,
    collectResourceTiming: false,
    testMode: false
};
/**
 * The `Map` object represents the map on your page. It exposes methods
 * and properties that enable you to programmatically change the map,
 * and fires events as users interact with it.
 *
 * You create a `Map` by specifying a `container` and other options.
 * Then Mapbox GL JS initializes the map on the page and returns your `Map`
 * object.
 *
 * @extends Evented
 * @param {Object} options
 * @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.
 * @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24).
 * @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24).
 * @param {number} [options.minPitch=0] The minimum pitch of the map (0-85).
 * @param {number} [options.maxPitch=85] The maximum pitch of the map (0-85).
 * @param {Object | string} [options.style='mapbox://styles/mapbox/standard'] The map's Mapbox style. This must be an a JSON object conforming to
 *     the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL
 *     to such JSON. Can accept a null value to allow adding a style manually.
 *
 *     To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`,
 *     where `:owner` is your Mapbox account name and `:style` is the style ID. You can also use a
 *     [Mapbox-owned style](https://docs.mapbox.com/api/maps/styles/#mapbox-styles):
 *
 *     * `mapbox://styles/mapbox/standard`
 *     * `mapbox://styles/mapbox/streets-v12`
 *     * `mapbox://styles/mapbox/outdoors-v12`
 *     * `mapbox://styles/mapbox/light-v11`
 *     * `mapbox://styles/mapbox/dark-v11`
 *     * `mapbox://styles/mapbox/satellite-v9`
 *     * `mapbox://styles/mapbox/satellite-streets-v12`
 *     * `mapbox://styles/mapbox/navigation-day-v1`
 *     * `mapbox://styles/mapbox/navigation-night-v1`.
 *
 *     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-v11?optimize=true`.
 *     Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/maps/#retrieve-tiles).
 *
 * @param {(boolean|string)} [options.hash=false] If `true`, the map's [position](https://docs.mapbox.com/help/glossary/camera) (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL.
 *     For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`.
 *     An additional string may optionally be provided to indicate a parameter-styled hash,
 *     for example http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where `foo`
 *     is a custom parameter and `bar` is an arbitrary hash distinct from the map hash.
 * @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.
 * @param {number} [options.bearingSnap=7] The threshold, measured in degrees, that determines when the map's
 *     bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates
 *     the map within 7 degrees of north, the map will automatically snap to exact north.
 * @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.
 * @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).
 * @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map.
 * @param {string | Array<string>} [options.customAttribution=null] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`.
 * @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`.
 * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox GL JS would be dramatically worse than expected (a software renderer would be used).
 * @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.
 * @param {boolean} [options.antialias=false] If `true`, the gl context will be created with [MSAA antialiasing](https://en.wikipedia.org/wiki/Multisample_anti-aliasing), which can be useful for antialiasing custom layers. This is `false` by default as a performance optimization.
 * @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.
 * @param {LngLatBoundsLike} [options.maxBounds=null] If set, the map will be constrained to the given bounds.
 * @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}.
 * @param {boolean} [options.boxZoom=true] If `true`, the "box zoom" interaction is enabled (see {@link BoxZoomHandler}).
 * @param {boolean} [options.dragRotate=true] If `true`, the "drag to rotate" interaction is enabled (see {@link DragRotateHandler}).
 * @param {boolean | Object} [options.dragPan=true] If `true`, the "drag to pan" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}.
 * @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).
 * @param {boolean} [options.doubleClickZoom=true] If `true`, the "double click to zoom" interaction is enabled (see {@link DoubleClickZoomHandler}).
 * @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}.
 * @param {boolean | Object} [options.touchPitch=true] If `true`, the "drag to pitch" interaction is enabled. An `Object` value is passed as options to {@link TouchPitchHandler}.
 * @param {boolean} [options.cooperativeGestures] If `true`, scroll zoom will require pressing the ctrl or ⌘ key while scrolling to zoom map, and touch pan will require using two fingers while panning to move the map. Touch pitch will require three fingers to activate if enabled.
 * @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes.
 * @param {boolean} [options.performanceMetricsCollection=true] If `true`, mapbox-gl will collect and send performance metrics.
 * @param {LngLatLike} [options.center=[0, 0]] The initial geographical [centerpoint](https://docs.mapbox.com/help/glossary/camera#center) 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.
 * @param {number} [options.zoom=0] The initial [zoom](https://docs.mapbox.com/help/glossary/camera#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`.
 * @param {number} [options.bearing=0] The initial [bearing](https://docs.mapbox.com/help/glossary/camera#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`.
 * @param {number} [options.pitch=0] The initial [pitch](https://docs.mapbox.com/help/glossary/camera#pitch) (tilt) of the map, measured in degrees away from the plane of the screen (0-85). If `pitch` is not specified in the constructor options, 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`.
 * @param {LngLatBoundsLike} [options.bounds=null] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.
 * @param {Object} [options.fitBoundsOptions=null] A {@link Map#fitBounds} options object to use _only_ when fitting the initial `bounds` provided above.
 * @param {'auto' | string | string[]} [options.language=null] A string with a BCP 47 language tag, or an array of such strings representing the desired languages used for the map's labels and UI components. Languages can only be set on Mapbox vector tile sources.
 *     By default, GL JS will not set a language so that the language of Mapbox tiles will be determined by the vector tile source's TileJSON.
 *     Valid language strings must be a [BCP-47 language code](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_subtags). Unsupported BCP-47 codes will not include any translations. Invalid codes will result in an recoverable error.
 *     If a label has no translation for the selected language, it will display in the label's local language.
 *     If option is set to `auto`, GL JS will select a user's preferred language as determined by the browser's [`window.navigator.language`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) property.
 *     If the `locale` property is not set separately, this language will also be used to localize the UI for supported languages.
 * @param {string} [options.worldview=null] Sets the map's worldview. A worldview determines the way that certain disputed boundaries
 *     are rendered. By default, GL JS will not set a worldview so that the worldview of Mapbox tiles will be determined by the vector tile source's TileJSON.
 *     Valid worldview strings must be an [ISO alpha-2 country code](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes). Unsupported
 *     ISO alpha-2 codes will fall back to the TileJSON's default worldview. Invalid codes will result in a recoverable error.
 * @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
 *     - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
 *     container, there will be blank space beyond 180 and -180 degrees longitude.
 *     - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
 *     map and the other on the left edge of the map) at every zoom level.
 * @param {number} [options.minTileCacheSize=null] The minimum number of tiles stored in the tile cache for a given source. Larger viewports use more tiles and need larger caches. Larger viewports are more likely to be found on devices with more memory and on pages where the map is more important. If omitted, the cache will be dynamically sized based on the current viewport.
 * @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.
 * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana', 'Hangul Syllables' and 'CJK Symbols and Punctuation' ranges.
 *     In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).
 *     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.
 *     The purpose of this option is to avoid bandwidth-intensive glyph server requests. For an example of this option in use, see [Use locally generated ideographs](https://www.mapbox.com/mapbox-gl-js/example/local-ideographs).
 * @param {string} [options.localFontFamily=null] Defines a CSS
 *     font-family for locally overriding generation of all glyphs. Font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).
 *     If set, this option overrides the setting in localIdeographFontFamily.
 * @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.
 *     Expected to return a {@link RequestParameters} object with a `url` property and optionally `headers` and `credentials` properties.
 * @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.
 * @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.
 * @param {boolean} [options.respectPrefersReducedMotion=true] If set to `true`, the map will respect the user's `prefers-reduced-motion` browser setting and apply a reduced motion mode, minimizing animations and transitions. When set to `false`, the map will always ignore the `prefers-reduced-motion` settings, regardless of the user's preference, making all animations essential.
 * @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.
 * @param {string} [options.accessToken=null] If specified, map will use this [token](https://docs.mapbox.com/help/glossary/access-token/) instead of the one defined in `mapboxgl.accessToken`.
 * @param {Object} [options.locale=null] A patch to apply to the default localization table for UI strings such as control tooltips. The `locale` object maps namespaced UI string IDs to translated strings in the target language;
 *     see [`src/ui/default_locale.js`](https://github.com/mapbox/mapbox-gl-js/blob/main/src/ui/default_locale.js) for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table).
 * @param {boolean} [options.testMode=false] Silences errors and warnings generated due to an invalid accessToken, useful when using the library to write unit tests.
 * @param {ProjectionSpecification} [options.projection='mercator'] The [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) the map should be rendered in.
 *     Supported projections are:
 *     * [Albers](https://en.wikipedia.org/wiki/Albers_projection) equal-area conic projection as `albers`
 *     * [Equal Earth](https://en.wikipedia.org/wiki/Equal_Earth_projection) equal-area pseudocylindrical projection as `equalEarth`
 *     * [Equirectangular](https://en.wikipedia.org/wiki/Equirectangular_projection) (Plate Carrée/WGS84) as `equirectangular`
 *     * 3d Globe as `globe`
 *     * [Lambert Conformal Conic](https://en.wikipedia.org/wiki/Lambert_conformal_conic_projection) as `lambertConformalConic`
 *     * [Mercator](https://en.wikipedia.org/wiki/Mercator_projection) cylindrical map projection as `mercator`
 *     * [Natural Earth](https://en.wikipedia.org/wiki/Natural_Earth_projection) pseudocylindrical map projection as `naturalEarth`
 *     * [Winkel Tripel](https://en.wikipedia.org/wiki/Winkel_tripel_projection) azimuthal map projection as `winkelTripel`
 *     Conic projections such as Albers and Lambert have configurable `center` and `parallels` properties that allow developers to define the region in which the projection has minimal distortion; see the example for how to configure these properties.
 * @example
 * const map = new mapboxgl.Map({
 *     container: 'map', // container ID
 *     center: [-122.420679, 37.772537], // starting position [lng, lat]
 *     zoom: 13, // starting zoom
 *     style: 'mapbox://styles/mapbox/streets-v11', // style URL or style object
 *     hash: true, // sync `center`, `zoom`, `pitch`, and `bearing` with URL
 *     // Use `transformRequest` to modify requests that begin with `http://myHost`.
 *     transformRequest: (url, resourceType) => {
 *         if (resourceType === 'Source' && url.startsWith('http://myHost')) {
 *             return {
 *                 url: url.replace('http', 'https'),
 *                 headers: {'my-custom-header': true},
 *                 credentials: 'include'  // Include cookies for cross-origin requests
 *             };
 *         }
 *     }
 * });
 * @see [Example: Display a map on a webpage](https://docs.mapbox.com/mapbox-gl-js/example/simple-map/)
 * @see [Example: Display a map with a custom style](https://docs.mapbox.com/mapbox-gl-js/example/custom-style-id/)
 * @see [Example: Check if Mapbox GL JS is supported](https://docs.mapbox.com/mapbox-gl-js/example/check-for-support/)
 */
let Map$1 = class Map extends Camera {
    // accounts for placement finishing as well
    // `_useExplicitProjection` indicates that a projection is set by a call to map.setProjection()
    /** @section {Interaction handlers} */
    /**
     * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.
     * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section.
     */
    /**
     * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed.
     * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section.
     */
    /**
     * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right
     * mouse button or with the Control key pressed. Find more details and examples using `dragRotate`
     * in the {@link DragRotateHandler} section.
     */
    /**
     * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.
     * Find more details and examples using `dragPan` in the {@link DragPanHandler} section.
     */
    /**
     * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard
     * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section.
     */
    /**
     * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.
     * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section.
     */
    /**
     * The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.
     * Find more details and examples using `touchZoomRotate` in the {@link TouchZoomRotateHandler} section.
     */
    /**
     * The map's {@link TouchPitchHandler}, which allows the user to pitch the map with touch gestures.
     * Find more details and examples using `touchPitch` in the {@link TouchPitchHandler} section.
     */
    constructor(options) {
        LivePerformanceUtils.mark(PerformanceMarkers.create);
        options = extend$1({}, defaultOptions$3, options);
        if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) {
            throw new Error(`maxZoom must be greater than or equal to minZoom`);
        }
        if (options.minPitch != null && options.maxPitch != null && options.minPitch > options.maxPitch) {
            throw new Error(`maxPitch must be greater than or equal to minPitch`);
        }
        if (options.minPitch != null && options.minPitch < defaultMinPitch) {
            throw new Error(`minPitch must be greater than or equal to ${ defaultMinPitch }`);
        }
        if (options.maxPitch != null && options.maxPitch > defaultMaxPitch) {
            throw new Error(`maxPitch must be less than or equal to ${ defaultMaxPitch }`);
        }
        // disable antialias with OS/iOS 15.4 and 15.5 due to rendering bug
        if (options.antialias && isSafariWithAntialiasingBug(window$1)) {
            options.antialias = false;
            warnOnce('Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609');
        }
        const transform = new Transform(options.minZoom, options.maxZoom, options.minPitch, options.maxPitch, options.renderWorldCopies);
        super(transform, options);
        this._interactive = options.interactive;
        this._minTileCacheSize = options.minTileCacheSize;
        this._maxTileCacheSize = options.maxTileCacheSize;
        this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat;
        this._preserveDrawingBuffer = options.preserveDrawingBuffer;
        this._antialias = options.antialias;
        this._trackResize = options.trackResize;
        this._bearingSnap = options.bearingSnap;
        this._refreshExpiredTiles = options.refreshExpiredTiles;
        this._fadeDuration = options.fadeDuration;
        this._isInitialLoad = true;
        this._crossSourceCollisions = options.crossSourceCollisions;
        this._collectResourceTiming = options.collectResourceTiming;
        this._language = this._parseLanguage(options.language);
        this._worldview = options.worldview;
        this._renderTaskQueue = new TaskQueue();
        this._domRenderTaskQueue = new TaskQueue();
        this._controls = [];
        this._markers = [];
        this._popups = [];
        this._mapId = uniqueId();
        this._locale = extend$1({}, defaultLocale, options.locale);
        this._clickTolerance = options.clickTolerance;
        this._cooperativeGestures = options.cooperativeGestures;
        this._performanceMetricsCollection = options.performanceMetricsCollection;
        this._containerWidth = 0;
        this._containerHeight = 0;
        this._averageElevationLastSampledAt = -Infinity;
        this._averageElevationExaggeration = 0;
        this._averageElevation = new EasedVariable(0);
        this._interactionRange = [
            +Infinity,
            -Infinity
        ];
        this._visibilityHidden = 0;
        this._useExplicitProjection = false;
        // Fallback to stylesheet by default
        this._requestManager = new RequestManager(options.transformRequest, options.accessToken, options.testMode);
        this._silenceAuthErrors = !!options.testMode;
        if (typeof options.container === 'string') {
            this._container = window$1.document.getElementById(options.container);
            if (!this._container) {
                throw new Error(`Container '${ options.container.toString() }' not found.`);
            }
        } else if (options.container instanceof window$1.HTMLElement) {
            this._container = options.container;
        } else {
            throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);
        }
        if (this._container.childNodes.length > 0) {
            warnOnce(`The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead.`);
        }
        if (options.maxBounds) {
            this.setMaxBounds(options.maxBounds);
        }
        bindAll([
            '_onWindowOnline',
            '_onWindowResize',
            '_onVisibilityChange',
            '_onMapScroll',
            '_contextLost',
            '_contextRestored'
        ], this);
        this._setupContainer();
        this._setupPainter();
        if (this.painter === undefined) {
            throw new Error(`Failed to initialize WebGL.`);
        }
        this.on('move', () => this._update(false));
        this.on('moveend', () => this._update(false));
        this.on('zoom', () => this._update(true));
        if (typeof window$1 !== 'undefined') {
            this._fullscreenchangeEvent = 'onfullscreenchange' in window$1.document ? 'fullscreenchange' : 'webkitfullscreenchange';
            // $FlowFixMe[method-unbinding]
            window$1.addEventListener('online', this._onWindowOnline, false);
            // $FlowFixMe[method-unbinding]
            window$1.addEventListener('resize', this._onWindowResize, false);
            // $FlowFixMe[method-unbinding]
            window$1.addEventListener('orientationchange', this._onWindowResize, false);
            // $FlowFixMe[method-unbinding]
            window$1.addEventListener(this._fullscreenchangeEvent, this._onWindowResize, false);
            // $FlowFixMe[method-unbinding]
            window$1.addEventListener('visibilitychange', this._onVisibilityChange, false);
        }
        this.handlers = new HandlerManager(this, options);
        this._localFontFamily = options.localFontFamily;
        this._localIdeographFontFamily = options.localIdeographFontFamily;
        if (options.style || !options.testMode) {
            const style = options.style || config.DEFAULT_STYLE;
            this.setStyle(style, {
                localFontFamily: this._localFontFamily,
                localIdeographFontFamily: this._localIdeographFontFamily
            });
        }
        if (options.projection) {
            this.setProjection(options.projection);
        }
        const hashName = typeof options.hash === 'string' && options.hash || undefined;
        if (options.hash)
            this._hash = new Hash(hashName).addTo(this);
        // don't set position from options if set through hash
        if (!this._hash || !this._hash._onHashChange()) {
            this.jumpTo({
                center: options.center,
                zoom: options.zoom,
                bearing: options.bearing,
                pitch: options.pitch
            });
            const bounds = options.bounds;
            if (bounds) {
                this.resize();
                this.fitBounds(bounds, extend$1({}, options.fitBoundsOptions, { duration: 0 }));
            }
        }
        this.resize();
        if (options.attributionControl)
            // $FlowFixMe[method-unbinding]
            this.addControl(new AttributionControl({ customAttribution: options.customAttribution }));
        // $FlowFixMe[method-unbinding]
        this._logoControl = new LogoControl();
        // $FlowFixMe[method-unbinding]
        this.addControl(this._logoControl, options.logoPosition);
        this.on('style.load', () => {
            if (this.transform.unmodified) {
                this.jumpTo(this.style.stylesheet);
            }
        });
        this.on('data', event => {
            this._update(event.dataType === 'style');
            this.fire(new Event(`${ event.dataType }data`, event));
        });
        this.on('dataloading', event => {
            this.fire(new Event(`${ event.dataType }dataloading`, event));
        });
    }
    /*
    * Returns a unique number for this map instance which is used for the MapLoadEvent
    * to make sure we only fire one event per instantiated map object.
    * @private
    * @returns {number}
    */
    _getMapId() {
        return this._mapId;
    }
    /** @section {Controls} */
    /**
     * Adds an {@link IControl} to the map, calling `control.onAdd(this)`.
     *
     * @param {IControl} control The {@link IControl} to add.
     * @param {string} [position] Position on the map to which the control will be added.
     *     Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Add zoom and rotation controls to the map.
     * map.addControl(new mapboxgl.NavigationControl());
     * @see [Example: Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)
     */
    addControl(control, position) {
        if (position === undefined) {
            if (control.getDefaultPosition) {
                position = control.getDefaultPosition();
            } else {
                position = 'top-right';
            }
        }
        if (!control || !control.onAdd) {
            return this.fire(new ErrorEvent(new Error('Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.')));
        }
        const controlElement = control.onAdd(this);
        this._controls.push(control);
        const positionContainer = this._controlPositions[position];
        if (position.indexOf('bottom') !== -1) {
            positionContainer.insertBefore(controlElement, positionContainer.firstChild);
        } else {
            positionContainer.appendChild(controlElement);
        }
        return this;
    }
    /**
     * Removes the control from the map.
     *
     * @param {IControl} control The {@link IControl} to remove.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Define a new navigation control.
     * const navigation = new mapboxgl.NavigationControl();
     * // Add zoom and rotation controls to the map.
     * map.addControl(navigation);
     * // Remove zoom and rotation controls from the map.
     * map.removeControl(navigation);
     */
    removeControl(control) {
        if (!control || !control.onRemove) {
            return this.fire(new ErrorEvent(new Error('Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.')));
        }
        const ci = this._controls.indexOf(control);
        if (ci > -1)
            this._controls.splice(ci, 1);
        control.onRemove(this);
        return this;
    }
    /**
     * Checks if a control is on the map.
     *
     * @param {IControl} control The {@link IControl} to check.
     * @returns {boolean} True if map contains control.
     * @example
     * // Define a new navigation control.
     * const navigation = new mapboxgl.NavigationControl();
     * // Add zoom and rotation controls to the map.
     * map.addControl(navigation);
     * // Check that the navigation control exists on the map.
     * const added = map.hasControl(navigation);
     * // added === true
     */
    hasControl(control) {
        return this._controls.indexOf(control) > -1;
    }
    /**
     * Returns the map's containing HTML element.
     *
     * @returns {HTMLElement} The map's container.
     * @example
     * const container = map.getContainer();
     */
    getContainer() {
        return this._container;
    }
    /**
     * Returns the HTML element containing the map's `<canvas>` element.
     *
     * If you want to add non-GL overlays to the map, you should append them to this element.
     *
     * This is the element to which event bindings for map interactivity (such as panning and zooming) are
     * attached. It will receive bubbled events from child elements such as the `<canvas>`, but not from
     * map controls.
     *
     * @returns {HTMLElement} The container of the map's `<canvas>`.
     * @example
     * const canvasContainer = map.getCanvasContainer();
     * @see [Example: Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)
     * @see [Example: Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
     */
    getCanvasContainer() {
        return this._canvasContainer;
    }
    /**
     * Returns the map's `<canvas>` element.
     *
     * @returns {HTMLCanvasElement} The map's `<canvas>` element.
     * @example
     * const canvas = map.getCanvas();
     * @see [Example: Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)
     * @see [Example: Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
     * @see [Example: Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)
     */
    getCanvas() {
        return this._canvas;
    }
    /** @section {Map constraints} */
    /**
     * Resizes the map according to the dimensions of its
     * `container` element.
     *
     * Checks if the map container size changed and updates the map if it has changed.
     * This method must be called after the map's `container` is resized programmatically
     * or when the map is shown after being initially hidden with CSS.
     *
     * @param {Object | null} eventData Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend`
     *     events that get triggered as a result of resize. This can be useful for differentiating the
     *     source of an event (for example, user-initiated or programmatically-triggered events).
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Resize the map when the map container is shown
     * // after being initially hidden with CSS.
     * const mapDiv = document.getElementById('map');
     * if (mapDiv.style.visibility === true) map.resize();
     */
    resize(eventData) {
        this._updateContainerDimensions();
        // do nothing if container remained the same size
        if (this._containerWidth === this.transform.width && this._containerHeight === this.transform.height)
            return this;
        this._resizeCanvas(this._containerWidth, this._containerHeight);
        this.transform.resize(this._containerWidth, this._containerHeight);
        this.painter.resize(Math.ceil(this._containerWidth), Math.ceil(this._containerHeight));
        const fireMoving = !this._moving;
        if (fireMoving) {
            this.fire(new Event('movestart', eventData)).fire(new Event('move', eventData));
        }
        this.fire(new Event('resize', eventData));
        if (fireMoving)
            this.fire(new Event('moveend', eventData));
        return this;
    }
    /**
     * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not
     * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
     * If a padding is set on the map, the bounds returned are for the inset.
     * With globe projection, the smallest bounds encompassing the visible region
     * may not precisely represent the visible region due to the earth's curvature.
     *
     * @returns {LngLatBounds} The geographical bounds of the map as {@link LngLatBounds}.
     * @example
     * const bounds = map.getBounds();
     */
    getBounds() {
        return this.transform.getBounds();
    }
    /**
     * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
     *
     * @returns {Map} The map object.
     *
     * @example
     * const maxBounds = map.getMaxBounds();
     */
    getMaxBounds() {
        return this.transform.getMaxBounds() || null;
    }
    /**
     * Sets or clears the map's geographical bounds.
     *
     * Pan and zoom operations are constrained within these bounds.
     * If a pan or zoom is performed that would
     * display regions outside these bounds, the map will
     * instead display a position and zoom level
     * as close as possible to the operation's request while still
     * remaining within the bounds.
     *
     * For `mercator` projection, the viewport will be constrained to the bounds.
     * For other projections such as `globe`, only the map center will be constrained.
     *
     * @param {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Define bounds that conform to the `LngLatBoundsLike` object.
     * const bounds = [
     *     [-74.04728, 40.68392], // [west, south]
     *     [-73.91058, 40.87764]  // [east, north]
     * ];
     * // Set the map's max bounds.
     * map.setMaxBounds(bounds);
     */
    setMaxBounds(bounds) {
        this.transform.setMaxBounds(LngLatBounds.convert(bounds));
        return this._update();
    }
    /**
     * Sets or clears the map's minimum zoom level.
     * If the map's current zoom level is lower than the new minimum,
     * the map will zoom to the new minimum.
     *
     * It is not always possible to zoom out and reach the set `minZoom`.
     * Other factors such as map height may restrict zooming. For example,
     * if the map is 512px tall it will not be possible to zoom below zoom 0
     * no matter what the `minZoom` is set to.
     *
     * @param {number | null | undefined} minZoom The minimum zoom level to set (-2 - 24).
     *     If `null` or `undefined` is provided, the function removes the current minimum zoom and it will be reset to -2.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setMinZoom(12.25);
     */
    setMinZoom(minZoom) {
        minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom;
        if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) {
            this.transform.minZoom = minZoom;
            this._update();
            if (this.getZoom() < minZoom) {
                this.setZoom(minZoom);
            } else {
                this.fire(new Event('zoomstart')).fire(new Event('zoom')).fire(new Event('zoomend'));
            }
            return this;
        } else
            throw new Error(`minZoom must be between ${ defaultMinZoom } and the current maxZoom, inclusive`);
    }
    /**
     * Returns the map's minimum allowable zoom level.
     *
     * @returns {number} Returns `minZoom`.
     * @example
     * const minZoom = map.getMinZoom();
     */
    getMinZoom() {
        return this.transform.minZoom;
    }
    /**
     * Sets or clears the map's maximum zoom level.
     * If the map's current zoom level is higher than the new maximum,
     * the map will zoom to the new maximum.
     *
     * @param {number | null | undefined} maxZoom The maximum zoom level to set.
     *     If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setMaxZoom(18.75);
     */
    setMaxZoom(maxZoom) {
        maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom;
        if (maxZoom >= this.transform.minZoom) {
            this.transform.maxZoom = maxZoom;
            this._update();
            if (this.getZoom() > maxZoom) {
                this.setZoom(maxZoom);
            } else {
                this.fire(new Event('zoomstart')).fire(new Event('zoom')).fire(new Event('zoomend'));
            }
            return this;
        } else
            throw new Error(`maxZoom must be greater than the current minZoom`);
    }
    /**
     * Returns the map's maximum allowable zoom level.
     *
     * @returns {number} Returns `maxZoom`.
     * @example
     * const maxZoom = map.getMaxZoom();
     */
    getMaxZoom() {
        return this.transform.maxZoom;
    }
    /**
     * Sets or clears the map's minimum pitch.
     * If the map's current pitch is lower than the new minimum,
     * the map will pitch to the new minimum.
     *
     * @param {number | null | undefined} minPitch The minimum pitch to set (0-85). If `null` or `undefined` is provided, the function removes the current minimum pitch and resets it to 0.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setMinPitch(5);
     */
    setMinPitch(minPitch) {
        minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch;
        if (minPitch < defaultMinPitch) {
            throw new Error(`minPitch must be greater than or equal to ${ defaultMinPitch }`);
        }
        if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) {
            this.transform.minPitch = minPitch;
            this._update();
            if (this.getPitch() < minPitch) {
                this.setPitch(minPitch);
            } else {
                this.fire(new Event('pitchstart')).fire(new Event('pitch')).fire(new Event('pitchend'));
            }
            return this;
        } else
            throw new Error(`minPitch must be between ${ defaultMinPitch } and the current maxPitch, inclusive`);
    }
    /**
     * Returns the map's minimum allowable pitch.
     *
     * @returns {number} Returns `minPitch`.
     * @example
     * const minPitch = map.getMinPitch();
     */
    getMinPitch() {
        return this.transform.minPitch;
    }
    /**
     * Sets or clears the map's maximum pitch.
     * If the map's current pitch is higher than the new maximum,
     * the map will pitch to the new maximum.
     *
     * @param {number | null | undefined} maxPitch The maximum pitch to set.
     *     If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 85).
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setMaxPitch(70);
     */
    setMaxPitch(maxPitch) {
        maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch;
        if (maxPitch > defaultMaxPitch) {
            throw new Error(`maxPitch must be less than or equal to ${ defaultMaxPitch }`);
        }
        if (maxPitch >= this.transform.minPitch) {
            this.transform.maxPitch = maxPitch;
            this._update();
            if (this.getPitch() > maxPitch) {
                this.setPitch(maxPitch);
            } else {
                this.fire(new Event('pitchstart')).fire(new Event('pitch')).fire(new Event('pitchend'));
            }
            return this;
        } else
            throw new Error(`maxPitch must be greater than or equal to minPitch`);
    }
    /**
     * Returns the map's maximum allowable pitch.
     *
     * @returns {number} Returns `maxPitch`.
     * @example
     * const maxPitch = map.getMaxPitch();
     */
    getMaxPitch() {
        return this.transform.maxPitch;
    }
    /**
     * Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
     * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
     * container, there will be blank space beyond 180 and -180 degrees longitude.
     * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
     * map and the other on the left edge of the map) at every zoom level.
     *
     * @returns {boolean} Returns `renderWorldCopies` boolean.
     * @example
     * const worldCopiesRendered = map.getRenderWorldCopies();
     * @see [Example: Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)
     */
    getRenderWorldCopies() {
        return this.transform.renderWorldCopies;
    }
    /**
     * Sets the state of `renderWorldCopies`.
     *
     * @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
     *     - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
     *     container, there will be blank space beyond 180 and -180 degrees longitude.
     *     - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
     *     map and the other on the left edge of the map) at every zoom level.
     *
     *     `undefined` is treated as `true`, `null` is treated as `false`.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setRenderWorldCopies(true);
     * @see [Example: Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)
     */
    setRenderWorldCopies(renderWorldCopies) {
        this.transform.renderWorldCopies = renderWorldCopies;
        if (!this.transform.renderWorldCopies) {
            this._forceMarkerAndPopupUpdate(true);
        }
        return this._update();
    }
    /**
     * Returns the map's language, which is used for translating map labels and UI components.
     *
     * @private
     * @returns {undefined | string | string[]} Returns the map's language code.
     * @example
     * const language = map.getLanguage();
     */
    getLanguage() {
        return this._language;
    }
    _parseLanguage(language) {
        if (language === 'auto')
            return window$1.navigator.language;
        if (Array.isArray(language))
            return language.length === 0 ? undefined : language.map(l => l === 'auto' ? window$1.navigator.language : l);
        return language;
    }
    /**
     * Sets the map's language, which is used for translating map labels and UI components.
     *
     * @private
     * @param {'auto' | string | string[]} [language] A string representing the desired language used for the map's labels and UI components. Languages can only be set on Mapbox vector tile sources.
     *  Valid language strings must be a [BCP-47 language code](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_subtags). Unsupported BCP-47 codes will not include any translations. Invalid codes will result in an recoverable error.
     *  If a label has no translation for the selected language, it will display in the label's local language.
     *  If param is set to `auto`, GL JS will select a user's preferred language as determined by the browser's [`window.navigator.language`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) property.
     *  If the `locale` property is not set separately, this language will also be used to localize the UI for supported languages.
     *  If param is set to `undefined` or `null`, it will remove the current map language and reset the language used for translating map labels and UI components.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setLanguage('es');
     *
     * @example
     * map.setLanguage(['en-GB', 'en-US']);
     *
     * @example
     * map.setLanguage('auto');
     *
     * @example
     * map.setLanguage();
     */
    setLanguage(language) {
        const newLanguage = this._parseLanguage(language);
        if (!this.style || newLanguage === this._language)
            return this;
        this._language = newLanguage;
        this.style.clearSources();
        for (const control of this._controls) {
            if (control._setLanguage) {
                control._setLanguage(this._language);
            }
        }
        return this;
    }
    /**
     * Returns the code for the map's worldview.
     *
     * @private
     * @returns {string} Returns the map's worldview code.
     * @example
     * const worldview = map.getWorldview();
     */
    getWorldview() {
        return this._worldview;
    }
    /**
     * Sets the map's worldview.
     *
     * @private
     * @param {string} [worldview] A string representing the desired worldview.
     *  A worldview determines the way that certain disputed boundaries are rendered.
     *  Valid worldview strings must be an [ISO alpha-2 country code](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes).
     *  Unsupported ISO alpha-2 codes will fall back to the TileJSON's default worldview. Invalid codes will result in a recoverable error.
     *  If param is set to `undefined` or `null`, it will cause the map to fall back to the TileJSON's default worldview.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setWorldView('JP');
     *
     * @example
     * map.setWorldView();
     */
    setWorldview(worldview) {
        if (!this.style || worldview === this._worldview)
            return this;
        this._worldview = worldview;
        this.style.clearSources();
        return this;
    }
    /** @section {Point conversion} */
    /**
     * Returns a [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) object that defines the current map projection.
     *
     * @returns {ProjectionSpecification} The [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) defining the current map projection.
     * @example
     * const projection = map.getProjection();
     */
    getProjection() {
        if (this.transform.mercatorFromTransition) {
            return {
                name: 'globe',
                center: [
                    0,
                    0
                ]
            };
        }
        return this.transform.getProjection();
    }
    /**
     * Returns true if map [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) has been set to globe AND the map is at a low enough zoom level that globe view is enabled.
     * @private
     * @returns {boolean} Returns `globe-is-active` boolean.
     * @example
     * if (map._showingGlobe()) {
     *     // do globe things here
     * }
     */
    _showingGlobe() {
        return this.transform.projection.name === 'globe';
    }
    /**
     * Sets the map's projection. If called with `null` or `undefined`, the map will reset to Mercator.
     *
     * @param {ProjectionSpecification | string | null | undefined} projection The projection that the map should be rendered in.
     *     This can be a [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) object or a string of the projection's name.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setProjection('albers');
     * map.setProjection({
     *     name: 'albers',
     *     center: [35, 55],
     *     parallels: [20, 60]
     * });
     * @see [Example: Display a web map using an alternate projection](https://docs.mapbox.com/mapbox-gl-js/example/map-projection/)
     * @see [Example: Use different map projections for web maps](https://docs.mapbox.com/mapbox-gl-js/example/projections/)
     */
    setProjection(projection) {
        this._lazyInitEmptyStyle();
        if (!projection) {
            projection = null;
        } else if (typeof projection === 'string') {
            projection = { name: projection };
        }
        this._useExplicitProjection = !!projection;
        return this._prioritizeAndUpdateProjection(projection, this.style.projection);
    }
    _updateProjectionTransition() {
        // The projection isn't globe, we can skip updating the transition
        if (this.getProjection().name !== 'globe') {
            return;
        }
        const tr = this.transform;
        const projection = tr.projection.name;
        let projectionHasChanged;
        if (projection === 'globe' && tr.zoom >= GLOBE_ZOOM_THRESHOLD_MAX) {
            tr.setMercatorFromTransition();
            projectionHasChanged = true;
        } else if (projection === 'mercator' && tr.zoom < GLOBE_ZOOM_THRESHOLD_MAX) {
            tr.setProjection({ name: 'globe' });
            projectionHasChanged = true;
        }
        if (projectionHasChanged) {
            this.style.applyProjectionUpdate();
            this.style._forceSymbolLayerUpdate();
        }
    }
    _prioritizeAndUpdateProjection(explicitProjection, styleProjection) {
        // Given a stylesheet and eventual runtime projection, in order of priority, we select:
        //  1. the explicit projection
        //  2. the stylesheet projection
        //  3. mercator (fallback)
        const prioritizedProjection = explicitProjection || styleProjection || { name: 'mercator' };
        return this._updateProjection(prioritizedProjection);
    }
    _updateProjection(projection) {
        let projectionHasChanged;
        if (projection.name === 'globe' && this.transform.zoom >= GLOBE_ZOOM_THRESHOLD_MAX) {
            projectionHasChanged = this.transform.setMercatorFromTransition();
        } else {
            projectionHasChanged = this.transform.setProjection(projection);
        }
        this.style.applyProjectionUpdate();
        if (projectionHasChanged) {
            this.painter.clearBackgroundTiles();
            this.style.clearSources();
            this._update(true);
            this._forceMarkerAndPopupUpdate(true);
        }
        return this;
    }
    /**
     * Returns a {@link Point} representing pixel coordinates, relative to the map's `container`,
     * that correspond to the specified geographical location.
     *
     * When the map is pitched and `lnglat` is completely behind the camera, there are no pixel
     * coordinates corresponding to that location. In that case,
     * the `x` and `y` components of the returned {@link Point} are set to Number.MAX_VALUE.
     *
     * @param {LngLatLike} lnglat The geographical location to project.
     * @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`.
     * @example
     * const coordinate = [-122.420679, 37.772537];
     * const point = map.project(coordinate);
     */
    project(lnglat) {
        return this.transform.locationPoint3D(LngLat$1.convert(lnglat));
    }
    /**
     * Returns a {@link LngLat} representing geographical coordinates that correspond
     * to the specified pixel coordinates. If horizon is visible, and specified pixel is
     * above horizon, returns a {@link LngLat} corresponding to point on horizon, nearest
     * to the point.
     *
     * @param {PointLike} point The pixel coordinates to unproject.
     * @returns {LngLat} The {@link LngLat} corresponding to `point`.
     * @example
     * map.on('click', (e) => {
     *     // When the map is clicked, get the geographic coordinate.
     *     const coordinate = map.unproject(e.point);
     * });
     */
    unproject(point) {
        return this.transform.pointLocation3D(Point$2.convert(point));
    }
    /** @section {Movement state} */
    /**
     * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.
     *
     * @returns {boolean} True if the map is moving.
     * @example
     * const isMoving = map.isMoving();
     */
    isMoving() {
        return this._moving || this.handlers && this.handlers.isMoving() || false;
    }
    /**
     * Returns true if the map is zooming due to a camera animation or user gesture.
     *
     * @returns {boolean} True if the map is zooming.
     * @example
     * const isZooming = map.isZooming();
     */
    isZooming() {
        return this._zooming || this.handlers && this.handlers.isZooming() || false;
    }
    /**
     * Returns true if the map is rotating due to a camera animation or user gesture.
     *
     * @returns {boolean} True if the map is rotating.
     * @example
     * map.isRotating();
     */
    isRotating() {
        return this._rotating || this.handlers && this.handlers.isRotating() || false;
    }
    _isDragging() {
        return this.handlers && this.handlers._isDragging() || false;
    }
    _createDelegatedListener(type, layers, listener) {
        if (type === 'mouseenter' || type === 'mouseover') {
            let mousein = false;
            const mousemove = e => {
                const filteredLayers = layers.filter(layerId => this.getLayer(layerId));
                const features = filteredLayers.length ? this.queryRenderedFeatures(e.point, { layers: filteredLayers }) : [];
                if (!features.length) {
                    mousein = false;
                } else if (!mousein) {
                    mousein = true;
                    listener.call(this, new MapMouseEvent(type, this, e.originalEvent, { features }));
                }
            };
            const mouseout = () => {
                mousein = false;
            };
            return {
                layers: new Set(layers),
                listener,
                delegates: {
                    mousemove,
                    mouseout
                }
            };
        } else if (type === 'mouseleave' || type === 'mouseout') {
            let mousein = false;
            const mousemove = e => {
                const filteredLayers = layers.filter(layerId => this.getLayer(layerId));
                const features = filteredLayers.length ? this.queryRenderedFeatures(e.point, { layers: filteredLayers }) : [];
                if (features.length) {
                    mousein = true;
                } else if (mousein) {
                    mousein = false;
                    listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
                }
            };
            const mouseout = e => {
                if (mousein) {
                    mousein = false;
                    listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
                }
            };
            return {
                layers: new Set(layers),
                listener,
                delegates: {
                    mousemove,
                    mouseout
                }
            };
        } else {
            const delegate = e => {
                const filteredLayers = layers.filter(layerId => this.getLayer(layerId));
                const features = filteredLayers.length ? this.queryRenderedFeatures(e.point, { layers: filteredLayers }) : [];
                if (features.length) {
                    // Here we need to mutate the original event, so that preventDefault works as expected.
                    e.features = features;
                    listener.call(this, e);
                    delete e.features;
                }
            };
            return {
                layers: new Set(layers),
                listener,
                delegates: { [type]: delegate }
            };
        }
    }
    /** @section {Working with events} */
    /**
     * Adds a listener for events of a specified type,
     * optionally limited to features in a specified style layer.
     *
     * @param {string} type The event type to listen for. Events compatible with the optional `layerId` parameter are triggered
     *     when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.
     *
     *     | Event                                                     | Compatible with `layerId` |
     *     |-----------------------------------------------------------|---------------------------|
     *     | [`mousedown`](#map.event:mousedown)                       | yes                       |
     *     | [`mouseup`](#map.event:mouseup)                           | yes                       |
     *     | [`mouseover`](#map.event:mouseover)                       | yes                       |
     *     | [`mouseout`](#map.event:mouseout)                         | yes                       |
     *     | [`mousemove`](#map.event:mousemove)                       | yes                       |
     *     | [`mouseenter`](#map.event:mouseenter)                     | yes (required)            |
     *     | [`mouseleave`](#map.event:mouseleave)                     | yes (required)            |
     *     | [`preclick`](#map.event:preclick)                         |                           |
     *     | [`click`](#map.event:click)                               | yes                       |
     *     | [`dblclick`](#map.event:dblclick)                         | yes                       |
     *     | [`contextmenu`](#map.event:contextmenu)                   | yes                       |
     *     | [`touchstart`](#map.event:touchstart)                     | yes                       |
     *     | [`touchend`](#map.event:touchend)                         | yes                       |
     *     | [`touchcancel`](#map.event:touchcancel)                   | yes                       |
     *     | [`wheel`](#map.event:wheel)                               |                           |
     *     | [`resize`](#map.event:resize)                             |                           |
     *     | [`remove`](#map.event:remove)                             |                           |
     *     | [`touchmove`](#map.event:touchmove)                       |                           |
     *     | [`movestart`](#map.event:movestart)                       |                           |
     *     | [`move`](#map.event:move)                                 |                           |
     *     | [`moveend`](#map.event:moveend)                           |                           |
     *     | [`dragstart`](#map.event:dragstart)                       |                           |
     *     | [`drag`](#map.event:drag)                                 |                           |
     *     | [`dragend`](#map.event:dragend)                           |                           |
     *     | [`zoomstart`](#map.event:zoomstart)                       |                           |
     *     | [`zoom`](#map.event:zoom)                                 |                           |
     *     | [`zoomend`](#map.event:zoomend)                           |                           |
     *     | [`rotatestart`](#map.event:rotatestart)                   |                           |
     *     | [`rotate`](#map.event:rotate)                             |                           |
     *     | [`rotateend`](#map.event:rotateend)                       |                           |
     *     | [`pitchstart`](#map.event:pitchstart)                     |                           |
     *     | [`pitch`](#map.event:pitch)                               |                           |
     *     | [`pitchend`](#map.event:pitchend)                         |                           |
     *     | [`boxzoomstart`](#map.event:boxzoomstart)                 |                           |
     *     | [`boxzoomend`](#map.event:boxzoomend)                     |                           |
     *     | [`boxzoomcancel`](#map.event:boxzoomcancel)               |                           |
     *     | [`webglcontextlost`](#map.event:webglcontextlost)         |                           |
     *     | [`webglcontextrestored`](#map.event:webglcontextrestored) |                           |
     *     | [`load`](#map.event:load)                                 |                           |
     *     | [`render`](#map.event:render)                             |                           |
     *     | [`idle`](#map.event:idle)                                 |                           |
     *     | [`error`](#map.event:error)                               |                           |
     *     | [`data`](#map.event:data)                                 |                           |
     *     | [`styledata`](#map.event:styledata)                       |                           |
     *     | [`sourcedata`](#map.event:sourcedata)                     |                           |
     *     | [`dataloading`](#map.event:dataloading)                   |                           |
     *     | [`styledataloading`](#map.event:styledataloading)         |                           |
     *     | [`sourcedataloading`](#map.event:sourcedataloading)       |                           |
     *     | [`styleimagemissing`](#map.event:styleimagemissing)       |                           |
     *     | [`style.load`](#map.event:style.load)                     |                           |
     *
     * @param {string | Array<string>} layerIds (optional) The ID(s) of a style layer(s). If you provide a `layerId`,
     *     the listener will be triggered only if its location is within a visible feature in these layers,
     *     and the event will have a `features` property containing an array of the matching features.
     *     If you do not provide `layerIds`, the listener will be triggered by a corresponding event
     *     happening anywhere on the map, and the event will not have a `features` property.
     *     Note that many event types are not compatible with the optional `layerIds` parameter.
     * @param {Function} listener The function to be called when the event is fired.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Set an event listener that will fire
     * // when the map has finished loading.
     * map.on('load', () => {
     *     // Add a new layer.
     *     map.addLayer({
     *         id: 'points-of-interest',
     *         source: {
     *             type: 'vector',
     *             url: 'mapbox://mapbox.mapbox-streets-v8'
     *         },
     *         'source-layer': 'poi_label',
     *         type: 'circle',
     *         paint: {
     *             // Mapbox Style Specification paint properties
     *         },
     *         layout: {
     *             // Mapbox Style Specification layout properties
     *         }
     *     });
     * });
     * @example
     * // Set an event listener that will fire
     * // when a feature on the countries layer of the map is clicked.
     * map.on('click', 'countries', (e) => {
     *     new mapboxgl.Popup()
     *         .setLngLat(e.lngLat)
     *         .setHTML(`Country name: ${e.features[0].properties.name}`)
     *         .addTo(map);
     * });
     * @example
     * // Set an event listener that will fire
     * // when a feature on the countries or background layers of the map is clicked.
     * map.on('click', ['countries', 'background'], (e) => {
     *     new mapboxgl.Popup()
     *         .setLngLat(e.lngLat)
     *         .setHTML(`Country name: ${e.features[0].properties.name}`)
     *         .addTo(map);
     * });
     * @see [Example: Add 3D terrain to a map](https://docs.mapbox.com/mapbox-gl-js/example/add-terrain/)
     * @see [Example: Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/)
     * @see [Example: Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
     * @see [Example: Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)
     * @see [Example: Display popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)
     */
    on(type, layerIds, listener) {
        if (listener === undefined) {
            return super.on(type, layerIds);
        }
        if (!Array.isArray(layerIds)) {
            layerIds = [layerIds];
        }
        if (layerIds) {
            for (const layerId of layerIds) {
                if (!this._isValidId(layerId)) {
                    return this;
                }
            }
        }
        const delegatedListener = this._createDelegatedListener(type, layerIds, listener);
        this._delegatedListeners = this._delegatedListeners || {};
        this._delegatedListeners[type] = this._delegatedListeners[type] || [];
        this._delegatedListeners[type].push(delegatedListener);
        for (const event in delegatedListener.delegates) {
            this.on(event, delegatedListener.delegates[event]);
        }
        return this;
    }
    /**
     * Adds a listener that will be called only once to a specified event type,
     * optionally limited to events occurring on features in a specified style layer.
     *
     * @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'preclick'`, `'click'`, `'dblclick'`,
     *     `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,
     *     `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters
     *     a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`
     *     and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves
     *     the map canvas.
     * @param {string | Array<string>} layerIds (optional) The ID(s) of a style layer(s). If you provide `layerIds`,
     *     the listener will be triggered only if its location is within a visible feature in these layers,
     *     and the event will have a `features` property containing an array of the matching features.
     *     If you do not provide `layerIds`, the listener will be triggered by a corresponding event
     *     happening anywhere on the map, and the event will not have a `features` property.
     *     Note that many event types are not compatible with the optional `layerIds` parameter.
     * @param {Function} listener The function to be called when the event is fired.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Log the coordinates of a user's first map touch.
     * map.once('touchstart', (e) => {
     *     console.log(`The first map touch was at: ${e.lnglat}`);
     * });
     * @example
     * // Log the coordinates of a user's first map touch
     * // on a specific layer.
     * map.once('touchstart', 'my-point-layer', (e) => {
     *     console.log(`The first map touch on the point layer was at: ${e.lnglat}`);
     * });
     * @example
     * // Log the coordinates of a user's first map touch
     * // on specific layers.
     * map.once('touchstart', ['my-point-layer', 'my-point-layer-2'], (e) => {
     *     console.log(`The first map touch on the point layer was at: ${e.lnglat}`);
     * });
     * @see [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
     * @see [Example: Animate the camera around a point with 3D terrain](https://docs.mapbox.com/mapbox-gl-js/example/free-camera-point/)
     * @see [Example: Play map locations as a slideshow](https://docs.mapbox.com/mapbox-gl-js/example/playback-locations/)
     */
    once(type, layerIds, listener) {
        if (listener === undefined) {
            return super.once(type, layerIds);
        }
        if (!Array.isArray(layerIds)) {
            layerIds = [layerIds];
        }
        if (layerIds) {
            for (const layerId of layerIds) {
                if (!this._isValidId(layerId)) {
                    return this;
                }
            }
        }
        const delegatedListener = this._createDelegatedListener(type, layerIds, listener);
        for (const event in delegatedListener.delegates) {
            this.once(event, delegatedListener.delegates[event]);
        }
        return this;
    }
    /**
     * Removes an event listener previously added with {@link Map#on},
     * optionally limited to layer-specific events.
     *
     * @param {string} type The event type previously used to install the listener.
     * @param {string | Array<string>} layerIds (optional) The layer ID(s) previously used to install the listener.
     * @param {Function} listener The function previously installed as a listener.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * // Create a function to print coordinates while a mouse is moving.
     * function onMove(e) {
     *     console.log(`The mouse is moving: ${e.lngLat}`);
     * }
     * // Create a function to unbind the `mousemove` event.
     * function onUp(e) {
     *     console.log(`The final coordinates are: ${e.lngLat}`);
     *     map.off('mousemove', onMove);
     * }
     * // When a click occurs, bind both functions to mouse events.
     * map.on('mousedown', (e) => {
     *     map.on('mousemove', onMove);
     *     map.once('mouseup', onUp);
     * });
     * @see [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
     */
    off(type, layerIds, listener) {
        if (listener === undefined) {
            return super.off(type, layerIds);
        }
        layerIds = new Set(Array.isArray(layerIds) ? layerIds : [layerIds]);
        for (const layerId of layerIds) {
            if (!this._isValidId(layerId)) {
                return this;
            }
        }
        const areLayerArraysEqual = (hash1, hash2) => {
            if (hash1.size !== hash2.size) {
                return false;    // at-least 1 arr has duplicate value(s)
            }
            // comparing values
            for (const value of hash1) {
                if (!hash2.has(value))
                    return false;
            }
            return true;
        };
        const removeDelegatedListeners = listeners => {
            for (let i = 0; i < listeners.length; i++) {
                const delegatedListener = listeners[i];
                if (delegatedListener.listener === listener && areLayerArraysEqual(delegatedListener.layers, layerIds)) {
                    for (const event in delegatedListener.delegates) {
                        this.off(event, delegatedListener.delegates[event]);
                    }
                    listeners.splice(i, 1);
                    return this;
                }
            }
        };
        const delegatedListeners = this._delegatedListeners ? this._delegatedListeners[type] : undefined;
        if (delegatedListeners) {
            removeDelegatedListeners(delegatedListeners);
        }
        return this;
    }
    /** @section {Querying features} */
    /**
     * Returns an array of [GeoJSON](http://geojson.org/)
     * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)
     * representing visible features that satisfy the query parameters.
     *
     * @param {PointLike|Array<PointLike>} [geometry] - The geometry of the query region in pixels:
     *     either a single point or bottom left and top right points describing a bounding box, where the origin is at the top left.
     *     Omitting this parameter (by calling {@link Map#queryRenderedFeatures} with zero arguments,
     *     or with only an `options` argument) is equivalent to passing a bounding box encompassing the entire
     *     map viewport.
     *     Only values within the existing viewport are supported.
     * @param {Object} [options] Options object.
     * @param {Array<string>} [options.layers] An array of [style layer IDs](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) for the query to inspect.
     *     Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.
     * @param {Array} [options.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter)
     *     to limit query results.
     * @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.
     *
     * @returns {Array<Object>} An array of [GeoJSON](http://geojson.org/)
     *     [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
     *
     *     The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only
     *     string and numeric property values are supported. `null`, `Array`, and `Object` values are not supported.
     *
     *     Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object
     *     representing the style layer to  which the feature belongs. Layout and paint properties in this object contain values
     *     which are fully evaluated for the given zoom level and feature.
     *
     *     Only features that are currently rendered are included. Some features will **not** be included, like:
     *
     *     - Features from layers whose `visibility` property is `"none"`.
     *     - Features from layers whose zoom range excludes the current zoom level.
     *     - Symbol features that have been hidden due to text or icon collision.
     *
     *     Features from all other layers are included, including features that may have no visible
     *     contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0.
     *
     *     The topmost rendered feature appears first in the returned array, and subsequent features are sorted by
     *     descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low
     *     zoom levels) are returned only once (though subject to the following caveat).
     *
     *     Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
     *     geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
     *     times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
     *     The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
     *     rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
     *     will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
     *     tiles due to tile buffering.
     *
     * @example
     * // Find all features at a point
     * const features = map.queryRenderedFeatures(
     *   [20, 35],
     *   {layers: ['my-layer-name']}
     * );
     *
     * @example
     * // Find all features within a static bounding box
     * const features = map.queryRenderedFeatures(
     *   [[10, 20], [30, 50]],
     *   {layers: ['my-layer-name']}
     * );
     *
     * @example
     * // Find all features within a bounding box around a point
     * const width = 10;
     * const height = 20;
     * const features = map.queryRenderedFeatures([
     *     [point.x - width / 2, point.y - height / 2],
     *     [point.x + width / 2, point.y + height / 2]
     * ], {layers: ['my-layer-name']});
     *
     * @example
     * // Query all rendered features from a single layer
     * const features = map.queryRenderedFeatures({layers: ['my-layer-name']});
     * @see [Example: Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/)
     * @see [Example: Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
     * @see [Example: Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
     */
    queryRenderedFeatures(geometry, options) {
        // The first parameter can be omitted entirely, making this effectively an overloaded method
        // with two signatures:
        //
        //     queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object)
        //     queryRenderedFeatures(options?: Object)
        //
        // There no way to express that in a way that's compatible with both flow and documentation.js.
        // Related: https://github.com/facebook/flow/issues/1556
        if (!this.style) {
            return [];
        }
        if (options === undefined && geometry !== undefined && !(geometry instanceof Point$2) && !Array.isArray(geometry)) {
            options = geometry;
            geometry = undefined;
        }
        options = options || {};
        geometry = geometry || [
            [
                0,
                0
            ],
            [
                this.transform.width,
                this.transform.height
            ]
        ];
        if (options.layers && Array.isArray(options.layers)) {
            for (const layerId of options.layers) {
                if (!this._isValidId(layerId)) {
                    return [];
                }
            }
        }
        return this.style.queryRenderedFeatures(geometry, options, this.transform);
    }
    /**
     * Returns an array of [GeoJSON](http://geojson.org/)
     * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)
     * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
     *
     * @param {string} sourceId The ID of the vector tile or GeoJSON source to query.
     * @param {Object} [parameters] Options object.
     * @param {string} [parameters.sourceLayer] The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/)
     *     to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored.
     * @param {Array} [parameters.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter)
     *     to limit query results.
     * @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.
     *
     * @returns {Array<Object>} An array of [GeoJSON](http://geojson.org/)
     *     [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
     *
     *     In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters,
     *     whether or not they are rendered by the current style (in other words, are visible). The domain of the query includes all currently-loaded
     *     vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently
     *     visible viewport.
     *
     *     Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
     *     geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
     *     times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
     *     The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
     *     rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
     *     will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
     *     tiles due to tile buffering.
     *
     * @example
     * // Find all features in one source layer in a vector source
     * const features = map.querySourceFeatures('your-source-id', {
     *     sourceLayer: 'your-source-layer'
     * });
     *
     * @see [Example: Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)
     */
    querySourceFeatures(sourceId, parameters) {
        if (!this._isValidId(sourceId)) {
            return [];
        }
        return this.style.querySourceFeatures(sourceId, parameters);
    }
    /**
     * Determines if the given point is located on a visible map surface.
     *
     * @param {PointLike} point - The point to be checked, specified as an array of two numbers representing the x and y coordinates, or as a {@link https://docs.mapbox.com/mapbox-gl-js/api/geography/#point|Point} object.
     * @returns {boolean} Returns `true` if the point is on the visible map surface, otherwise returns `false`.
     * @example
     * const pointOnSurface = map.isPointOnSurface([100, 200]);
     */
    isPointOnSurface(point) {
        const {name} = this.transform.projection;
        if (name !== 'globe' && name !== 'mercator') {
            warnOnce(`${ name } projection does not support isPointOnSurface, this API may behave unexpectedly.`);
        }
        return this.transform.isPointOnSurface(Point$2.convert(point));
    }
    /** @section {Working with styles} */
    /**
     * Updates the map's Mapbox style object with a new value.
     *
     * If a style is already set when this is used and the `diff` option is set to `true`, the map renderer will attempt to compare the given style
     * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites
     * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current
     * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building
     * the given one from scratch.
     *
     * @param {Object | string| null} style A JSON object conforming to the schema described in the
     *     [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON.
     * @param {Object} [options] Options object.
     * @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style
     *     and building the given one instead of attempting a diff-based update.
     * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS
     *     font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.
     *     In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).
     *     Set to `false`, to enable font settings from the map's style for these glyph ranges.
     *     Forces a full update.
     * @returns {Map} Returns itself to allow for method chaining.
     *
     * @example
     * map.setStyle("mapbox://styles/mapbox/streets-v11");
     *
     * @see [Example: Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/)
     */
    setStyle(style, options) {
        options = extend$1({}, {
            localIdeographFontFamily: this._localIdeographFontFamily,
            localFontFamily: this._localFontFamily
        }, options);
        if (options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily && options.localFontFamily === this._localFontFamily && this.style && style) {
            this._diffStyle(style, options);
            return this;
        } else {
            this._localIdeographFontFamily = options.localIdeographFontFamily;
            this._localFontFamily = options.localFontFamily;
            return this._updateStyle(style, options);
        }
    }
    _getUIString(key) {
        const str = this._locale[key];
        if (str == null) {
            throw new Error(`Missing UI string '${ key }'`);
        }
        return str;
    }
    _updateStyle(style, options) {
        if (this.style) {
            this.style.setEventedParent(null);
            this.style._remove();
            this.style = undefined;    // we lazy-init it so it's never undefined when accessed
        }
        if (style) {
            this.style = new Style(this, options || {});
            this.style.setEventedParent(this, { style: this.style });
            if (typeof style === 'string') {
                this.style.loadURL(style);
            } else {
                this.style.loadJSON(style);
            }
        }
        this._updateTerrain();
        return this;
    }
    _lazyInitEmptyStyle() {
        if (!this.style) {
            this.style = new Style(this, {});
            this.style.setEventedParent(this, { style: this.style });
            this.style.loadEmpty();
        }
    }
    _diffStyle(style, options) {
        if (typeof style === 'string') {
            const url = this._requestManager.normalizeStyleURL(style);
            const request = this._requestManager.transformRequest(url, ResourceType.Style);
            getJSON(request, (error, json) => {
                if (error) {
                    this.fire(new ErrorEvent(error));
                } else if (json) {
                    this._updateDiff(json, options);
                }
            });
        } else if (typeof style === 'object') {
            this._updateDiff(style, options);
        }
    }
    _updateDiff(style, options) {
        try {
            if (this.style.setState(style)) {
                this._update(true);
            }
        } catch (e) {
            warnOnce(`Unable to perform style diff: ${ e.message || e.error || e }.  Rebuilding the style from scratch.`);
            this._updateStyle(style, options);
        }
    }
    /**
     * Returns the map's Mapbox [style](https://docs.mapbox.com/help/glossary/style/) object, a JSON object which can be used to recreate the map's style.
     *
     * @returns {Object} The map's style JSON object.
     *
     * @example
     * map.on('load', () => {
     *     const styleJson = map.getStyle();
     * });
     */
    getStyle() {
        if (this.style) {
            return this.style.serialize();
        }
    }
    /**
     * Returns a Boolean indicating whether the map's style is fully loaded.
     *
     * @returns {boolean} A Boolean indicating whether the style is fully loaded.
     *
     * @example
     * const styleLoadStatus = map.isStyleLoaded();
     */
    isStyleLoaded() {
        if (!this.style) {
            warnOnce('There is no style added to the map.');
            return false;
        }
        return this.style.loaded();
    }
    _isValidId(id) {
        // Disallow using fully qualified IDs in the public APIs
        if (isFQID(id)) {
            this.fire(new ErrorEvent(new Error(`IDs can't contain special symbols: "${ id }".`)));
            return false;
        }
        return true;
    }
    /** @section {Sources} */
    /**
     * Adds a source to the map's style.
     *
     * @param {string} id The ID of the source to add. Must not conflict with existing sources.
     * @param {Object} source The source object, conforming to the
     *     Mapbox Style Specification's [source definition](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or
     *     {@link CanvasSourceOptions}.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.addSource('my-data', {
     *     type: 'vector',
     *     url: 'mapbox://myusername.tilesetid'
     * });
     * @example
     * map.addSource('my-data', {
     *     "type": "geojson",
     *     "data": {
     *         "type": "Feature",
     *         "geometry": {
     *             "type": "Point",
     *             "coordinates": [-77.0323, 38.9131]
     *         },
     *         "properties": {
     *             "title": "Mapbox DC",
     *             "marker-symbol": "monument"
     *         }
     *     }
     * });
     * @see Example: Vector source: [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)
     * @see Example: GeoJSON source: [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)
     * @see Example: Raster DEM source: [Add hillshading](https://docs.mapbox.com/mapbox-gl-js/example/hillshade/)
     */
    addSource(id, source) {
        if (!this._isValidId(id)) {
            return this;
        }
        this._lazyInitEmptyStyle();
        this.style.addSource(id, source);
        return this._update(true);
    }
    /**
     * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with
     * the given ID in the map's style has no outstanding network requests, otherwise `false`.
     *
     * @param {string} id The ID of the source to be checked.
     * @returns {boolean} A Boolean indicating whether the source is loaded.
     * @example
     * const sourceLoaded = map.isSourceLoaded('bathymetry-data');
     */
    isSourceLoaded(id) {
        if (!this._isValidId(id)) {
            return false;
        }
        return !!this.style && this.style._isSourceCacheLoaded(id);
    }
    /**
     * Returns a Boolean indicating whether all tiles in the viewport from all sources on
     * the style are loaded.
     *
     * @returns {boolean} A Boolean indicating whether all tiles are loaded.
     * @example
     * const tilesLoaded = map.areTilesLoaded();
     */
    areTilesLoaded() {
        const sources = this.style && this.style._sourceCaches;
        for (const id in sources) {
            const source = sources[id];
            const tiles = source._tiles;
            for (const t in tiles) {
                const tile = tiles[t];
                if (!(tile.state === 'loaded' || tile.state === 'errored'))
                    return false;
            }
        }
        return true;
    }
    /**
     * Adds a [custom source type](#Custom Sources), making it available for use with
     * {@link Map#addSource}.
     * @private
     * @param {string} name The name of the source type; source definition objects use this name in the `{type: ...}` field.
     * @param {Function} SourceType A {@link Source} constructor.
     * @param {Function} callback Called when the source type is ready or with an error argument if there is an error.
     */
    addSourceType(name, SourceType, callback) {
        this._lazyInitEmptyStyle();
        this.style.addSourceType(name, SourceType, callback);
    }
    /**
     * Removes a source from the map's style.
     *
     * @param {string} id The ID of the source to remove.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.removeSource('bathymetry-data');
     */
    removeSource(id) {
        if (!this._isValidId(id)) {
            return this;
        }
        this.style.removeSource(id);
        this._updateTerrain();
        return this._update(true);
    }
    /**
     * Returns the source with the specified ID in the map's style.
     *
     * This method is often used to update a source using the instance members for the relevant
     * source type as defined in [Sources](#sources).
     * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates`
     * of an image source.
     *
     * @param {string} id The ID of the source to get.
     * @returns {?Object} The style source with the specified ID or `undefined` if the ID
     *     corresponds to no existing sources.
     *     The shape of the object varies by source type.
     *     A list of options for each source type is available on the Mapbox Style Specification's
     *     [Sources](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) page.
     * @example
     * const sourceObject = map.getSource('points');
     * @see [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
     * @see [Example: Animate a point](https://docs.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)
     * @see [Example: Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)
     */
    getSource(id) {
        if (!this._isValidId(id)) {
            return null;
        }
        return this.style.getOwnSource(id);
    }
    /** @section {Images} */
    // eslint-disable-next-line jsdoc/require-returns
    /**
     * Add an image to the style. This image can be displayed on the map like any other icon in the style's
     * [sprite](https://docs.mapbox.com/mapbox-gl-js/style-spec/sprite/) using the image's ID with
     * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image),
     * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern),
     * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern),
     * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).
     * A {@link Map.event:error} event will be fired if there is not enough space in the sprite to add this image.
     *
     * @param {string} id The ID of the image.
     * @param {HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface} image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`
     *     properties with the same format as `ImageData`.
     * @param {Object | null} options Options object.
     * @param {number} options.pixelRatio The ratio of pixels in the image to physical pixels on the screen.
     * @param {boolean} options.sdf Whether the image should be interpreted as an SDF image.
     * @param {[number, number, number, number]} options.content `[x1, y1, x2, y2]`  If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field`.
     * @param {Array<[number, number]>} options.stretchX `[[x1, x2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally.
     * @param {Array<[number, number]>} options.stretchY `[[y1, y2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically.
     *
     * @example
     * // If the style's sprite does not already contain an image with ID 'cat',
     * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.
     * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', (error, image) => {
     *     if (error) throw error;
     *     if (!map.hasImage('cat')) map.addImage('cat', image);
     * });
     *
     * // Add a stretchable image that can be used with `icon-text-fit`
     * // In this example, the image is 600px wide by 400px high.
     * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', (error, image) => {
     *     if (error) throw error;
     *     if (!map.hasImage('border-image')) {
     *         map.addImage('border-image', image, {
     *             content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border
     *             stretchX: [[16, 584]], // stretch everything horizontally except the 16px border
     *             stretchY: [[16, 384]], // stretch everything vertically except the 16px border
     *         });
     *     }
     * });
     *
     *
     * @see Example: Use `HTMLImageElement`: [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)
     * @see Example: Use `ImageData`: [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/)
     */
    addImage(id, image, {pixelRatio = 1, sdf = false, stretchX, stretchY, content} = {}) {
        this._lazyInitEmptyStyle();
        const version = 0;
        if (image instanceof window$1.HTMLImageElement || window$1.ImageBitmap && image instanceof window$1.ImageBitmap) {
            const {width, height, data} = exported$1.getImageData(image);
            this.style.addImage(id, {
                data: new RGBAImage({
                    width,
                    height
                }, data),
                pixelRatio,
                stretchX,
                stretchY,
                content,
                sdf,
                version
            });
        } else if (image.width === undefined || image.height === undefined) {
            this.fire(new ErrorEvent(new Error('Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));
        } else {
            const {width, height} = image;
            const userImage = image;
            const data = userImage.data;
            this.style.addImage(id, {
                data: new RGBAImage({
                    width,
                    height
                }, new Uint8Array(data)),
                pixelRatio,
                stretchX,
                stretchY,
                content,
                sdf,
                version,
                userImage
            });
            if (userImage.onAdd) {
                userImage.onAdd(this, id);
            }
        }
    }
    // eslint-disable-next-line jsdoc/require-returns
    /**
     * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's
     * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with
     * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image),
     * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern),
     * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern),
     * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).
     *
     * @param {string} id The ID of the image.
     * @param {HTMLImageElement | ImageBitmap | ImageData | StyleImageInterface} image The image as an `HTMLImageElement`, [`ImageData`](https://developer.mozilla.org/en-US/docs/Web/API/ImageData), [`ImageBitmap`](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap) or object with `width`, `height`, and `data`
     *     properties with the same format as `ImageData`.
     *
     * @example
    * // Load an image from an external URL.
     * map.loadImage('http://placekitten.com/50/50', (error, image) => {
     *     if (error) throw error;
     *     // If an image with the ID 'cat' already exists in the style's sprite,
     *     // replace that image with a new image, 'other-cat-icon.png'.
     *     if (map.hasImage('cat')) map.updateImage('cat', image);
     * });
     */
    updateImage(id, image) {
        this._lazyInitEmptyStyle();
        const existingImage = this.style.getImage(id);
        if (!existingImage) {
            this.fire(new ErrorEvent(new Error('The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.')));
            return;
        }
        const imageData = image instanceof window$1.HTMLImageElement || window$1.ImageBitmap && image instanceof window$1.ImageBitmap ? exported$1.getImageData(image) : image;
        const {width, height} = imageData;
        // Flow can't refine the type enough to exclude ImageBitmap
        const data = imageData.data;
        if (width === undefined || height === undefined) {
            this.fire(new ErrorEvent(new Error('Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));
            return;
        }
        if (width !== existingImage.data.width || height !== existingImage.data.height) {
            this.fire(new ErrorEvent(new Error(`The width and height of the updated image (${ width }, ${ height })
                must be that same as the previous version of the image
                (${ existingImage.data.width }, ${ existingImage.data.height })`)));
            return;
        }
        const copy = !(image instanceof window$1.HTMLImageElement || window$1.ImageBitmap && image instanceof window$1.ImageBitmap);
        existingImage.data.replace(data, copy);
        this.style.updateImage(id, existingImage);
    }
    /**
     * Check whether or not an image with a specific ID exists in the style. This checks both images
     * in the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) and any images
     * that have been added at runtime using {@link Map#addImage}.
     *
     * @param {string} id The ID of the image.
     *
     * @returns {boolean} A Boolean indicating whether the image exists.
     * @example
     * // Check if an image with the ID 'cat' exists in
     * // the style's sprite.
     * const catIconExists = map.hasImage('cat');
     */
    hasImage(id) {
        if (!id) {
            this.fire(new ErrorEvent(new Error('Missing required image id')));
            return false;
        }
        if (!this.style)
            return false;
        return !!this.style.getImage(id);
    }
    /**
     * Remove an image from a style. This can be an image from the style's original
     * [sprite](https://docs.mapbox.com/help/glossary/sprite/) or any images
     * that have been added at runtime using {@link Map#addImage}.
     *
     * @param {string} id The ID of the image.
     *
     * @example
     * // If an image with the ID 'cat' exists in
     * // the style's sprite, remove it.
     * if (map.hasImage('cat')) map.removeImage('cat');
     */
    removeImage(id) {
        this.style.removeImage(id);
    }
    /**
     * Load an image from an external URL to be used with {@link Map#addImage}. External
     * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).
     *
     * @param {string} url The URL of the image file. Image file must be in png, webp, or jpg format.
     * @param {Function} callback Expecting `callback(error, data)`. Called when the image has loaded or with an error argument if there is an error.
     *
     * @example
     * // Load an image from an external URL.
     * map.loadImage('http://placekitten.com/50/50', (error, image) => {
     *     if (error) throw error;
     *     // Add the loaded image to the style's sprite with the ID 'kitten'.
     *     map.addImage('kitten', image);
     * });
     *
     * @see [Example: Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)
     */
    loadImage(url, callback) {
        getImage(this._requestManager.transformRequest(url, ResourceType.Image), (err, img) => {
            callback(err, img instanceof window$1.HTMLImageElement ? exported$1.getImageData(img) : img);
        });
    }
    /**
    * Returns an Array of strings containing the IDs of all images currently available in the map.
    * This includes both images from the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/)
    * and any images that have been added at runtime using {@link Map#addImage}.
    *
    * @returns {Array<string>} An Array of strings containing the names of all sprites/images currently available in the map.
    *
    * @example
    * const allImages = map.listImages();
    */
    listImages() {
        return this.style.listImages();
    }
    /**
     * @section {Models}
     * @private
     */
    // eslint-disable-next-line jsdoc/require-returns
    /**
     * Add a model to the style. This model can be displayed on the map like any other model in the style
     * using the model ID in conjunction with a 2D vector layer. This API can also be used for updating
     * a model. If the model for a given `modelId` was already added, it gets replaced by the new model.
     *
     * @param {string} id The ID of the model.
     * @param {string} url Pointing to the model to load.
     *
     * @example
     * // If the style does not already contain a model with ID 'tree',
     * // load a tree model and then use a geojson to show it.
     * map.addModel('tree', 'http://path/to/my/tree.glb');
     * map.addLayer({
     *     "id": "tree-layer",
     *     "type": "model",
     *     "source": "trees",
     *     "source-layer": "trees",
     *     "layout": {
     *         "model-id": "tree"
     *     }
     *});
     *
     * @private
     */
    addModel(id, url) {
        this._lazyInitEmptyStyle();
        this.style.addModel(id, url);
    }
    /**
     * Check whether or not a model with a specific ID exists in the style. This checks both models
     * in the style and any models that have been added at runtime using {@link Map#addModel}.
     *
     * @param {string} id The ID of the model.
     *
     * @returns {boolean} A Boolean indicating whether the model exists.
     * @example
     * // Check if a model with the ID 'tree' exists in
     * // the style.
     * const treeModelExists = map.hasModel('tree');
     *
     * @private
     */
    hasModel(id) {
        if (!id) {
            this.fire(new ErrorEvent(new Error('Missing required model id')));
            return false;
        }
        return this.style.hasModel(id);
    }
    /**
     * Remove an model from a style. This can be a model from the style original
     *  or any models that have been added at runtime using {@link Map#addModel}.
     *
     * @param {string} id The ID of the model.
     *
     * @example
     * // If an model with the ID 'tree' exists in
     * // the style, remove it.
     * if (map.hasModel('tree')) map.removeModel('tree');
     *
     * @private
     */
    removeModel(id) {
        this.style.removeModel(id);
    }
    /**
    * Returns an Array of strings containing the IDs of all models currently available in the map.
    * This includes both models from the style and any models that have been added at runtime using {@link Map#addModel}.
    *
    * @returns {Array<string>} An Array of strings containing the names of all model IDs currently available in the map.
    *
    * @example
    * const allModels = map.listModels();
    *
    * @private
    */
    listModels() {
        return this.style.listModels();
    }
    /** @section {Layers} */
    /**
     * Adds a [Mapbox style layer](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers)
     * to the map's style.
     *
     * A layer defines how data from a specified source will be styled. Read more about layer types
     * and available paint and layout properties in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers).
     *
     * @param {Object | CustomLayerInterface} layer The layer to add, conforming to either the Mapbox Style Specification's [layer definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) or, less commonly, the {@link CustomLayerInterface} specification.
     *     The Mapbox Style Specification's layer definition is appropriate for most layers.
     *
     * @param {string} layer.id A unique identifier that you define.
     * @param {string} layer.type The type of layer (for example `fill` or `symbol`).
     *     A list of layer types is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type).
     *
     *     This can also be `custom`. For more information, see {@link CustomLayerInterface}.
     * @param {string | Object} [layer.source] The data source for the layer.
     *     Reference a source that has _already been defined_ using the source's unique id.
     *     Reference a _new source_ using a source object (as defined in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/)) directly.
     *     This is **required** for all `layer.type` options _except_ for `custom` and `background`.
     * @param {string} [layer.sourceLayer] (optional) The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) within the specified `layer.source` to use for this style layer.
     *     This is only applicable for vector tile sources and is **required** when `layer.source` is of the type `vector`.
     * @param {Array} [layer.filter] (optional) An expression specifying conditions on source features.
     *     Only features that match the filter are displayed.
     *     The Mapbox Style Specification includes more information on the limitations of the [`filter`](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) parameter
     *     and a complete list of available [expressions](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/).
     *     If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed.
     * @param {Object} [layer.paint] (optional) Paint properties for the layer.
     *     Available paint properties vary by `layer.type`.
     *     A full list of paint properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/).
     *     If no paint properties are specified, default values will be used.
     * @param {Object} [layer.layout] (optional) Layout properties for the layer.
     *     Available layout properties vary by `layer.type`.
     *     A full list of layout properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/).
     *     If no layout properties are specified, default values will be used.
     * @param {number} [layer.maxzoom] (optional) The maximum zoom level for the layer.
     *     At zoom levels equal to or greater than the maxzoom, the layer will be hidden.
     *     The value can be any number between `0` and `24` (inclusive).
     *     If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.
     * @param {number} [layer.minzoom] (optional) The minimum zoom level for the layer.
     *     At zoom levels less than the minzoom, the layer will be hidden.
     *     The value can be any number between `0` and `24` (inclusive).
     *     If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.
     * @param {Object} [layer.metadata] (optional) Arbitrary properties useful to track with the layer, but do not influence rendering.
     * @param {string} [layer.renderingMode] This is only applicable for layers with the type `custom`.
     *     See {@link CustomLayerInterface} for more information.
     * @param {string} [beforeId] The ID of an existing layer to insert the new layer before,
     *     resulting in the new layer appearing visually beneath the existing layer.
     *     If this argument is not specified, the layer will be appended to the end of the layers array
     *     and appear visually above all other layers.
     *
     * @returns {Map} Returns itself to allow for method chaining.
     *
     * @example
     * // Add a circle layer with a vector source
     * map.addLayer({
     *     id: 'points-of-interest',
     *     source: {
     *         type: 'vector',
     *         url: 'mapbox://mapbox.mapbox-streets-v8'
     *     },
     *     'source-layer': 'poi_label',
     *     type: 'circle',
     *     paint: {
     *     // Mapbox Style Specification paint properties
     *     },
     *     layout: {
     *     // Mapbox Style Specification layout properties
     *     }
     * });
     *
     * @example
     * // Define a source before using it to create a new layer
     * map.addSource('state-data', {
     *     type: 'geojson',
     *     data: 'path/to/data.geojson'
     * });
     *
     * map.addLayer({
     *     id: 'states',
     *     // References the GeoJSON source defined above
     *     // and does not require a `source-layer`
     *     source: 'state-data',
     *     type: 'symbol',
     *     layout: {
     *         // Set the label content to the
     *         // feature's `name` property
     *         'text-field': ['get', 'name']
     *     }
     * });
     *
     * @example
     * // Add a new symbol layer before an existing layer
     * map.addLayer({
     *     id: 'states',
     *     // References a source that's already been defined
     *     source: 'state-data',
     *     type: 'symbol',
     *     layout: {
     *         // Set the label content to the
     *         // feature's `name` property
     *         'text-field': ['get', 'name']
     *     }
     * // Add the layer before the existing `cities` layer
     * }, 'cities');
     *
     * @see [Example: Select features around a clicked point](https://docs.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures-around-point/) (fill layer)
     * @see [Example: Add a new layer below labels](https://docs.mapbox.com/mapbox-gl-js/example/geojson-layer-in-stack/)
     * @see [Example: Create and style clusters](https://docs.mapbox.com/mapbox-gl-js/example/cluster/) (circle layer)
     * @see [Example: Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/) (line layer)
     * @see [Example: Add a WMS layer](https://docs.mapbox.com/mapbox-gl-js/example/wms/) (raster layer)
     */
    addLayer(layer, beforeId) {
        if (!this._isValidId(layer.id)) {
            return this;
        }
        this._lazyInitEmptyStyle();
        this.style.addLayer(layer, beforeId);
        return this._update(true);
    }
    /**
     * Moves a layer to a different z-position.
     *
     * @param {string} id The ID of the layer to move.
     * @param {string} [beforeId] The ID of an existing layer to insert the new layer before. When viewing the map, the `id` layer will appear beneath the `beforeId` layer. If `beforeId` is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.
     * @returns {Map} Returns itself to allow for method chaining.
     *
     * @example
     * // Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map.
     * map.moveLayer('polygon', 'country-label');
     */
    moveLayer(id, beforeId) {
        if (!this._isValidId(id)) {
            return this;
        }
        this.style.moveLayer(id, beforeId);
        return this._update(true);
    }
    /**
     * Removes the layer with the given ID from the map's style.
     *
     * If no such layer exists, an `error` event is fired.
     *
     * @param {string} id ID of the layer to remove.
     * @returns {Map} Returns itself to allow for method chaining.
     * @fires Map.event:error
     *
     * @example
     * // If a layer with ID 'state-data' exists, remove it.
     * if (map.getLayer('state-data')) map.removeLayer('state-data');
     */
    removeLayer(id) {
        if (!this._isValidId(id)) {
            return this;
        }
        this.style.removeLayer(id);
        return this._update(true);
    }
    /**
     * Returns the layer with the specified ID in the map's style.
     *
     * @param {string} id The ID of the layer to get.
     * @returns {?Object} The layer with the specified ID, or `undefined`
     *     if the ID corresponds to no existing layers.
     *
     * @example
     * const stateDataLayer = map.getLayer('state-data');
     *
     * @see [Example: Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/)
     * @see [Example: Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/)
     */
    getLayer(id) {
        if (!this._isValidId(id)) {
            return null;
        }
        return this.style.getOwnLayer(id);
    }
    /**
     * Sets the zoom extent for the specified style layer. The zoom extent includes the
     * [minimum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-minzoom)
     * and [maximum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-maxzoom))
     * at which the layer will be rendered.
     *
     * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the
     * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum
     * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style
     * layer will not be rendered at all zoom levels in the zoom range.
     *
     * @param {string} layerId The ID of the layer to which the zoom extent will be applied.
     * @param {number} minzoom The minimum zoom to set (0-24).
     * @param {number} maxzoom The maximum zoom to set (0-24).
     * @returns {Map} Returns itself to allow for method chaining.
     *
     * @example
     * map.setLayerZoomRange('my-layer', 2, 5);
     */
    setLayerZoomRange(layerId, minzoom, maxzoom) {
        if (!this._isValidId(layerId)) {
            return this;
        }
        this.style.setLayerZoomRange(layerId, minzoom, maxzoom);
        return this._update(true);
    }
    /**
     * Sets the filter for the specified style layer.
     *
     * Filters control which features a style layer renders from its source.
     * Any feature for which the filter expression evaluates to `true` will be
     * rendered on the map. Those that are false will be hidden.
     *
     * Use `setFilter` to show a subset of your source data.
     *
     * To clear the filter, pass `null` or `undefined` as the second parameter.
     *
     * @param {string} layerId The ID of the layer to which the filter will be applied.
     * @param {Array | null | undefined} filter The filter, conforming to the Mapbox Style Specification's
     *     [filter definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter).  If `null` or `undefined` is provided, the function removes any existing filter from the layer.
     * @param {Object} [options] Options object.
     * @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.
     * @returns {Map} Returns itself to allow for method chaining.
     *
     * @example
     * // display only features with the 'name' property 'USA'
     * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);
     * @example
     * // display only features with five or more 'available-spots'
     * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);
     * @example
     * // remove the filter for the 'bike-docks' style layer
     * map.setFilter('bike-docks', null);
     *
     * @see [Example: Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
     * @see [Example: Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)
     * @see [Example: Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)
     * @see [Tutorial: Show changes over time](https://docs.mapbox.com/help/tutorials/show-changes-over-time/)
     */
    setFilter(layerId, filter, options = {}) {
        if (!this._isValidId(layerId)) {
            return this;
        }
        this.style.setFilter(layerId, filter, options);
        return this._update(true);
    }
    /**
     * Returns the filter applied to the specified style layer.
     *
     * @param {string} layerId The ID of the style layer whose filter to get.
     * @returns {Array} The layer's filter.
     * @example
     * const filter = map.getFilter('myLayer');
     */
    getFilter(layerId) {
        if (!this._isValidId(layerId)) {
            return null;
        }
        return this.style.getFilter(layerId);
    }
    /**
     * Sets the value of a paint property in the specified style layer.
     *
     * @param {string} layerId The ID of the layer to set the paint property in.
     * @param {string} name The name of the paint property to set.
     * @param {*} value The value of the paint property to set.
     *     Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).
     * @param {Object} [options] Options object.
     * @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.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setPaintProperty('my-layer', 'fill-color', '#faafee');
     * @see [Example: Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/)
     * @see [Example: Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/)
     * @see [Example: Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)
     */
    setPaintProperty(layerId, name, value, options = {}) {
        if (!this._isValidId(layerId)) {
            return this;
        }
        this.style.setPaintProperty(layerId, name, value, options);
        return this._update(true);
    }
    /**
     * Returns the value of a paint property in the specified style layer.
     *
     * @param {string} layerId The ID of the layer to get the paint property from.
     * @param {string} name The name of a paint property to get.
     * @returns {*} The value of the specified paint property.
     * @example
     * const paintProperty = map.getPaintProperty('mySymbolLayer', 'icon-color');
     */
    getPaintProperty(layerId, name) {
        if (!this._isValidId(layerId)) {
            return null;
        }
        return this.style.getPaintProperty(layerId, name);
    }
    /**
     * Sets the value of a layout property in the specified style layer.
     *
     * @param {string} layerId The ID of the layer to set the layout property in.
     * @param {string} name The name of the layout property to set.
     * @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/).
     * @param {Object} [options] Options object.
     * @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.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setLayoutProperty('my-layer', 'visibility', 'none');
     * @see [Example: Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)
     */
    setLayoutProperty(layerId, name, value, options = {}) {
        if (!this._isValidId(layerId)) {
            return this;
        }
        this.style.setLayoutProperty(layerId, name, value, options);
        return this._update(true);
    }
    /**
     * Returns the value of a layout property in the specified style layer.
     *
     * @param {string} layerId The ID of the layer to get the layout property from.
     * @param {string} name The name of the layout property to get.
     * @returns {*} The value of the specified layout property.
     * @example
     * const layoutProperty = map.getLayoutProperty('mySymbolLayer', 'icon-anchor');
     */
    getLayoutProperty(layerId, name) {
        if (!this._isValidId(layerId)) {
            return null;
        }
        return this.style.getLayoutProperty(layerId, name);
    }
    /** @section {Style properties} */
    /**
     * Sets the value of a configuration property in the currently set style.
     *
     * @param {string} importId The name of the imported style to set the config for (e.g. `basemap`).
     * @param {string} configName The name of the configuration property from the style.
     * @param {*} value The value of the configuration property. Must be of a type appropriate for the property, as defined by the style configuration schema.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setConfigProperty('basemap', 'showLabels', false);
     */
    setConfigProperty(importId, configName, value) {
        this.style.setConfigProperty(importId, configName, value);
        return this._update(true);
    }
    /**
     * Adds a set of Mapbox style light to the map's style.
     *
     * _Note: This light is not to confuse with our legacy light API used through {@link Map#setLight} and {@link Map#getLight}_.
     *
     * @param {Array<LightsSpecification>} lights An array of lights to add, conforming to the Mapbox Style Specification's light definition.
     * @returns {Map} Returns itself to allow for method chaining.
     *
     * @example
     * // Add a directional light
     * map.setLights([{
     *     "id": "sun_light",
     *     "type": "directional",
     *     "properties": {
     *         "color": "rgba(255.0, 0.0, 0.0, 1.0)",
     *         "intensity": 0.4,
     *         "direction": [200.0, 40.0],
     *         "cast-shadows": true,
     *         "shadow-intensity": 0.2
     *     }
     * }]);
     */
    setLights(lights) {
        this._lazyInitEmptyStyle();
        if (lights && lights.length === 1 && lights[0].type === 'flat') {
            const flatLight = lights[0];
            if (!flatLight.properties) {
                this.style.setFlatLight({}, 'flat');
            } else {
                this.style.setFlatLight(flatLight.properties, flatLight.id, {});
            }
        } else {
            this.style.setLights(lights);
            if (this.painter.terrain) {
                this.painter.terrain.invalidateRenderCache = true;
            }
        }
        return this._update(true);
    }
    /**
     * Returns the lights added to the map.
     *
     * @returns {Array<LightSpecification>} Lights added to the map.
     * @example
     * const lights = map.getLights();
     */
    getLights() {
        const lights = this.style.getLights() || [];
        if (lights.length === 0) {
            lights.push({
                'id': this.style.light.id,
                'type': 'flat',
                'properties': this.style.getFlatLight()
            });
        }
        return lights;
    }
    /**
     * Sets the any combination of light values.
     *
     * _Note: that this API is part of the legacy light API, prefer using {@link Map#setLights}.
     *
     * @param {LightSpecification} light Light properties to set. Must conform to the [Light Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light).
     * @param {Object} [options] Options object.
     * @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.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setLight({
     *     "anchor": "viewport",
     *     "color": "blue",
     *     "intensity": 0.5
     * });
     */
    // eslint-disable-next-line no-unused-vars
    setLight(light, options = {}) {
        console.log('The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead.');
        return this.setLights([{
                'id': 'flat',
                'type': 'flat',
                'properties': light
            }]);
    }
    /**
     * Returns the value of the light object.
     *
     * @returns {LightSpecification} Light properties of the style.
     * @example
     * const light = map.getLight();
     */
    getLight() {
        console.log('The `map.getLight` function is deprecated, prefer using `map.getLights` instead.');
        return this.style.getFlatLight();
    }
    // eslint-disable-next-line jsdoc/require-returns
    /**
     * Sets the terrain property of the style.
     *
     * @param {TerrainSpecification} terrain Terrain properties to set. Must conform to the [Terrain Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/terrain/).
     *     If `null` or `undefined` is provided, function removes terrain.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.addSource('mapbox-dem', {
     *     'type': 'raster-dem',
     *     'url': 'mapbox://mapbox.mapbox-terrain-dem-v1',
     *     'tileSize': 512,
     *     'maxzoom': 14
     * });
     * // add the DEM source as a terrain layer with exaggerated height
     * map.setTerrain({'source': 'mapbox-dem', 'exaggeration': 1.5});
     */
    setTerrain(terrain) {
        this._lazyInitEmptyStyle();
        if (!terrain && this.transform.projection.requiresDraping) {
            this.style.setTerrainForDraping();
        } else {
            this.style.setTerrain(terrain);
        }
        this._averageElevationLastSampledAt = -Infinity;
        return this._update(true);
    }
    /**
     * Returns the terrain specification or `null` if terrain isn't set on the map.
     *
     * @returns {TerrainSpecification | null} Terrain specification properties of the style.
     * @example
     * const terrain = map.getTerrain();
     */
    getTerrain() {
        return this.style ? this.style.getTerrain() : null;
    }
    /**
     * Sets the fog property of the style.
     *
     * @param {FogSpecification} fog The fog properties to set. Must conform to the [Fog Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/fog/).
     *     If `null` or `undefined` is provided, this function call removes the fog from the map.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setFog({
     *     "range": [0.8, 8],
     *     "color": "#dc9f9f",
     *     "horizon-blend": 0.5,
     *     "high-color": "#245bde",
     *     "space-color": "#000000",
     *     "star-intensity": 0.15
     * });
     * @see [Example: Add fog to a map](https://docs.mapbox.com/mapbox-gl-js/example/add-fog/)
     */
    setFog(fog) {
        this._lazyInitEmptyStyle();
        this.style.setFog(fog);
        return this._update(true);
    }
    /**
     * Returns the fog specification or `null` if fog is not set on the map.
     *
     * @returns {FogSpecification} Fog specification properties of the style.
     * @example
     * const fog = map.getFog();
     */
    getFog() {
        return this.style ? this.style.getFog() : null;
    }
    /**
     * Sets the camera property of the style.
     *
     * @param {CameraSpecification} camera The camera properties to set. Must conform to the Camera Style Specification.
     * @returns {Map} Returns itself to allow for method chaining.
     * @example
     * map.setCamera({
     *     "camera-projection": "perspective",
     * });
     */
    setCamera(camera) {
        this.style.setCamera(camera);
        return this._triggerCameraUpdate(camera);
    }
    _triggerCameraUpdate(camera) {
        return this._update(this.transform.setOrthographicProjectionAtLowPitch(camera['camera-projection'] === 'orthographic'));
    }
    /**
     * Returns the camera options specification.
     *
     * @returns {CameraSpecification} Camera specification properties of the style.
     * @example
     * const camera = map.getCamera();
     */
    getCamera() {
        return this.style.camera;
    }
    /**
     * Returns the fog opacity for a given location.
     *
     * An opacity of 0 means that there is no fog contribution for the given location
     * while a fog opacity of 1.0 means the location is fully obscured by the fog effect.
     *
     * If there is no fog set on the map, this function will return 0.
     *
     * @param {LngLatLike} lnglat The geographical location to evaluate the fog on.
     * @returns {number} A value between 0 and 1 representing the fog opacity, where 1 means fully within, and 0 means not affected by the fog effect.
     * @private
     */
    _queryFogOpacity(lnglat) {
        if (!this.style || !this.style.fog)
            return 0;
        return this.style.fog.getOpacityAtLatLng(LngLat$1.convert(lnglat), this.transform);
    }
    /** @section {Feature state} */
    /**
     * Sets the `state` of a feature.
     * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.
     * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state.
     * Features are identified by their `id` attribute, which can be any number or string.
     *
     * This method can only be used with sources that have a `id` attribute. The `id` attribute can be defined in three ways:
     * - For vector or GeoJSON sources, including an `id` attribute in the original data file.
     * - For vector or GeoJSON sources, using the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option at the time the source is defined.
     * - For GeoJSON sources, using the [`generateId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#geojson-generateId) option to auto-assign an `id` based on the feature's index in the source data. If you change feature data using `map.getSource('some id').setData(...)`, you may need to re-apply state taking into account updated `id` values.
     *
     * _Note: You can use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling_.
     *
     * @param {Object} feature Feature identifier. Feature objects returned from
     *     {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.
     * @param {number | string} feature.id Unique id of the feature. Can be an integer or a string, but supports string values only when the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option has been applied to the source or the string can be cast to an integer.
     * @param {string} feature.source The id of the vector or GeoJSON source for the feature.
     * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required*.
     * @param {Object} state A set of key-value pairs. The values should be valid JSON types.
     * @returns {Map} The map object.
     * @example
     * // When the mouse moves over the `my-layer` layer, update
     * // the feature state for the feature under the mouse
     * map.on('mousemove', 'my-layer', (e) => {
     *     if (e.features.length > 0) {
     *         map.setFeatureState({
     *             source: 'my-source',
     *             sourceLayer: 'my-source-layer',
     *             id: e.features[0].id,
     *         }, {
     *             hover: true
     *         });
     *     }
     * });
     *
     * @see [Example: Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)
     * @see [Tutorial: Create interactive hover effects with Mapbox GL JS](https://docs.mapbox.com/help/tutorials/create-interactive-hover-effects-with-mapbox-gl-js/)
     */
    setFeatureState(feature, state) {
        if (!this._isValidId(feature.source)) {
            return this;
        }
        this.style.setFeatureState(feature, state);
        return this._update();
    }
    // eslint-disable-next-line jsdoc/require-returns
    /**
     * Removes the `state` of a feature, setting it back to the default behavior.
     * If only a `feature.source` is specified, it will remove the state for all features from that source.
     * If `feature.id` is also specified, it will remove all keys for that feature's state.
     * If `key` is also specified, it removes only that key from that feature's state.
     * Features are identified by their `feature.id` attribute, which can be any number or string.
     *
     * @param {Object} feature Identifier of where to remove state. It can be a source, a feature, or a specific key of feature.
     *     Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.
     * @param {number | string} [feature.id] (optional) Unique id of the feature. Can be an integer or a string, but supports string values only when the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option has been applied to the source or the string can be cast to an integer.
     * @param {string} feature.source The id of the vector or GeoJSON source for the feature.
     * @param {string} [feature.sourceLayer] (optional) For vector tile sources, `sourceLayer` is required.
     * @param {string} [key] (optional) The key in the feature state to reset.
     *
     * @example
     * // Reset the entire state object for all features
     * // in the `my-source` source
     * map.removeFeatureState({
     *     source: 'my-source'
     * });
     *
     * @example
     * // When the mouse leaves the `my-layer` layer,
     * // reset the entire state object for the
     * // feature under the mouse
     * map.on('mouseleave', 'my-layer', (e) => {
     *     map.removeFeatureState({
     *         source: 'my-source',
     *         sourceLayer: 'my-source-layer',
     *         id: e.features[0].id
     *     });
     * });
     *
     * @example
     * // When the mouse leaves the `my-layer` layer,
     * // reset only the `hover` key-value pair in the
     * // state for the feature under the mouse
     * map.on('mouseleave', 'my-layer', (e) => {
     *     map.removeFeatureState({
     *         source: 'my-source',
     *         sourceLayer: 'my-source-layer',
     *         id: e.features[0].id
     *     }, 'hover');
     * });
     */
    removeFeatureState(feature, key) {
        if (!this._isValidId(feature.source)) {
            return this;
        }
        this.style.removeFeatureState(feature, key);
        return this._update();
    }
    /**
     * Gets the `state` of a feature.
     * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.
     * Features are identified by their `id` attribute, which can be any number or string.
     *
     * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state)_.
     *
     * @param {Object} feature Feature identifier. Feature objects returned from
     *     {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.
     * @param {number | string} feature.id Unique id of the feature. Can be an integer or a string, but supports string values only when the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option has been applied to the source or the string can be cast to an integer.
     * @param {string} feature.source The id of the vector or GeoJSON source for the feature.
     * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required*.
     *
     * @returns {Object} The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.
     *
     * @example
     * // When the mouse moves over the `my-layer` layer,
     * // get the feature state for the feature under the mouse
     * map.on('mousemove', 'my-layer', (e) => {
     *     if (e.features.length > 0) {
     *         map.getFeatureState({
     *             source: 'my-source',
     *             sourceLayer: 'my-source-layer',
     *             id: e.features[0].id
     *         });
     *     }
     * });
     */
    getFeatureState(feature) {
        if (!this._isValidId(feature.source)) {
            return null;
        }
        return this.style.getFeatureState(feature);
    }
    _updateContainerDimensions() {
        if (!this._container)
            return;
        const width = this._container.getBoundingClientRect().width || 400;
        const height = this._container.getBoundingClientRect().height || 300;
        let transformValues;
        let transformScaleWidth;
        let transformScaleHeight;
        let el = this._container;
        while (el && (!transformScaleWidth || !transformScaleHeight)) {
            const transformMatrix = window$1.getComputedStyle(el).transform;
            if (transformMatrix && transformMatrix !== 'none') {
                transformValues = transformMatrix.match(/matrix.*\((.+)\)/)[1].split(', ');
                if (transformValues[0] && transformValues[0] !== '0' && transformValues[0] !== '1')
                    transformScaleWidth = transformValues[0];
                if (transformValues[3] && transformValues[3] !== '0' && transformValues[3] !== '1')
                    transformScaleHeight = transformValues[3];
            }
            el = el.parentElement;
        }
        this._containerWidth = transformScaleWidth ? Math.abs(width / transformScaleWidth) : width;
        this._containerHeight = transformScaleHeight ? Math.abs(height / transformScaleHeight) : height;
    }
    _detectMissingCSS() {
        const computedColor = window$1.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color');
        if (computedColor !== 'rgb(250, 128, 114)') {
            warnOnce('This page appears to be missing CSS declarations for ' + 'Mapbox GL JS, which may cause the map to display incorrectly. ' + 'Please ensure your page includes mapbox-gl.css, as described ' + 'in https://www.mapbox.com/mapbox-gl-js/api/.');
        }
    }
    _setupContainer() {
        const container = this._container;
        container.classList.add('mapboxgl-map');
        const missingCSSCanary = this._missingCSSCanary = create$a('div', 'mapboxgl-canary', container);
        missingCSSCanary.style.visibility = 'hidden';
        this._detectMissingCSS();
        const canvasContainer = this._canvasContainer = create$a('div', 'mapboxgl-canvas-container', container);
        this._canvas = create$a('canvas', 'mapboxgl-canvas', canvasContainer);
        if (this._interactive) {
            canvasContainer.classList.add('mapboxgl-interactive');
            this._canvas.setAttribute('tabindex', '0');
        }
        // $FlowFixMe[method-unbinding]
        this._canvas.addEventListener('webglcontextlost', this._contextLost, false);
        // $FlowFixMe[method-unbinding]
        this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false);
        this._canvas.setAttribute('aria-label', this._getUIString('Map.Title'));
        this._canvas.setAttribute('role', 'region');
        this._updateContainerDimensions();
        this._resizeCanvas(this._containerWidth, this._containerHeight);
        const controlContainer = this._controlContainer = create$a('div', 'mapboxgl-control-container', container);
        const positions = this._controlPositions = {};
        [
            'top-left',
            'top-right',
            'bottom-left',
            'bottom-right'
        ].forEach(positionName => {
            positions[positionName] = create$a('div', `mapboxgl-ctrl-${ positionName }`, controlContainer);
        });
        // $FlowFixMe[method-unbinding]
        this._container.addEventListener('scroll', this._onMapScroll, false);
    }
    _resizeCanvas(width, height) {
        const pixelRatio = exported$1.devicePixelRatio || 1;
        // Request the required canvas size (rounded up) taking the pixelratio into account.
        this._canvas.width = pixelRatio * Math.ceil(width);
        this._canvas.height = pixelRatio * Math.ceil(height);
        // Maintain the same canvas size, potentially downscaling it for HiDPI displays
        this._canvas.style.width = `${ width }px`;
        this._canvas.style.height = `${ height }px`;
    }
    _addMarker(marker) {
        this._markers.push(marker);
    }
    _removeMarker(marker) {
        const index = this._markers.indexOf(marker);
        if (index !== -1) {
            this._markers.splice(index, 1);
        }
    }
    _addPopup(popup) {
        this._popups.push(popup);
    }
    _removePopup(popup) {
        const index = this._popups.indexOf(popup);
        if (index !== -1) {
            this._popups.splice(index, 1);
        }
    }
    _setupPainter() {
        const attributes = extend$1({}, supported.webGLContextAttributes, {
            failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,
            preserveDrawingBuffer: this._preserveDrawingBuffer,
            antialias: this._antialias || false
        });
        const gl = this._canvas.getContext('webgl2', attributes);
        if (!gl) {
            this.fire(new ErrorEvent(new Error('Failed to initialize WebGL')));
            return;
        }
        storeAuthState(gl, true);
        this.painter = new Painter(gl, this.transform);
        this.on('data', event => {
            if (event.dataType === 'source') {
                this.painter.setTileLoadedFlag(true);
            }
        });
        exported$2.testSupport(gl);
    }
    _contextLost(event) {
        event.preventDefault();
        if (this._frame) {
            this._frame.cancel();
            this._frame = null;
        }
        this.fire(new Event('webglcontextlost', { originalEvent: event }));
    }
    _contextRestored(event) {
        this._setupPainter();
        this.resize();
        this._update();
        this.fire(new Event('webglcontextrestored', { originalEvent: event }));
    }
    _onMapScroll(event) {
        if (event.target !== this._container)
            return;
        // Revert any scroll which would move the canvas outside of the view
        this._container.scrollTop = 0;
        this._container.scrollLeft = 0;
        return false;
    }
    /** @section {Lifecycle} */
    /**
     * Returns a Boolean indicating whether the map is fully loaded.
     *
     * Returns `false` if the style is not yet fully loaded,
     * or if there has been a change to the sources or style that
     * has not yet fully loaded.
     *
     * @returns {boolean} A Boolean indicating whether the map is fully loaded.
     * @example
     * const isLoaded = map.loaded();
     */
    loaded() {
        return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();
    }
    /**
     * Update this map's style and sources, and re-render the map.
     *
     * @param {boolean} updateStyle mark the map's style for reprocessing as
     * well as its sources
     * @returns {Map} this
     * @private
     */
    _update(updateStyle) {
        if (!this.style)
            return this;
        this._styleDirty = this._styleDirty || updateStyle;
        this._sourcesDirty = true;
        this.triggerRepaint();
        return this;
    }
    /**
     * Request that the given callback be executed during the next render
     * frame.  Schedule a render frame if one is not already scheduled.
     * @returns An id that can be used to cancel the callback
     * @private
     */
    // $FlowFixMe[method-unbinding]
    _requestRenderFrame(callback) {
        this._update();
        return this._renderTaskQueue.add(callback);
    }
    // $FlowFixMe[method-unbinding]
    _cancelRenderFrame(id) {
        this._renderTaskQueue.remove(id);
    }
    /**
     * Request that the given callback be executed during the next render frame if the map is not
     * idle. Otherwise it is executed immediately, to avoid triggering a new render.
     * @private
     */
    _requestDomTask(callback) {
        // This condition means that the map is idle: the callback needs to be called right now as
        // there won't be a triggered render to run the queue.
        if (!this.loaded() || this.loaded() && !this.isMoving()) {
            callback();
        } else {
            this._domRenderTaskQueue.add(callback);
        }
    }
    /**
     * Call when a (re-)render of the map is required:
     * - The style has changed (`setPaintProperty()`, etc.)
     * - Source data has changed (for example, tiles have finished loading)
     * - The map has is moving (or just finished moving)
     * - A transition is in progress
     *
     * @param {number} paintStartTimeStamp  The time when the animation frame began executing.
     *
     * @returns {Map} this
     * @private
     */
    _render(paintStartTimeStamp) {
        this.fire(new Event('renderstart'));
        let gpuTimer;
        const extTimerQuery = this.painter.context.extTimerQuery;
        const frameStartTime = exported$1.now();
        const gl = this.painter.context.gl;
        if (this.listens('gpu-timing-frame')) {
            gpuTimer = gl.createQuery();
            gl.beginQuery(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);
        }
        // A custom layer may have used the context asynchronously. Mark the state as dirty.
        this.painter.context.setDirty();
        this.painter.setBaseState();
        if (this.isMoving() || this.isRotating() || this.isZooming()) {
            this._interactionRange[0] = Math.min(this._interactionRange[0], window$1.performance.now());
            this._interactionRange[1] = Math.max(this._interactionRange[1], window$1.performance.now());
        }
        this._renderTaskQueue.run(paintStartTimeStamp);
        this._domRenderTaskQueue.run(paintStartTimeStamp);
        // A task queue callback may have fired a user event which may have removed the map
        if (this._removed)
            return;
        this._updateProjectionTransition();
        const fadeDuration = this._isInitialLoad ? 0 : this._fadeDuration;
        // If the style has changed, the map is being zoomed, or a transition or fade is in progress:
        //  - Apply style changes (in a batch)
        //  - Recalculate paint properties.
        if (this.style && this._styleDirty) {
            this._styleDirty = false;
            const zoom = this.transform.zoom;
            const pitch = this.transform.pitch;
            const now = exported$1.now();
            const parameters = new EvaluationParameters(zoom, {
                now,
                fadeDuration,
                pitch,
                transition: this.style.transition
            });
            this.style.update(parameters);
        }
        if (this.style && this.style.hasFogTransition()) {
            this.style._markersNeedUpdate = true;
            this._sourcesDirty = true;
        }
        // If we are in _render for any reason other than an in-progress paint
        // transition, update source caches to check for and load any tiles we
        // need for the current transform
        let averageElevationChanged = false;
        if (this.style && this._sourcesDirty) {
            this._sourcesDirty = false;
            this.painter._updateFog(this.style);
            this._updateTerrain();
            // Terrain DEM source updates here and skips update in style._updateSources.
            averageElevationChanged = this._updateAverageElevation(frameStartTime);
            this.style.updateSources(this.transform);
            // Update positions of markers and popups on enabling/disabling terrain
            this._forceMarkerAndPopupUpdate();
        } else {
            averageElevationChanged = this._updateAverageElevation(frameStartTime);
        }
        this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions);
        // Actually draw
        if (this.style) {
            this.painter.render(this.style, {
                showTileBoundaries: this.showTileBoundaries,
                wireframe: {
                    terrain: this.showTerrainWireframe,
                    layers2D: this.showLayers2DWireframe,
                    layers3D: this.showLayers3DWireframe
                },
                showOverdrawInspector: this._showOverdrawInspector,
                showQueryGeometry: !!this._showQueryGeometry,
                showTileAABBs: this.showTileAABBs,
                rotating: this.isRotating(),
                zooming: this.isZooming(),
                moving: this.isMoving(),
                fadeDuration,
                isInitialLoad: this._isInitialLoad,
                showPadding: this.showPadding,
                gpuTiming: !!this.listens('gpu-timing-layer'),
                gpuTimingDeferredRender: !!this.listens('gpu-timing-deferred-render'),
                speedIndexTiming: this.speedIndexTiming
            });
        }
        this.fire(new Event('render'));
        if (this.loaded() && !this._loaded) {
            this._loaded = true;
            this.fire(new Event('load'));
        }
        if (this.style && this.style.hasTransitions()) {
            this._styleDirty = true;
        }
        if (this.style && !this._placementDirty) {
            // Since no fade operations are in progress, we can release
            // all tiles held for fading. If we didn't do this, the tiles
            // would just sit in the SourceCaches until the next render
            this.style._releaseSymbolFadeTiles();
        }
        if (gpuTimer) {
            const renderCPUTime = exported$1.now() - frameStartTime;
            gl.endQuery(extTimerQuery.TIME_ELAPSED_EXT);
            setTimeout(() => {
                const renderGPUTime = gl.getQueryParameter(gpuTimer, gl.QUERY_RESULT) / (1000 * 1000);
                gl.deleteQuery(gpuTimer);
                this.fire(new Event('gpu-timing-frame', {
                    cpuTime: renderCPUTime,
                    gpuTime: renderGPUTime
                }));
                window$1.performance.mark('frame-gpu', {
                    startTime: frameStartTime,
                    detail: { gpuTime: renderGPUTime }
                });
            }, 50);    // Wait 50ms to give time for all GPU calls to finish before querying
        }
        if (this.listens('gpu-timing-layer')) {
            // Resetting the Painter's per-layer timing queries here allows us to isolate
            // the queries to individual frames.
            const frameLayerQueries = this.painter.collectGpuTimers();
            setTimeout(() => {
                const renderedLayerTimes = this.painter.queryGpuTimers(frameLayerQueries);
                this.fire(new Event('gpu-timing-layer', { layerTimes: renderedLayerTimes }));
            }, 50);    // Wait 50ms to give time for all GPU calls to finish before querying
        }
        if (this.listens('gpu-timing-deferred-render')) {
            const deferredRenderQueries = this.painter.collectDeferredRenderGpuQueries();
            setTimeout(() => {
                const gpuTime = this.painter.queryGpuTimeDeferredRender(deferredRenderQueries);
                this.fire(new Event('gpu-timing-deferred-render', { gpuTime }));
            }, 50);    // Wait 50ms to give time for all GPU calls to finish before querying
        }
        // Schedule another render frame if it's needed.
        //
        // Even though `_styleDirty` and `_sourcesDirty` are reset in this
        // method, synchronous events fired during Style#update or
        // Style#_updateSources could have caused them to be set again.
        const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty || averageElevationChanged;
        if (somethingDirty || this._repaint) {
            this.triggerRepaint();
        } else {
            const willIdle = !this.isMoving() && this.loaded();
            if (willIdle) {
                // Before idling, we perform one last sample so that if the average elevation
                // does not exactly match the terrain, we skip idle and ease it to its final state.
                averageElevationChanged = this._updateAverageElevation(frameStartTime, true);
            }
            if (averageElevationChanged) {
                this.triggerRepaint();
            } else {
                this._triggerFrame(false);
                if (willIdle) {
                    this.fire(new Event('idle'));
                    this._isInitialLoad = false;
                    // check the options to see if need to calculate the speed index
                    if (this.speedIndexTiming) {
                        const speedIndexNumber = this._calculateSpeedIndex();
                        this.fire(new Event('speedindexcompleted', { speedIndex: speedIndexNumber }));
                        this.speedIndexTiming = false;
                    }
                }
            }
        }
        if (this._loaded && !this._fullyLoaded && !somethingDirty) {
            this._fullyLoaded = true;
            LivePerformanceUtils.mark(PerformanceMarkers.fullLoad);
            // Following lines are billing and metrics related code. Do not change. See LICENSE.txt
            if (this._performanceMetricsCollection) {
                postPerformanceEvent(this._requestManager._customAccessToken, {
                    width: this.painter.width,
                    height: this.painter.height,
                    interactionRange: this._interactionRange,
                    visibilityHidden: this._visibilityHidden,
                    terrainEnabled: !!this.painter.style.getTerrain(),
                    fogEnabled: !!this.painter.style.getFog(),
                    projection: this.getProjection().name,
                    zoom: this.transform.zoom,
                    renderer: this.painter.context.renderer,
                    vendor: this.painter.context.vendor
                });
            }
            this._authenticate();
        }
    }
    _forceMarkerAndPopupUpdate(shouldWrap) {
        for (const marker of this._markers) {
            // Wrap marker location when toggling to a projection without world copies
            if (shouldWrap && !this.getRenderWorldCopies()) {
                marker._lngLat = marker._lngLat.wrap();
            }
            marker._update();
        }
        for (const popup of this._popups) {
            // Wrap popup location when toggling to a projection without world copies and track pointer set to false
            if (shouldWrap && !this.getRenderWorldCopies() && !popup._trackPointer) {
                popup._lngLat = popup._lngLat.wrap();
            }
            popup._update();
        }
    }
    /**
     * Update the average visible elevation by sampling terrain
     *
     * @returns {boolean} true if elevation has changed from the last sampling
     * @private
     */
    _updateAverageElevation(timeStamp, ignoreTimeout = false) {
        const applyUpdate = value => {
            this.transform.averageElevation = value;
            this._update(false);
            return true;
        };
        if (!this.painter.averageElevationNeedsEasing()) {
            if (this.transform.averageElevation !== 0)
                return applyUpdate(0);
            return false;
        }
        const exaggerationChanged = this.transform.elevation && this.transform.elevation.exaggeration() !== this._averageElevationExaggeration;
        const timeoutElapsed = ignoreTimeout || timeStamp - this._averageElevationLastSampledAt > AVERAGE_ELEVATION_SAMPLING_INTERVAL;
        if (exaggerationChanged || timeoutElapsed && !this._averageElevation.isEasing(timeStamp)) {
            const currentElevation = this.transform.averageElevation;
            let newElevation = this.transform.sampleAverageElevation();
            if (this.transform.elevation) {
                // $FlowIgnore[incompatible-use]
                this._averageElevationExaggeration = this.transform.elevation.exaggeration();
            }
            // New elevation is NaN if no terrain tiles were available
            if (isNaN(newElevation)) {
                newElevation = 0;
            } else {
                // Don't activate the timeout if no data was available
                this._averageElevationLastSampledAt = timeStamp;
            }
            const elevationChange = Math.abs(currentElevation - newElevation);
            if (elevationChange > AVERAGE_ELEVATION_EASE_THRESHOLD) {
                if (this._isInitialLoad || exaggerationChanged) {
                    this._averageElevation.jumpTo(newElevation);
                    return applyUpdate(newElevation);
                } else {
                    this._averageElevation.easeTo(newElevation, timeStamp, AVERAGE_ELEVATION_EASE_TIME);
                }
            } else if (elevationChange > AVERAGE_ELEVATION_CHANGE_THRESHOLD) {
                this._averageElevation.jumpTo(newElevation);
                return applyUpdate(newElevation);
            }
        }
        if (this._averageElevation.isEasing(timeStamp)) {
            return applyUpdate(this._averageElevation.getValue(timeStamp));
        }
        return false;
    }
    /***** START WARNING - REMOVAL OR MODIFICATION OF THE
    * FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE  ******
    * The following code is used to access Mapbox's APIs. Removal or modification
    * of this code can result in higher fees and/or
    * termination of your account with Mapbox.
    *
    * Under the Mapbox Terms of Service, you may not use this code to access Mapbox
    * Mapping APIs other than through Mapbox SDKs.
    *
    * The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps
    * and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/
    ******************************************************************************/
    _authenticate() {
        getMapSessionAPI(this._getMapId(), this._requestManager._skuToken, this._requestManager._customAccessToken, err => {
            if (err) {
                // throwing an error here will cause the callback to be called again unnecessarily
                if (err.message === AUTH_ERR_MSG || err.status === 401) {
                    const gl = this.painter.context.gl;
                    storeAuthState(gl, false);
                    if (this._logoControl instanceof LogoControl) {
                        this._logoControl._updateLogo();
                    }
                    if (gl)
                        gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
                    if (!this._silenceAuthErrors) {
                        this.fire(new ErrorEvent(new Error('A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/')));
                    }
                }
            }
        });
        postMapLoadEvent(this._getMapId(), this._requestManager._skuToken, this._requestManager._customAccessToken, () => {
        });
    }
    /***** END WARNING - REMOVAL OR MODIFICATION OF THE
    PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE  ******/
    _updateTerrain() {
        // Recalculate if enabled/disabled and calculate elevation cover. As camera is using elevation tiles before
        // render (and deferred update after zoom recalculation), this needs to be called when removing terrain source.
        const adaptCameraAltitude = this._isDragging();
        this.painter.updateTerrain(this.style, adaptCameraAltitude);
    }
    _calculateSpeedIndex() {
        const finalFrame = this.painter.canvasCopy();
        const canvasCopyInstances = this.painter.getCanvasCopiesAndTimestamps();
        canvasCopyInstances.timeStamps.push(performance.now());
        const gl = this.painter.context.gl;
        const framebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        function read(texture) {
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
            const pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
            gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
            return pixels;
        }
        return this._canvasPixelComparison(read(finalFrame), canvasCopyInstances.canvasCopies.map(read), canvasCopyInstances.timeStamps);
    }
    _canvasPixelComparison(finalFrame, allFrames, timeStamps) {
        let finalScore = timeStamps[1] - timeStamps[0];
        const numPixels = finalFrame.length / 4;
        for (let i = 0; i < allFrames.length; i++) {
            const frame = allFrames[i];
            let cnt = 0;
            for (let j = 0; j < frame.length; j += 4) {
                if (frame[j] === finalFrame[j] && frame[j + 1] === finalFrame[j + 1] && frame[j + 2] === finalFrame[j + 2] && frame[j + 3] === finalFrame[j + 3]) {
                    cnt = cnt + 1;
                }
            }
            //calculate the % visual completeness
            const interval = timeStamps[i + 2] - timeStamps[i + 1];
            const visualCompletness = cnt / numPixels;
            finalScore += interval * (1 - visualCompletness);
        }
        return finalScore;
    }
    /**
     * Clean up and release all internal resources associated with this map.
     *
     * This includes DOM elements, event bindings, web workers, and WebGL resources.
     *
     * Use this method when you are done using the map and wish to ensure that it no
     * longer consumes browser resources. Afterwards, you must not call any other
     * methods on the map.
     *
     * @example
     * map.remove();
     */
    remove() {
        if (this._hash)
            this._hash.remove();
        for (const control of this._controls)
            control.onRemove(this);
        this._controls = [];
        if (this._frame) {
            this._frame.cancel();
            this._frame = null;
        }
        this._renderTaskQueue.clear();
        this._domRenderTaskQueue.clear();
        if (this.style) {
            this.style.destroy();
        }
        this.painter.destroy();
        if (this.handlers)
            this.handlers.destroy();
        this.handlers = undefined;
        this.setStyle(null);
        if (typeof window$1 !== 'undefined') {
            // $FlowFixMe[method-unbinding]
            window$1.removeEventListener('resize', this._onWindowResize, false);
            // $FlowFixMe[method-unbinding]
            window$1.removeEventListener('orientationchange', this._onWindowResize, false);
            // $FlowFixMe[method-unbinding]
            window$1.removeEventListener(this._fullscreenchangeEvent, this._onWindowResize, false);
            // $FlowFixMe[method-unbinding]
            window$1.removeEventListener('online', this._onWindowOnline, false);
            // $FlowFixMe[method-unbinding]
            window$1.removeEventListener('visibilitychange', this._onVisibilityChange, false);
        }
        const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');
        if (extension)
            extension.loseContext();
        // $FlowFixMe[method-unbinding]
        this._canvas.removeEventListener('webglcontextlost', this._contextLost, false);
        // $FlowFixMe[method-unbinding]
        this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false);
        this._canvasContainer.remove();
        this._controlContainer.remove();
        this._missingCSSCanary.remove();
        this._canvas = undefined;
        this._canvasContainer = undefined;
        this._controlContainer = undefined;
        this._missingCSSCanary = undefined;
        this._container.classList.remove('mapboxgl-map');
        // $FlowFixMe[method-unbinding]
        this._container.removeEventListener('scroll', this._onMapScroll, false);
        removeAuthState(this.painter.context.gl);
        this._removed = true;
        this.fire(new Event('remove'));
    }
    /**
     * Trigger the rendering of a single frame. Use this method with custom layers to
     * repaint the map when the layer's properties or properties associated with the
     * layer's source change. Calling this multiple times before the
     * next frame is rendered will still result in only a single frame being rendered.
     *
     * @example
     * map.triggerRepaint();
     * @see [Example: Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/)
     * @see [Example: Add an animated icon to the map](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/)
     */
    triggerRepaint() {
        this._triggerFrame(true);
    }
    _triggerFrame(render) {
        this._renderNextFrame = this._renderNextFrame || render;
        if (this.style && !this._frame) {
            this._frame = exported$1.frame(paintStartTimeStamp => {
                const isRenderFrame = !!this._renderNextFrame;
                this._frame = null;
                this._renderNextFrame = null;
                if (isRenderFrame) {
                    this._render(paintStartTimeStamp);
                }
            });
        }
    }
    /**
     * Preloads all tiles that will be requested for one or a series of transformations
     *
     * @private
     * @returns {Object} Returns `this` | Promise.
     */
    // $FlowFixMe[method-unbinding]
    _preloadTiles(transform) {
        const sources = this.style ? Object.values(this.style._sourceCaches) : [];
        asyncAll(sources, (source, done) => source._preloadTiles(transform, done), () => {
            this.triggerRepaint();
        });
        return this;
    }
    _onWindowOnline() {
        this._update();
    }
    _onWindowResize(event) {
        if (this._trackResize) {
            this.resize({ originalEvent: event })._update();
        }
    }
    _onVisibilityChange() {
        if (window$1.document.visibilityState === 'hidden') {
            this._visibilityHidden++;
        }
    }
    /** @section {Debug features} */
    /**
     * Gets and sets a Boolean indicating whether the map will render an outline
     * around each tile and the tile ID. These tile boundaries are useful for
     * debugging.
     *
     * The uncompressed file size of the first vector source is drawn in the top left
     * corner of each tile, next to the tile ID.
     *
     * @name showTileBoundaries
     * @type {boolean}
     * @instance
     * @memberof Map
     * @example
     * map.showTileBoundaries = true;
     */
    get showTileBoundaries() {
        return !!this._showTileBoundaries;
    }
    set showTileBoundaries(value) {
        if (this._showTileBoundaries === value)
            return;
        this._showTileBoundaries = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the map will render a wireframe
     * on top of the displayed terrain. Useful for debugging.
     *
     * The wireframe is always red and is drawn only when terrain is active.
     *
     * @name showTerrainWireframe
     * @type {boolean}
     * @instance
     * @memberof Map
     * @example
     * map.showTerrainWireframe = true;
     */
    get showTerrainWireframe() {
        return !!this._showTerrainWireframe;
    }
    set showTerrainWireframe(value) {
        if (this._showTerrainWireframe === value)
            return;
        this._showTerrainWireframe = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the map will render a wireframe
     * on top of 2D layers. Useful for debugging.
     *
     * The wireframe is always red and is drawn only for 2D layers.
     *
     * @name showLayers2DWireframe
     * @type {boolean}
     * @instance
     * @memberof Map
     * @example
     * map.showLayers2DWireframe = true;
     */
    get showLayers2DWireframe() {
        return !!this._showLayers2DWireframe;
    }
    set showLayers2DWireframe(value) {
        if (this._showLayers2DWireframe === value)
            return;
        this._showLayers2DWireframe = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the map will render a wireframe
     * on top of 3D layers. Useful for debugging.
     *
     * The wireframe is always red and is drawn only for 3D layers.
     *
     * @name showLayers3DWireframe
     * @type {boolean}
     * @instance
     * @memberof Map
     * @example
     * map.showLayers3DWireframe = true;
     */
    get showLayers3DWireframe() {
        return !!this._showLayers3DWireframe;
    }
    set showLayers3DWireframe(value) {
        if (this._showLayers3DWireframe === value)
            return;
        this._showLayers3DWireframe = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the speedindex metric calculation is on or off
     *
     * @private
     * @name speedIndexTiming
     * @type {boolean}
     * @instance
     * @memberof Map
     * @example
     * map.speedIndexTiming = true;
     */
    get speedIndexTiming() {
        return !!this._speedIndexTiming;
    }
    set speedIndexTiming(value) {
        if (this._speedIndexTiming === value)
            return;
        this._speedIndexTiming = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the map will visualize
     * the padding offsets.
     *
     * @name showPadding
     * @type {boolean}
     * @instance
     * @memberof Map
     */
    get showPadding() {
        return !!this._showPadding;
    }
    set showPadding(value) {
        if (this._showPadding === value)
            return;
        this._showPadding = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the map will render boxes
     * around all symbols in the data source, revealing which symbols
     * were rendered or which were hidden due to collisions.
     * This information is useful for debugging.
     *
     * @name showCollisionBoxes
     * @type {boolean}
     * @instance
     * @memberof Map
     */
    get showCollisionBoxes() {
        return !!this._showCollisionBoxes;
    }
    set showCollisionBoxes(value) {
        if (this._showCollisionBoxes === value)
            return;
        this._showCollisionBoxes = value;
        if (value) {
            // When we turn collision boxes on we have to generate them for existing tiles
            // When we turn them off, there's no cost to leaving existing boxes in place
            this.style._generateCollisionBoxes();
        } else {
            // Otherwise, call an update to remove collision boxes
            this._update();
        }
    }
    /**
     * Gets and sets a Boolean indicating whether the map should color-code
     * each fragment to show how many times it has been shaded.
     * White fragments have been shaded 8 or more times.
     * Black fragments have been shaded 0 times.
     * This information is useful for debugging.
     *
     * @name showOverdraw
     * @type {boolean}
     * @instance
     * @memberof Map
     */
    get showOverdrawInspector() {
        return !!this._showOverdrawInspector;
    }
    set showOverdrawInspector(value) {
        if (this._showOverdrawInspector === value)
            return;
        this._showOverdrawInspector = value;
        this._update();
    }
    /**
     * Gets and sets a Boolean indicating whether the map will
     * continuously repaint. This information is useful for analyzing performance.
     *
     * @name repaint
     * @type {boolean}
     * @instance
     * @memberof Map
     */
    get repaint() {
        return !!this._repaint;
    }
    set repaint(value) {
        if (this._repaint !== value) {
            this._repaint = value;
            this.triggerRepaint();
        }
    }
    // show vertices
    get vertices() {
        return !!this._vertices;
    }
    set vertices(value) {
        this._vertices = value;
        this._update();
    }
    /**
    * Display tile AABBs for debugging
    *
    * @private
    * @type {boolean}
    */
    get showTileAABBs() {
        return !!this._showTileAABBs;
    }
    set showTileAABBs(value) {
        if (this._showTileAABBs === value)
            return;
        this._showTileAABBs = value;
        if (!value) {
            return;
        }
        this._update();
    }
    // for cache browser tests
    _setCacheLimits(limit, checkThreshold) {
        setCacheLimits(limit, checkThreshold);
    }
    /**
     * The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.
     *
     * @name version
     * @instance
     * @memberof Map
     * @var {string} version
     */
    get version() {
        return version;
    }
};
                       /**
 * Register a control on the map and give it a chance to register event listeners
 * and resources. This method is called by {@link Map#addControl}
 * internally.
 *
 * @function
 * @memberof IControl
 * @instance
 * @name onAdd
 * @param {Map} map The Map this control will be added to.
 * @returns {HTMLElement} The control's container element. This should
 *     be created by the control and returned by onAdd without being attached
 *     to the DOM: the map will insert the control's element into the DOM
 *     as necessary.
 */
                       /**
 * Unregister a control on the map and give it a chance to detach event listeners
 * and resources. This method is called by {@link Map#removeControl}
 * internally.
 *
 * @function
 * @memberof IControl
 * @instance
 * @name onRemove
 * @param {Map} map The Map this control will be removed from.
 * @returns {undefined} There is no required return value for this method.
 */
                       /**
 * Optionally provide a default position for this control. If this method
 * is implemented and {@link Map#addControl} is called without the `position`
 * parameter, the value returned by getDefaultPosition will be used as the
 * control's position.
 *
 * @function
 * @memberof IControl
 * @instance
 * @name getDefaultPosition
 * @returns {string} A control position, one of the values valid in addControl.
 */
                       /**
 * A [`Point` geometry](https://github.com/mapbox/point-geometry) object, which has
 * `x` and `y` properties representing screen coordinates in pixels.
 *
 * @typedef {Point} Point
 * @example
 * const point = new mapboxgl.Point(-77, 38);
 */
                       /**
 * A {@link Point} or an array of two numbers representing `x` and `y` screen coordinates in pixels.
 *
 * @typedef {(Point | Array<number>)} PointLike
 * @example
 * const p1 = new mapboxgl.Point(-77, 38); // a PointLike which is a Point
 * const p2 = [-77, 38]; // a PointLike which is an array of two numbers
 */

//      
const defaultOptions$2 = {
    showCompass: true,
    showZoom: true,
    visualizePitch: false
};
/**
 * A `NavigationControl` control contains zoom buttons and a compass.
 * Add this control to a map using {@link Map#addControl}.
 *
 * @implements {IControl}
 * @param {Object} [options]
 * @param {boolean} [options.showCompass=true] If `true` the compass button is included.
 * @param {boolean} [options.showZoom=true] If `true` the zoom-in and zoom-out buttons are included.
 * @param {boolean} [options.visualizePitch=false] If `true` the pitch is visualized by rotating X-axis of compass.
 * @example
 * const nav = new mapboxgl.NavigationControl();
 * map.addControl(nav, 'top-left');
 * @example
 * const nav = new mapboxgl.NavigationControl({
 *     visualizePitch: true
 * });
 * map.addControl(nav, 'bottom-right');
 * @see [Example: Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)
 * @see [Example: Add a third party vector tile source](https://www.mapbox.com/mapbox-gl-js/example/third-party/)
 */
class NavigationControl {
    constructor(options) {
        this.options = extend$1({}, defaultOptions$2, options);
        this._container = create$a('div', 'mapboxgl-ctrl mapboxgl-ctrl-group');
        this._container.addEventListener('contextmenu', e => e.preventDefault());
        if (this.options.showZoom) {
            bindAll([
                '_setButtonTitle',
                '_updateZoomButtons'
            ], this);
            this._zoomInButton = this._createButton('mapboxgl-ctrl-zoom-in', e => {
                if (this._map)
                    this._map.zoomIn({}, { originalEvent: e });
            });
            create$a('span', `mapboxgl-ctrl-icon`, this._zoomInButton).setAttribute('aria-hidden', 'true');
            this._zoomOutButton = this._createButton('mapboxgl-ctrl-zoom-out', e => {
                if (this._map)
                    this._map.zoomOut({}, { originalEvent: e });
            });
            create$a('span', `mapboxgl-ctrl-icon`, this._zoomOutButton).setAttribute('aria-hidden', 'true');
        }
        if (this.options.showCompass) {
            bindAll(['_rotateCompassArrow'], this);
            this._compass = this._createButton('mapboxgl-ctrl-compass', e => {
                const map = this._map;
                if (!map)
                    return;
                if (this.options.visualizePitch) {
                    map.resetNorthPitch({}, { originalEvent: e });
                } else {
                    map.resetNorth({}, { originalEvent: e });
                }
            });
            this._compassIcon = create$a('span', 'mapboxgl-ctrl-icon', this._compass);
            this._compassIcon.setAttribute('aria-hidden', 'true');
        }
    }
    _updateZoomButtons() {
        const map = this._map;
        if (!map)
            return;
        const zoom = map.getZoom();
        const isMax = zoom === map.getMaxZoom();
        const isMin = zoom === map.getMinZoom();
        this._zoomInButton.disabled = isMax;
        this._zoomOutButton.disabled = isMin;
        this._zoomInButton.setAttribute('aria-disabled', isMax.toString());
        this._zoomOutButton.setAttribute('aria-disabled', isMin.toString());
    }
    _rotateCompassArrow() {
        const map = this._map;
        if (!map)
            return;
        const rotate = this.options.visualizePitch ? `scale(${ 1 / Math.pow(Math.cos(map.transform.pitch * (Math.PI / 180)), 0.5) }) rotateX(${ map.transform.pitch }deg) rotateZ(${ map.transform.angle * (180 / Math.PI) }deg)` : `rotate(${ map.transform.angle * (180 / Math.PI) }deg)`;
        map._requestDomTask(() => {
            if (this._compassIcon) {
                this._compassIcon.style.transform = rotate;
            }
        });
    }
    onAdd(map) {
        this._map = map;
        if (this.options.showZoom) {
            this._setButtonTitle(this._zoomInButton, 'ZoomIn');
            this._setButtonTitle(this._zoomOutButton, 'ZoomOut');
            // $FlowFixMe[method-unbinding]
            map.on('zoom', this._updateZoomButtons);
            this._updateZoomButtons();
        }
        if (this.options.showCompass) {
            this._setButtonTitle(this._compass, 'ResetBearing');
            if (this.options.visualizePitch) {
                // $FlowFixMe[method-unbinding]
                map.on('pitch', this._rotateCompassArrow);
            }
            // $FlowFixMe[method-unbinding]
            map.on('rotate', this._rotateCompassArrow);
            this._rotateCompassArrow();
            this._handler = new MouseRotateWrapper(map, this._compass, this.options.visualizePitch);
        }
        return this._container;
    }
    onRemove() {
        const map = this._map;
        if (!map)
            return;
        this._container.remove();
        if (this.options.showZoom) {
            // $FlowFixMe[method-unbinding]
            map.off('zoom', this._updateZoomButtons);
        }
        if (this.options.showCompass) {
            if (this.options.visualizePitch) {
                // $FlowFixMe[method-unbinding]
                map.off('pitch', this._rotateCompassArrow);
            }
            // $FlowFixMe[method-unbinding]
            map.off('rotate', this._rotateCompassArrow);
            if (this._handler)
                this._handler.off();
            this._handler = undefined;
        }
        this._map = undefined;
    }
    _createButton(className, fn) {
        const a = create$a('button', className, this._container);
        a.type = 'button';
        a.addEventListener('click', fn);
        return a;
    }
    _setButtonTitle(button, title) {
        if (!this._map)
            return;
        const str = this._map._getUIString(`NavigationControl.${ title }`);
        button.setAttribute('aria-label', str);
        if (button.firstElementChild)
            button.firstElementChild.setAttribute('title', str);
    }
}
class MouseRotateWrapper {
    constructor(map, element, pitch = false) {
        this._clickTolerance = 10;
        this.element = element;
        this.mouseRotate = new MouseRotateHandler({ clickTolerance: map.dragRotate._mouseRotate._clickTolerance });
        this.map = map;
        if (pitch)
            this.mousePitch = new MousePitchHandler({ clickTolerance: map.dragRotate._mousePitch._clickTolerance });
        bindAll([
            'mousedown',
            'mousemove',
            'mouseup',
            'touchstart',
            'touchmove',
            'touchend',
            'reset'
        ], this);
        // $FlowFixMe[method-unbinding]
        element.addEventListener('mousedown', this.mousedown);
        // $FlowFixMe[method-unbinding]
        element.addEventListener('touchstart', this.touchstart, { passive: false });
        // $FlowFixMe[method-unbinding]
        element.addEventListener('touchmove', this.touchmove);
        // $FlowFixMe[method-unbinding]
        element.addEventListener('touchend', this.touchend);
        // $FlowFixMe[method-unbinding]
        element.addEventListener('touchcancel', this.reset);
    }
    down(e, point) {
        this.mouseRotate.mousedown(e, point);
        if (this.mousePitch)
            this.mousePitch.mousedown(e, point);
        disableDrag();
    }
    move(e, point) {
        const map = this.map;
        const r = this.mouseRotate.mousemoveWindow(e, point);
        const delta = r && r.bearingDelta;
        if (delta)
            map.setBearing(map.getBearing() + delta);
        if (this.mousePitch) {
            const p = this.mousePitch.mousemoveWindow(e, point);
            const delta = p && p.pitchDelta;
            if (delta)
                map.setPitch(map.getPitch() + delta);
        }
    }
    off() {
        const element = this.element;
        // $FlowFixMe[method-unbinding]
        element.removeEventListener('mousedown', this.mousedown);
        // $FlowFixMe[method-unbinding]
        element.removeEventListener('touchstart', this.touchstart, { passive: false });
        // $FlowFixMe[method-unbinding]
        element.removeEventListener('touchmove', this.touchmove);
        // $FlowFixMe[method-unbinding]
        element.removeEventListener('touchend', this.touchend);
        // $FlowFixMe[method-unbinding]
        element.removeEventListener('touchcancel', this.reset);
        this.offTemp();
    }
    offTemp() {
        enableDrag();
        // $FlowFixMe[method-unbinding]
        window$1.removeEventListener('mousemove', this.mousemove);
        // $FlowFixMe[method-unbinding]
        window$1.removeEventListener('mouseup', this.mouseup);
    }
    mousedown(e) {
        this.down(extend$1({}, e, {
            ctrlKey: true,
            preventDefault: () => e.preventDefault()
        }), mousePos(this.element, e));
        // $FlowFixMe[method-unbinding]
        window$1.addEventListener('mousemove', this.mousemove);
        // $FlowFixMe[method-unbinding]
        window$1.addEventListener('mouseup', this.mouseup);
    }
    mousemove(e) {
        this.move(e, mousePos(this.element, e));
    }
    mouseup(e) {
        this.mouseRotate.mouseupWindow(e);
        if (this.mousePitch)
            this.mousePitch.mouseupWindow(e);
        this.offTemp();
    }
    touchstart(e) {
        if (e.targetTouches.length !== 1) {
            this.reset();
        } else {
            this._startPos = this._lastPos = touchPos(this.element, e.targetTouches)[0];
            this.down({
                type: 'mousedown',
                button: 0,
                ctrlKey: true,
                preventDefault: () => e.preventDefault()
            }, this._startPos);
        }
    }
    touchmove(e) {
        if (e.targetTouches.length !== 1) {
            this.reset();
        } else {
            this._lastPos = touchPos(this.element, e.targetTouches)[0];
            this.move({ preventDefault: () => e.preventDefault() }, this._lastPos);
        }
    }
    touchend(e) {
        if (e.targetTouches.length === 0 && this._startPos && this._lastPos && this._startPos.dist(this._lastPos) < this._clickTolerance) {
            this.element.click();
        }
        this.reset();
    }
    reset() {
        this.mouseRotate.reset();
        if (this.mousePitch)
            this.mousePitch.reset();
        delete this._startPos;
        delete this._lastPos;
        this.offTemp();
    }
}

//      
const defaultOptions$1 = {
    positionOptions: {
        enableHighAccuracy: false,
        maximumAge: 0,
        timeout: 6000    /* 6 sec */
    },
    fitBoundsOptions: { maxZoom: 15 },
    trackUserLocation: false,
    showAccuracyCircle: true,
    showUserLocation: true,
    showUserHeading: false
};
/**
 * A `GeolocateControl` control provides a button that uses the browser's geolocation
 * API to locate the user on the map.
 * Add this control to a map using {@link Map#addControl}.
 *
 * Not all browsers support geolocation,
 * and some users may disable the feature. Geolocation support for modern
 * browsers including Chrome requires sites to be served over HTTPS. If
 * geolocation support is not available, the GeolocateControl will show
 * as disabled.
 *
 * The [zoom level](https://docs.mapbox.com/help/glossary/zoom-level/) applied depends on the accuracy of the geolocation provided by the device.
 *
 * The GeolocateControl has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three interaction states:
 * * active - The map's camera automatically updates as the user's location changes, keeping the location dot in the center. This is the initial state, and the state upon clicking the `GeolocateControl` button.
 * * passive - The user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement.
 * * disabled - Occurs if geolocation is not available, disabled, or denied.
 *
 * These interaction states can't be controlled programmatically. Instead, they are set based on user interactions.
 *
 * @implements {IControl}
 * @param {Object} [options]
 * @param {Object} [options.positionOptions={enableHighAccuracy: false, timeout: 6000}] A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object.
 * @param {Object} [options.fitBoundsOptions={maxZoom: 15}] A {@link 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.
 * @param {Object} [options.trackUserLocation=false] If `true` the GeolocateControl becomes a toggle button and when active the map will receive updates to the user's location as it changes.
 * @param {Object} [options.showAccuracyCircle=true] By default, if `showUserLocation` is `true`, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user's location. Set to `false` to disable. Always disabled when `showUserLocation` is `false`.
 * @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.
 * @param {Object} [options.showUserHeading=false] If `true` an arrow will be drawn next to the user location dot indicating the device's heading. This only has affect when `trackUserLocation` is `true`.
 * @param {Object} [options.geolocation=window.navigator.geolocation] `window.navigator.geolocation` by default; you can provide an object with the same shape to customize geolocation handling.
 *
 * @example
 * map.addControl(new mapboxgl.GeolocateControl({
 *     positionOptions: {
 *         enableHighAccuracy: true
 *     },
 *     trackUserLocation: true,
 *     showUserHeading: true
 * }));
 * @see [Example: Locate the user](https://www.mapbox.com/mapbox-gl-js/example/locate-user/)
 */
class GeolocateControl extends Evented {
    // set to true once the control has been setup
    constructor(options) {
        super();
        const geolocation = window$1.navigator.geolocation;
        this.options = extend$1({ geolocation }, defaultOptions$1, options);
        bindAll([
            '_onSuccess',
            '_onError',
            '_onZoom',
            '_finish',
            '_setupUI',
            '_updateCamera',
            '_updateMarker',
            '_updateMarkerRotation',
            '_onDeviceOrientation'
        ], this);
        // $FlowFixMe[method-unbinding]
        this._updateMarkerRotationThrottled = throttle(this._updateMarkerRotation, 20);
        this._numberOfWatches = 0;
    }
    onAdd(map) {
        this._map = map;
        this._container = create$a('div', `mapboxgl-ctrl mapboxgl-ctrl-group`);
        // $FlowFixMe[method-unbinding]
        this._checkGeolocationSupport(this._setupUI);
        return this._container;
    }
    onRemove() {
        // clear the geolocation watch if exists
        if (this._geolocationWatchID !== undefined) {
            this.options.geolocation.clearWatch(this._geolocationWatchID);
            this._geolocationWatchID = undefined;
        }
        // clear the markers from the map
        if (this.options.showUserLocation && this._userLocationDotMarker) {
            this._userLocationDotMarker.remove();
        }
        if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {
            this._accuracyCircleMarker.remove();
        }
        this._container.remove();
        // $FlowFixMe[method-unbinding]
        this._map.off('zoom', this._onZoom);
        this._map = undefined;
        this._numberOfWatches = 0;
        this._noTimeout = false;
    }
    _checkGeolocationSupport(callback) {
        const updateSupport = (supported = !!this.options.geolocation) => {
            this._supportsGeolocation = supported;
            callback(supported);
        };
        if (this._supportsGeolocation !== undefined) {
            callback(this._supportsGeolocation);
        } else if (window$1.navigator.permissions !== undefined) {
            // navigator.permissions has incomplete browser support http://caniuse.com/#feat=permissions-api
            // Test for the case where a browser disables Geolocation because of an insecure origin;
            // in some environments like iOS16 WebView, permissions reject queries but still support geolocation
            window$1.navigator.permissions.query({ name: 'geolocation' }).then(p => updateSupport(p.state !== 'denied')).catch(() => updateSupport());
        } else {
            updateSupport();
        }
    }
    /**
     * Check if the Geolocation API Position is outside the map's maxbounds.
     *
     * @param {Position} position the Geolocation API Position
     * @returns {boolean} Returns `true` if position is outside the map's maxbounds, otherwise returns `false`.
     * @private
     */
    _isOutOfMapMaxBounds(position) {
        const bounds = this._map.getMaxBounds();
        const coordinates = position.coords;
        return !!bounds && (coordinates.longitude < bounds.getWest() || coordinates.longitude > bounds.getEast() || coordinates.latitude < bounds.getSouth() || coordinates.latitude > bounds.getNorth());
    }
    _setErrorState() {
        switch (this._watchState) {
        case 'WAITING_ACTIVE':
            this._watchState = 'ACTIVE_ERROR';
            this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');
            this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');
            break;
        case 'ACTIVE_LOCK':
            this._watchState = 'ACTIVE_ERROR';
            this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');
            this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');
            this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
            // turn marker grey
            break;
        case 'BACKGROUND':
            this._watchState = 'BACKGROUND_ERROR';
            this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');
            this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');
            this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
            // turn marker grey
            break;
        }
    }
    /**
     * When the Geolocation API returns a new location, update the GeolocateControl.
     *
     * @param {Position} position the Geolocation API Position
     * @private
     */
    _onSuccess(position) {
        if (!this._map) {
            // control has since been removed
            return;
        }
        if (this._isOutOfMapMaxBounds(position)) {
            this._setErrorState();
            this.fire(new Event('outofmaxbounds', position));
            this._updateMarker();
            this._finish();
            return;
        }
        if (this.options.trackUserLocation) {
            // keep a record of the position so that if the state is BACKGROUND and the user
            // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for
            // watchPosition to trigger _onSuccess
            this._lastKnownPosition = position;
            switch (this._watchState) {
            case 'WAITING_ACTIVE':
            case 'ACTIVE_LOCK':
            case 'ACTIVE_ERROR':
                this._watchState = 'ACTIVE_LOCK';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');
                break;
            case 'BACKGROUND':
            case 'BACKGROUND_ERROR':
                this._watchState = 'BACKGROUND';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');
                break;
            }
        }
        // if showUserLocation and the watch state isn't off then update the marker location
        if (this.options.showUserLocation && this._watchState !== 'OFF') {
            this._updateMarker(position);
        }
        // if in normal mode (not watch mode), or if in watch mode and the state is active watch
        // then update the camera
        if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') {
            this._updateCamera(position);
        }
        if (this.options.showUserLocation) {
            this._userLocationDotMarker.removeClassName('mapboxgl-user-location-dot-stale');
        }
        this.fire(new Event('geolocate', position));
        this._finish();
    }
    /**
     * Update the camera location to center on the current position
     *
     * @param {Position} position the Geolocation API Position
     * @private
     */
    _updateCamera(position) {
        const center = new LngLat$1(position.coords.longitude, position.coords.latitude);
        const radius = position.coords.accuracy;
        const bearing = this._map.getBearing();
        const options = extend$1({ bearing }, this.options.fitBoundsOptions);
        this._map.fitBounds(center.toBounds(radius), options, {
            geolocateSource: true    // tag this camera change so it won't cause the control to change to background state
        });
    }
    /**
     * Update the user location dot Marker to the current position
     *
     * @param {Position} [position] the Geolocation API Position
     * @private
     */
    _updateMarker(position) {
        if (position) {
            const center = new LngLat$1(position.coords.longitude, position.coords.latitude);
            this._accuracyCircleMarker.setLngLat(center).addTo(this._map);
            this._userLocationDotMarker.setLngLat(center).addTo(this._map);
            this._accuracy = position.coords.accuracy;
            if (this.options.showUserLocation && this.options.showAccuracyCircle) {
                this._updateCircleRadius();
            }
        } else {
            this._userLocationDotMarker.remove();
            this._accuracyCircleMarker.remove();
        }
    }
    _updateCircleRadius() {
        const map = this._map;
        const tr = map.transform;
        const pixelsPerMeter = mercatorZfromAltitude(1, tr._center.lat) * tr.worldSize;
        const circleDiameter = Math.ceil(2 * this._accuracy * pixelsPerMeter);
        this._circleElement.style.width = `${ circleDiameter }px`;
        this._circleElement.style.height = `${ circleDiameter }px`;
    }
    _onZoom() {
        if (this.options.showUserLocation && this.options.showAccuracyCircle) {
            this._updateCircleRadius();
        }
    }
    /**
     * Update the user location dot Marker rotation to the current heading
     *
     * @private
     */
    _updateMarkerRotation() {
        if (this._userLocationDotMarker && typeof this._heading === 'number') {
            this._userLocationDotMarker.setRotation(this._heading);
            this._userLocationDotMarker.addClassName('mapboxgl-user-location-show-heading');
        } else {
            this._userLocationDotMarker.removeClassName('mapboxgl-user-location-show-heading');
            this._userLocationDotMarker.setRotation(0);
        }
    }
    _onError(error) {
        if (!this._map) {
            // control has since been removed
            return;
        }
        if (this.options.trackUserLocation) {
            if (error.code === 1) {
                // PERMISSION_DENIED
                this._watchState = 'OFF';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');
                this._geolocateButton.disabled = true;
                const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');
                this._geolocateButton.setAttribute('aria-label', title);
                if (this._geolocateButton.firstElementChild)
                    this._geolocateButton.firstElementChild.setAttribute('title', title);
                if (this._geolocationWatchID !== undefined) {
                    this._clearWatch();
                }
            } else if (error.code === 3 && this._noTimeout) {
                // this represents a forced error state
                // this was triggered to force immediate geolocation when a watch is already present
                // see https://github.com/mapbox/mapbox-gl-js/issues/8214
                // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position
                return;
            } else {
                this._setErrorState();
            }
        }
        if (this._watchState !== 'OFF' && this.options.showUserLocation) {
            this._userLocationDotMarker.addClassName('mapboxgl-user-location-dot-stale');
        }
        this.fire(new Event('error', error));
        this._finish();
    }
    _finish() {
        if (this._timeoutId) {
            clearTimeout(this._timeoutId);
        }
        this._timeoutId = undefined;
    }
    _setupUI(supported) {
        if (this._map === undefined) {
            // This control was removed from the map before geolocation
            // support was determined.
            return;
        }
        this._container.addEventListener('contextmenu', e => e.preventDefault());
        this._geolocateButton = create$a('button', `mapboxgl-ctrl-geolocate`, this._container);
        create$a('span', `mapboxgl-ctrl-icon`, this._geolocateButton).setAttribute('aria-hidden', 'true');
        this._geolocateButton.type = 'button';
        if (supported === false) {
            warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.');
            const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');
            this._geolocateButton.disabled = true;
            this._geolocateButton.setAttribute('aria-label', title);
            if (this._geolocateButton.firstElementChild)
                this._geolocateButton.firstElementChild.setAttribute('title', title);
        } else {
            const title = this._map._getUIString('GeolocateControl.FindMyLocation');
            this._geolocateButton.setAttribute('aria-label', title);
            if (this._geolocateButton.firstElementChild)
                this._geolocateButton.firstElementChild.setAttribute('title', title);
        }
        if (this.options.trackUserLocation) {
            this._geolocateButton.setAttribute('aria-pressed', 'false');
            this._watchState = 'OFF';
        }
        // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map
        if (this.options.showUserLocation) {
            this._dotElement = create$a('div', 'mapboxgl-user-location');
            this._dotElement.appendChild(create$a('div', 'mapboxgl-user-location-dot'));
            this._dotElement.appendChild(create$a('div', 'mapboxgl-user-location-heading'));
            this._userLocationDotMarker = new Marker({
                element: this._dotElement,
                rotationAlignment: 'map',
                pitchAlignment: 'map'
            });
            this._circleElement = create$a('div', 'mapboxgl-user-location-accuracy-circle');
            this._accuracyCircleMarker = new Marker({
                element: this._circleElement,
                pitchAlignment: 'map'
            });
            if (this.options.trackUserLocation)
                this._watchState = 'OFF';
            // $FlowFixMe[method-unbinding]
            this._map.on('zoom', this._onZoom);
        }
        // $FlowFixMe[method-unbinding]
        this._geolocateButton.addEventListener('click', this.trigger.bind(this));
        this._setup = true;
        // when the camera is changed (and it's not as a result of the Geolocation Control) change
        // the watch mode to background watch, so that the marker is updated but not the camera.
        if (this.options.trackUserLocation) {
            this._map.on('movestart', event => {
                const fromResize = event.originalEvent && event.originalEvent.type === 'resize';
                if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) {
                    this._watchState = 'BACKGROUND';
                    this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');
                    this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');
                    this.fire(new Event('trackuserlocationend'));
                }
            });
        }
    }
    /**
    * Programmatically request and move the map to the user's location.
    *
    * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`.
    * Called on a deviceorientation event.
    *
    * @param deviceOrientationEvent {DeviceOrientationEvent}
    * @private
    * @example
    * // Initialize the GeolocateControl.
    * var geolocate = new mapboxgl.GeolocateControl({
    *  positionOptions: {
    *    enableHighAccuracy: true
    *  },
    *  trackUserLocation: true
    * });
    * // Add the control to the map.
    * map.addControl(geolocate);
    * map.on('load', function() {
    *   geolocate.trigger();
    * });
    */
    _onDeviceOrientation(deviceOrientationEvent) {
        // absolute is true if the orientation data is provided as the difference between the Earth's coordinate frame and the device's coordinate frame, or false if the orientation data is being provided in reference to some arbitrary, device-determined coordinate frame.
        if (this._userLocationDotMarker) {
            if (deviceOrientationEvent.webkitCompassHeading) {
                // Safari
                this._heading = deviceOrientationEvent.webkitCompassHeading;
            } else if (deviceOrientationEvent.absolute === true) {
                // non-Safari alpha increases counter clockwise around the z axis
                this._heading = deviceOrientationEvent.alpha * -1;
            }
            this._updateMarkerRotationThrottled();
        }
    }
    /**
     * Trigger a geolocation event.
     *
     * @example
     * // Initialize the geolocate control.
     * const geolocate = new mapboxgl.GeolocateControl({
     *     positionOptions: {
     *         enableHighAccuracy: true
     *     },
     *     trackUserLocation: true
     * });
     * // Add the control to the map.
     * map.addControl(geolocate);
     * map.on('load', () => {
     *     geolocate.trigger();
     * });
     * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`.
     */
    trigger() {
        if (!this._setup) {
            warnOnce('Geolocate control triggered before added to a map');
            return false;
        }
        if (this.options.trackUserLocation) {
            // update watchState and do any outgoing state cleanup
            switch (this._watchState) {
            case 'OFF':
                // turn on the GeolocateControl
                this._watchState = 'WAITING_ACTIVE';
                this.fire(new Event('trackuserlocationstart'));
                break;
            case 'WAITING_ACTIVE':
            case 'ACTIVE_LOCK':
            case 'ACTIVE_ERROR':
            case 'BACKGROUND_ERROR':
                // turn off the Geolocate Control
                this._numberOfWatches--;
                this._noTimeout = false;
                this._watchState = 'OFF';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');
                this.fire(new Event('trackuserlocationend'));
                break;
            case 'BACKGROUND':
                this._watchState = 'ACTIVE_LOCK';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');
                // set camera to last known location
                if (this._lastKnownPosition)
                    this._updateCamera(this._lastKnownPosition);
                this.fire(new Event('trackuserlocationstart'));
                break;
            }
            // incoming state setup
            switch (this._watchState) {
            case 'WAITING_ACTIVE':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');
                break;
            case 'ACTIVE_LOCK':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');
                break;
            case 'ACTIVE_ERROR':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');
                break;
            case 'BACKGROUND':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');
                break;
            case 'BACKGROUND_ERROR':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');
                break;
            }
            // manage geolocation.watchPosition / geolocation.clearWatch
            if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) {
                // clear watchPosition as we've changed to an OFF state
                this._clearWatch();
            } else if (this._geolocationWatchID === undefined) {
                // enable watchPosition since watchState is not OFF and there is no watchPosition already running
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.setAttribute('aria-pressed', 'true');
                this._numberOfWatches++;
                let positionOptions;
                if (this._numberOfWatches > 1) {
                    positionOptions = {
                        maximumAge: 600000,
                        timeout: 0
                    };
                    this._noTimeout = true;
                } else {
                    positionOptions = this.options.positionOptions;
                    this._noTimeout = false;
                }
                this._geolocationWatchID = this.options.geolocation.watchPosition(this._onSuccess, this._onError, positionOptions);
                if (this.options.showUserHeading) {
                    this._addDeviceOrientationListener();
                }
            }
        } else {
            // $FlowFixMe[method-unbinding]
            this.options.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions);
            // This timeout ensures that we still call finish() even if
            // the user declines to share their location in Firefox
            // $FlowFixMe[method-unbinding]
            this._timeoutId = setTimeout(this._finish, 10000    /* 10sec */);
        }
        return true;
    }
    _addDeviceOrientationListener() {
        const addListener = () => {
            if ('ondeviceorientationabsolute' in window$1) {
                // $FlowFixMe[method-unbinding]
                window$1.addEventListener('deviceorientationabsolute', this._onDeviceOrientation);
            } else {
                // $FlowFixMe[method-unbinding]
                window$1.addEventListener('deviceorientation', this._onDeviceOrientation);
            }
        };
        if (typeof window$1.DeviceMotionEvent !== 'undefined' && typeof window$1.DeviceMotionEvent.requestPermission === 'function') {
            // $FlowFixMe
            DeviceOrientationEvent.requestPermission().then(response => {
                if (response === 'granted') {
                    addListener();
                }
            }).catch(console.error);
        } else {
            addListener();
        }
    }
    _clearWatch() {
        this.options.geolocation.clearWatch(this._geolocationWatchID);
        // $FlowFixMe[method-unbinding]
        window$1.removeEventListener('deviceorientation', this._onDeviceOrientation);
        // $FlowFixMe[method-unbinding]
        window$1.removeEventListener('deviceorientationabsolute', this._onDeviceOrientation);
        this._geolocationWatchID = undefined;
        this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
        this._geolocateButton.setAttribute('aria-pressed', 'false');
        if (this.options.showUserLocation) {
            this._updateMarker(null);
        }
    }
}
                                    /**
 * Fired on each Geolocation API position update that returned as success.
 *
 * @event geolocate
 * @memberof GeolocateControl
 * @instance
 * @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).
 * @example
 * // Initialize the GeolocateControl.
 * const geolocate = new mapboxgl.GeolocateControl({
 *     positionOptions: {
 *         enableHighAccuracy: true
 *     },
 *     trackUserLocation: true
 * });
 * // Add the control to the map.
 * map.addControl(geolocate);
 * // Set an event listener that fires
 * // when a geolocate event occurs.
 * geolocate.on('geolocate', () => {
 *     console.log('A geolocate event has occurred.');
 * });
 */
                                    /**
 * Fired on each Geolocation API position update that returned as an error.
 *
 * @event error
 * @memberof GeolocateControl
 * @instance
 * @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).
 * @example
 * // Initialize the GeolocateControl.
 * const geolocate = new mapboxgl.GeolocateControl({
 *     positionOptions: {
 *         enableHighAccuracy: true
 *     },
 *     trackUserLocation: true
 * });
 * // Add the control to the map.
 * map.addControl(geolocate);
 * // Set an event listener that fires
 * // when an error event occurs.
 * geolocate.on('error', () => {
 *     console.log('An error event has occurred.');
 * });
 */
                                    /**
 * Fired on each Geolocation API position update that returned as success but user position is out of map `maxBounds`.
 *
 * @event outofmaxbounds
 * @memberof GeolocateControl
 * @instance
 * @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).
 * @example
 * // Initialize the GeolocateControl.
 * const geolocate = new mapboxgl.GeolocateControl({
 *     positionOptions: {
 *         enableHighAccuracy: true
 *     },
 *     trackUserLocation: true
 * });
 * // Add the control to the map.
 * map.addControl(geolocate);
 * // Set an event listener that fires
 * // when an outofmaxbounds event occurs.
 * geolocate.on('outofmaxbounds', () => {
 *     console.log('An outofmaxbounds event has occurred.');
 * });
 */
                                    /**
 * Fired when the GeolocateControl changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or when 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).
 *
 * @event trackuserlocationstart
 * @memberof GeolocateControl
 * @instance
 * @example
 * // Initialize the GeolocateControl.
 * const geolocate = new mapboxgl.GeolocateControl({
 *     positionOptions: {
 *         enableHighAccuracy: true
 *     },
 *     trackUserLocation: true
 * });
 * // Add the control to the map.
 * map.addControl(geolocate);
 * // Set an event listener that fires
 * // when a trackuserlocationstart event occurs.
 * geolocate.on('trackuserlocationstart', () => {
 *     console.log('A trackuserlocationstart event has occurred.');
 * });
 */
                                    /**
 * Fired when the GeolocateControl changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not.
 *
 * @event trackuserlocationend
 * @memberof GeolocateControl
 * @instance
 * @example
 * // Initialize the GeolocateControl.
 * const geolocate = new mapboxgl.GeolocateControl({
 *     positionOptions: {
 *         enableHighAccuracy: true
 *     },
 *     trackUserLocation: true
 * });
 * // Add the control to the map.
 * map.addControl(geolocate);
 * // Set an event listener that fires
 * // when a trackuserlocationend event occurs.
 * geolocate.on('trackuserlocationend', () => {
 *     console.log('A trackuserlocationend event has occurred.');
 * });
 */

//      
const defaultOptions = {
    maxWidth: 100,
    unit: 'metric'
};
const unitAbbr = {
    kilometer: 'km',
    meter: 'm',
    mile: 'mi',
    foot: 'ft',
    'nautical-mile': 'nm'
};
/**
 * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground.
 * Add this control to a map using {@link Map#addControl}.
 *
 * @implements {IControl}
 * @param {Object} [options]
 * @param {number} [options.maxWidth='100'] The maximum length of the scale control in pixels.
 * @param {string} [options.unit='metric'] Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).
 * @example
 * const scale = new mapboxgl.ScaleControl({
 *     maxWidth: 80,
 *     unit: 'imperial'
 * });
 * map.addControl(scale);
 *
 * scale.setUnit('metric');
 */
class ScaleControl {
    constructor(options) {
        this.options = extend$1({}, defaultOptions, options);
        // Some old browsers (e.g., Safari < 14.1) don't support the "unit" style in NumberFormat.
        // This is a workaround to display the scale without proper internationalization support.
        this._isNumberFormatSupported = isNumberFormatSupported();
        bindAll([
            '_update',
            '_setScale',
            'setUnit'
        ], this);
    }
    getDefaultPosition() {
        return 'bottom-left';
    }
    _update() {
        // A horizontal scale is imagined to be present at center of the map
        // container with maximum length (Default) as 100px.
        // Using spherical law of cosines approximation, the real distance is
        // found between the two coordinates.
        const maxWidth = this.options.maxWidth || 100;
        const map = this._map;
        const y = map._containerHeight / 2;
        const x = map._containerWidth / 2 - maxWidth / 2;
        const left = map.unproject([
            x,
            y
        ]);
        const right = map.unproject([
            x + maxWidth,
            y
        ]);
        const maxMeters = left.distanceTo(right);
        // The real distance corresponding to 100px scale length is rounded off to
        // near pretty number and the scale length for the same is found out.
        // Default unit of the scale is based on User's locale.
        if (this.options.unit === 'imperial') {
            const maxFeet = 3.2808 * maxMeters;
            if (maxFeet > 5280) {
                const maxMiles = maxFeet / 5280;
                this._setScale(maxWidth, maxMiles, 'mile');
            } else {
                this._setScale(maxWidth, maxFeet, 'foot');
            }
        } else if (this.options.unit === 'nautical') {
            const maxNauticals = maxMeters / 1852;
            this._setScale(maxWidth, maxNauticals, 'nautical-mile');
        } else if (maxMeters >= 1000) {
            this._setScale(maxWidth, maxMeters / 1000, 'kilometer');
        } else {
            this._setScale(maxWidth, maxMeters, 'meter');
        }
    }
    _setScale(maxWidth, maxDistance, unit) {
        this._map._requestDomTask(() => {
            const distance = getRoundNum(maxDistance);
            const ratio = distance / maxDistance;
            if (this._isNumberFormatSupported && unit !== 'nautical-mile') {
                // $FlowFixMe[incompatible-call] — flow v0.190.1 doesn't support optional `locales` argument and `unit` style option
                this._container.innerHTML = new Intl.NumberFormat(this._language, {
                    style: 'unit',
                    unitDisplay: 'short',
                    unit
                }).format(distance);
            } else {
                this._container.innerHTML = `${ distance }&nbsp;${ unitAbbr[unit] }`;
            }
            this._container.style.width = `${ maxWidth * ratio }px`;
        });
    }
    onAdd(map) {
        this._map = map;
        this._language = map.getLanguage();
        this._container = create$a('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', map.getContainer());
        this._container.dir = 'auto';
        // $FlowFixMe[method-unbinding]
        this._map.on('move', this._update);
        this._update();
        return this._container;
    }
    onRemove() {
        this._container.remove();
        // $FlowFixMe[method-unbinding]
        this._map.off('move', this._update);
        this._map = undefined;
    }
    _setLanguage(language) {
        this._language = language;
        this._update();
    }
    /**
     * Set the scale's unit of the distance.
     *
     * @param {'imperial' | 'metric' | 'nautical'} unit Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).
     */
    setUnit(unit) {
        this.options.unit = unit;
        this._update();
    }
}
function isNumberFormatSupported() {
    try {
        // $FlowIgnore
        new Intl.NumberFormat('en', {
            style: 'unit',
            unitDisplay: 'short',
            unit: 'meter'
        });
        return true;
    } catch (_) {
        return false;
    }
}
function getDecimalRoundNum(d) {
    const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));
    return Math.round(d * multiplier) / multiplier;
}
function getRoundNum(num) {
    const pow10 = Math.pow(10, `${ Math.floor(num) }`.length - 1);
    let d = num / pow10;
    d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : d >= 1 ? 1 : getDecimalRoundNum(d);
    return pow10 * d;
}

//      
/**
 * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. See the `requestFullScreen` [compatibility table](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#browser_compatibility) for supported browsers.
 * Add this control to a map using {@link Map#addControl}.
 *
 * @implements {IControl}
 * @param {Object} [options]
 * @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.
 *
 * @example
 * map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));
 * @see [Example: View a fullscreen map](https://www.mapbox.com/mapbox-gl-js/example/fullscreen/)
 */
class FullscreenControl {
    constructor(options) {
        this._fullscreen = false;
        if (options && options.container) {
            if (options.container instanceof window$1.HTMLElement) {
                this._container = options.container;
            } else {
                warnOnce('Full screen control \'container\' must be a DOM element.');
            }
        }
        bindAll([
            '_onClickFullscreen',
            '_changeIcon'
        ], this);
        if ('onfullscreenchange' in window$1.document) {
            this._fullscreenchange = 'fullscreenchange';
        } else if ('onwebkitfullscreenchange' in window$1.document) {
            this._fullscreenchange = 'webkitfullscreenchange';
        }
    }
    onAdd(map) {
        this._map = map;
        if (!this._container)
            this._container = this._map.getContainer();
        this._controlContainer = create$a('div', `mapboxgl-ctrl mapboxgl-ctrl-group`);
        if (this._checkFullscreenSupport()) {
            this._setupUI();
        } else {
            this._controlContainer.style.display = 'none';
            warnOnce('This device does not support fullscreen mode.');
        }
        return this._controlContainer;
    }
    onRemove() {
        this._controlContainer.remove();
        this._map = null;
        // $FlowFixMe[method-unbinding]
        window$1.document.removeEventListener(this._fullscreenchange, this._changeIcon);
    }
    _checkFullscreenSupport() {
        return !!(window$1.document.fullscreenEnabled || window$1.document.webkitFullscreenEnabled);
    }
    _setupUI() {
        const button = this._fullscreenButton = create$a('button', `mapboxgl-ctrl-fullscreen`, this._controlContainer);
        create$a('span', `mapboxgl-ctrl-icon`, button).setAttribute('aria-hidden', 'true');
        button.type = 'button';
        this._updateTitle();
        // $FlowFixMe[method-unbinding]
        this._fullscreenButton.addEventListener('click', this._onClickFullscreen);
        // $FlowFixMe[method-unbinding]
        window$1.document.addEventListener(this._fullscreenchange, this._changeIcon);
    }
    _updateTitle() {
        const title = this._getTitle();
        this._fullscreenButton.setAttribute('aria-label', title);
        if (this._fullscreenButton.firstElementChild)
            this._fullscreenButton.firstElementChild.setAttribute('title', title);
    }
    _getTitle() {
        return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter');
    }
    _isFullscreen() {
        return this._fullscreen;
    }
    _changeIcon() {
        const fullscreenElement = window$1.document.fullscreenElement || window$1.document.webkitFullscreenElement;
        if (fullscreenElement === this._container !== this._fullscreen) {
            this._fullscreen = !this._fullscreen;
            this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-shrink`);
            this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-fullscreen`);
            this._updateTitle();
        }
    }
    _onClickFullscreen() {
        if (this._isFullscreen()) {
            if (window$1.document.exitFullscreen) {
                window$1.document.exitFullscreen();
            } else if (window$1.document.webkitCancelFullScreen) {
                window$1.document.webkitCancelFullScreen();
            }    // $FlowFixMe[method-unbinding]
        } else if (this._container.requestFullscreen) {
            this._container.requestFullscreen();
        } else if (this._container.webkitRequestFullscreen) {
            this._container.webkitRequestFullscreen();
        }
    }
}

//      
window$1.performance;

//      
const exported = {
    version,
    supported,
    setRTLTextPlugin,
    getRTLTextPluginStatus,
    Map: Map$1,
    NavigationControl,
    GeolocateControl,
    AttributionControl,
    ScaleControl,
    FullscreenControl,
    Popup,
    Marker,
    Style,
    LngLat: LngLat$1,
    LngLatBounds,
    Point: Point$2,
    MercatorCoordinate,
    FreeCameraOptions,
    Evented,
    config,
    /**
     * Initializes resources like WebWorkers that can be shared across maps to lower load
     * times in some situations. [`mapboxgl.workerUrl`](https://docs.mapbox.com/mapbox-gl-js/api/properties/#workerurl)
     * and [`mapboxgl.workerCount`](https://docs.mapbox.com/mapbox-gl-js/api/properties/#workercount), if being
     * used, must be set before `prewarm()` is called to have an effect.
     *
     * By default, the lifecycle of these resources is managed automatically, and they are
     * lazily initialized when a `Map` is first created. Invoking `prewarm()` creates these
     * resources ahead of time and ensures they are not cleared when the last `Map`
     * is removed from the page. This allows them to be re-used by new `Map` instances that
     * are created later. They can be manually cleared by calling
     * [`mapboxgl.clearPrewarmedResources()`](https://docs.mapbox.com/mapbox-gl-js/api/properties/#clearprewarmedresources).
     * This is only necessary if your web page remains active but stops using maps altogether.
     * `prewarm()` is idempotent and has guards against being executed multiple times,
     * and any resources allocated by `prewarm()` are created synchronously.
     *
     * This is primarily useful when using Mapbox GL JS maps in a single page app,
     * in which a user navigates between various views, resulting in
     * constant creation and destruction of `Map` instances.
     *
     * @function prewarm
     * @example
     * mapboxgl.prewarm();
     */
    prewarm,
    /**
     * Clears up resources that have previously been created by [`mapboxgl.prewarm()](https://docs.mapbox.com/mapbox-gl-js/api/properties/#prewarm)`.
     * Note that this is typically not necessary. You should only call this function
     * if you expect the user of your app to not return to a Map view at any point
     * in your application.
     *
     * @function clearPrewarmedResources
     * @example
     * mapboxgl.clearPrewarmedResources();
     */
    clearPrewarmedResources,
    /**
     * Gets and sets the map's [access token](https://www.mapbox.com/help/define-access-token/).
     *
     * @var {string} accessToken
     * @returns {string} The currently set access token.
     * @example
     * mapboxgl.accessToken = myAccessToken;
     * @see [Example: Display a map](https://www.mapbox.com/mapbox-gl-js/example/simple-map/)
     */
    get accessToken() {
        return config.ACCESS_TOKEN;
    },
    set accessToken(token) {
        config.ACCESS_TOKEN = token;
    },
    /**
     * Gets and sets the map's default API URL for requesting tiles, styles, sprites, and glyphs.
     *
     * @var {string} baseApiUrl
     * @returns {string} The current base API URL.
     * @example
     * mapboxgl.baseApiUrl = 'https://api.mapbox.com';
     */
    get baseApiUrl() {
        return config.API_URL;
    },
    set baseApiUrl(url) {
        config.API_URL = url;
    },
    /**
     * Gets and sets the number of web workers instantiated on a page with Mapbox GL JS maps.
     * By default, it is set to 2.
     * Make sure to set this property before creating any map instances for it to have effect.
     *
     * @var {string} workerCount
     * @returns {number} Number of workers currently configured.
     * @example
     * mapboxgl.workerCount = 4;
     */
    get workerCount() {
        return WorkerPool.workerCount;
    },
    set workerCount(count) {
        WorkerPool.workerCount = count;
    },
    /**
     * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel.
     * 16 by default. There is no maximum value, but the number of images affects performance in raster-heavy maps.
     *
     * @var {string} maxParallelImageRequests
     * @returns {number} Number of parallel requests currently configured.
     * @example
     * mapboxgl.maxParallelImageRequests = 10;
     */
    get maxParallelImageRequests() {
        return config.MAX_PARALLEL_IMAGE_REQUESTS;
    },
    set maxParallelImageRequests(numRequests) {
        config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests;
    },
    /**
     * Clears browser storage used by this library. Using this method flushes the Mapbox tile
     * cache that is managed by this library. Tiles may still be cached by the browser
     * in some cases.
     *
     * This API is supported on browsers where the [`Cache` API](https://developer.mozilla.org/en-US/docs/Web/API/Cache)
     * is supported and enabled. This includes all major browsers when pages are served over
     * `https://`, except Internet Explorer and Edge Mobile.
     *
     * When called in unsupported browsers or environments (private or incognito mode), the
     * callback will be called with an error argument.
     *
     * @function clearStorage
     * @param {Function} callback Called with an error argument if there is an error.
     * @example
     * mapboxgl.clearStorage();
     */
    clearStorage(callback) {
        clearTileCache(callback);
    },
    /**
     * Provides an interface for loading mapbox-gl's WebWorker bundle from a self-hosted URL.
     * This needs to be set only once, and before any call to `new mapboxgl.Map(..)` takes place.
     * This is useful if your site needs to operate in a strict CSP (Content Security Policy) environment
     * wherein you are not allowed to load JavaScript code from a [`Blob` URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL), which is default behavior.
     *
     * See our documentation on [CSP Directives](https://docs.mapbox.com/mapbox-gl-js/api/#csp-directives) for more details.
     *
     * @var {string} workerUrl
     * @returns {string} A URL hosting a JavaScript bundle for mapbox-gl's WebWorker.
     * @example
     * <script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl-csp.js'></script>
     * <script>
     * mapboxgl.workerUrl = "https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl-csp-worker.js";
     * ...
     * </script>
     */
    workerUrl: '',
    /**
     * Provides an interface for external module bundlers such as Webpack or Rollup to package
     * mapbox-gl's WebWorker into a separate class and integrate it with the library.
     *
     * Takes precedence over `mapboxgl.workerUrl`.
     *
     * @var {Object} workerClass
     * @returns {Object | null} A class that implements the `Worker` interface.
     * @example
     * import mapboxgl from 'mapbox-gl/dist/mapbox-gl-csp.js';
     * import MapboxGLWorker from 'mapbox-gl/dist/mapbox-gl-csp-worker.js';
     *
     * mapboxgl.workerClass = MapboxGLWorker;
     */
    workerClass: null,
    /**
     * Provides an interface for loading Draco decoding library (draco_decoder_gltf.wasm v1.5.6) from a self-hosted URL.
     * This needs to be set only once, and before any call to `new mapboxgl.Map(..)` takes place.
     * This is useful if your site needs to operate in a strict CSP (Content Security Policy) environment
     * wherein you are not allowed to load JavaScript code from a [`Blob` URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL), which is default behavior.
     *
     * See our documentation on [CSP Directives](https://docs.mapbox.com/mapbox-gl-js/api/#csp-directives) for more details.
     *
     * @var {string} dracoUrl
     * @returns {string} A URL hosting Google Draco decoding library (`draco_wasm_wrapper_gltf.js` and `draco_decoder_gltf.wasm`).
     * @example
     * <script src='https://api.mapbox.com/mapbox-gl-js/v3.0.0/mapbox-gl.js'></script>
     * <script>
     * mapboxgl.dracoUrl = "https://www.gstatic.com/draco/versioned/decoders/1.5.6/draco_decoder_gltf.wasm";
     * ...
     * </script>
     */
    get dracoUrl() {
        return getDracoUrl();
    },
    set dracoUrl(url) {
        setDracoUrl(url);
    },
    /**
     * Sets the time used by Mapbox GL JS internally for all animations. Useful for generating videos from Mapbox GL JS.
     *
     * @var {number} time
     */
    setNow: exported$1.setNow,
    /**
     * Restores the internal animation timing to follow regular computer time (`performance.now()`).
     */
    restoreNow: exported$1.restoreNow
};

exports.A = Actor;
exports.D = DEMData;
exports.E = EXTENT;
exports.F = FeatureIndex;
exports.K = KDBush;
exports.O = OverscaledTileID;
exports.P = Point$2;
exports.T = Tiled3dModelBucket;
exports.V = VectorTileFeature;
exports.a = vectorTile;
exports.b = pbf;
exports.c = createStyleLayer;
exports.d = VectorTileWorkerSource;
exports.e = createExpression;
exports.f = getPerformanceMeasurement;
exports.g = getDefaultExportFromCjs;
exports.h = getJSON;
exports.i = getArrayBuffer;
exports.j = process3DTile;
exports.k = EvaluationParameters;
exports.l = load3DTile;
exports.m = getProjection;
exports.n = plugin;
exports.o = Event;
exports.p = pointGeometry;
exports.q = enforceCacheSizeLimit;
exports.r = refProperties;
exports.s = exported;
exports.t = tileToMeter;
exports.v = values;
exports.w = window$1;

}));

define(['./shared'], (function (index) { 'use strict';

//      
function stringify(obj) {
    if (typeof obj === 'number' || typeof obj === 'boolean' || typeof obj === 'string' || obj === undefined || obj === null)
        return JSON.stringify(obj);
    if (Array.isArray(obj)) {
        let str = '[';
        for (const val of obj) {
            str += `${ stringify(val) },`;
        }
        return `${ str }]`;
    }
    let str = '{';
    for (const key of Object.keys(obj).sort()) {
        str += `${ key }:${ stringify(obj[key]) },`;
    }
    return `${ str }}`;
}
function getKey(layer) {
    let key = '';
    for (const k of index.r) {
        key += `/${ stringify(layer[k]) }`;
    }
    return key;
}
/**
 * Given an array of layers, return an array of arrays of layers where all
 * layers in each group have identical layout-affecting properties. These
 * are the properties that were formerly used by explicit `ref` mechanism
 * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom',
 * 'filter', and 'layout'.
 *
 * The input is not modified. The output layers are references to the
 * input layers.
 *
 * @private
 * @param {Array<Layer>} layers
 * @param {Object} [cachedKeys] - an object to keep already calculated keys.
 * @returns {Array<Array<Layer>>}
 */
function groupByLayout(layers, cachedKeys) {
    const groups = {};
    for (let i = 0; i < layers.length; i++) {
        const k = cachedKeys && cachedKeys[layers[i].id] || getKey(layers[i]);
        // update the cache if there is one
        if (cachedKeys)
            cachedKeys[layers[i].id] = k;
        let group = groups[k];
        if (!group) {
            group = groups[k] = [];
        }
        group.push(layers[i]);
    }
    const result = [];
    for (const k in groups) {
        result.push(groups[k]);
    }
    return result;
}

//      
class StyleLayerIndex {
    constructor(layerConfigs) {
        this.keyCache = {};
        if (layerConfigs) {
            this.replace(layerConfigs);
        }
    }
    replace(layerConfigs, options) {
        this._layerConfigs = {};
        this._layers = {};
        this.update(layerConfigs, [], options);
    }
    update(layerConfigs, removedIds, options) {
        this._options = options;
        for (const layerConfig of layerConfigs) {
            this._layerConfigs[layerConfig.id] = layerConfig;
            const layer = this._layers[layerConfig.id] = index.c(layerConfig, this._options);
            layer.setScope(this.scope);
            layer.compileFilter();
            if (this.keyCache[layerConfig.id])
                delete this.keyCache[layerConfig.id];
        }
        for (const id of removedIds) {
            delete this.keyCache[id];
            delete this._layerConfigs[id];
            delete this._layers[id];
        }
        this.familiesBySource = {};
        const groups = groupByLayout(index.v(this._layerConfigs), this.keyCache);
        for (const layerConfigs of groups) {
            const layers = layerConfigs.map(layerConfig => this._layers[layerConfig.id]);
            const layer = layers[0];
            if (layer.visibility === 'none') {
                continue;
            }
            const sourceId = layer.source || '';
            let sourceGroup = this.familiesBySource[sourceId];
            if (!sourceGroup) {
                sourceGroup = this.familiesBySource[sourceId] = {};
            }
            const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer';
            let sourceLayerFamilies = sourceGroup[sourceLayerId];
            if (!sourceLayerFamilies) {
                sourceLayerFamilies = sourceGroup[sourceLayerId] = [];
            }
            sourceLayerFamilies.push(layers);
        }
    }
}

//      
class RasterDEMTileWorkerSource {
    loadTile(params, callback) {
        const {uid, encoding, rawImageData, padding} = params;
        // Main thread will transfer ImageBitmap if offscreen decode with OffscreenCanvas is supported, else it will transfer an already decoded image.
        // Flow struggles to refine ImageBitmap type, likely due to the JSDom shim
        const imagePixels = index.w.ImageBitmap && rawImageData instanceof index.w.ImageBitmap ? this.getImageData(rawImageData, padding) : rawImageData;
        const dem = new index.D(uid, imagePixels, encoding, params.convertToFloat, padding < 1);
        callback(null, dem);
    }
    getImageData(imgBitmap, padding) {
        // Lazily initialize OffscreenCanvas
        if (!this.offscreenCanvas || !this.offscreenCanvasContext) {
            // Dem tiles are typically 256x256
            this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height);
            // $FlowIssue[extra-arg]: internal Flow types don't yet know about willReadFrequently
            this.offscreenCanvasContext = this.offscreenCanvas.getContext('2d', { willReadFrequently: true });
        }
        this.offscreenCanvas.width = imgBitmap.width;
        this.offscreenCanvas.height = imgBitmap.height;
        this.offscreenCanvasContext.drawImage(imgBitmap, 0, 0, imgBitmap.width, imgBitmap.height);
        // Insert or remove defined padding around the image to allow backfilling for neighboring data.
        const imgData = this.offscreenCanvasContext.getImageData(-padding, -padding, imgBitmap.width + 2 * padding, imgBitmap.height + 2 * padding);
        this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);
        return imgData;
    }
}

var geojsonRewind = rewind;
function rewind(gj, outer) {
    var type = gj && gj.type, i;
    if (type === 'FeatureCollection') {
        for (i = 0; i < gj.features.length; i++)
            rewind(gj.features[i], outer);
    } else if (type === 'GeometryCollection') {
        for (i = 0; i < gj.geometries.length; i++)
            rewind(gj.geometries[i], outer);
    } else if (type === 'Feature') {
        rewind(gj.geometry, outer);
    } else if (type === 'Polygon') {
        rewindRings(gj.coordinates, outer);
    } else if (type === 'MultiPolygon') {
        for (i = 0; i < gj.coordinates.length; i++)
            rewindRings(gj.coordinates[i], outer);
    }
    return gj;
}
function rewindRings(rings, outer) {
    if (rings.length === 0)
        return;
    rewindRing(rings[0], outer);
    for (var i = 1; i < rings.length; i++) {
        rewindRing(rings[i], !outer);
    }
}
function rewindRing(ring, dir) {
    var area = 0, err = 0;
    for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
        var k = (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]);
        var m = area + k;
        err += Math.abs(area) >= Math.abs(k) ? area - m + k : k - m + area;
        area = m;
    }
    if (area + err >= 0 !== !!dir)
        ring.reverse();
}

var rewind$1 = /*@__PURE__*/index.g(geojsonRewind);

//      
// $FlowFixMe[method-unbinding]
const toGeoJSON = index.V.prototype.toGeoJSON;
// The feature type used by geojson-vt and supercluster. Should be extracted to
// global type and used in module definitions for those two modules.
let FeatureWrapper$1 = class FeatureWrapper {
    constructor(feature) {
        this._feature = feature;
        this.extent = index.E;
        this.type = feature.type;
        this.properties = feature.tags;
        // If the feature has a top-level `id` property, copy it over, but only
        // if it can be coerced to an integer, because this wrapper is used for
        // serializing geojson feature data into vector tile PBF data, and the
        // vector tile spec only supports integer values for feature ids --
        // allowing non-integer values here results in a non-compliant PBF
        // that causes an exception when it is parsed with vector-tile-js
        if ('id' in feature && !isNaN(feature.id)) {
            this.id = parseInt(feature.id, 10);
        }
    }
    loadGeometry() {
        if (this._feature.type === 1) {
            const geometry = [];
            for (const point of this._feature.geometry) {
                geometry.push([new index.P(point[0], point[1])]);
            }
            return geometry;
        } else {
            const geometry = [];
            for (const ring of this._feature.geometry) {
                const newRing = [];
                for (const point of ring) {
                    newRing.push(new index.P(point[0], point[1]));
                }
                geometry.push(newRing);
            }
            return geometry;
        }
    }
    toGeoJSON(x, y, z) {
        return toGeoJSON.call(this, x, y, z);
    }
};
let GeoJSONWrapper$2 = class GeoJSONWrapper {
    constructor(features) {
        this.layers = { '_geojsonTileLayer': this };
        this.name = '_geojsonTileLayer';
        this.extent = index.E;
        this.length = features.length;
        this._features = features;
    }
    feature(i) {
        return new FeatureWrapper$1(this._features[i]);
    }
};

var vtPbf = {exports: {}};

var Point = index.p;
var VectorTileFeature = index.a.VectorTileFeature;
var geojson_wrapper = GeoJSONWrapper$1;
// conform to vectortile api
function GeoJSONWrapper$1(features, options) {
    this.options = options || {};
    this.features = features;
    this.length = features.length;
}
GeoJSONWrapper$1.prototype.feature = function (i) {
    return new FeatureWrapper(this.features[i], this.options.extent);
};
function FeatureWrapper(feature, extent) {
    this.id = typeof feature.id === 'number' ? feature.id : undefined;
    this.type = feature.type;
    this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry;
    this.properties = feature.tags;
    this.extent = extent || 4096;
}
FeatureWrapper.prototype.loadGeometry = function () {
    var rings = this.rawGeometry;
    this.geometry = [];
    for (var i = 0; i < rings.length; i++) {
        var ring = rings[i];
        var newRing = [];
        for (var j = 0; j < ring.length; j++) {
            newRing.push(new Point(ring[j][0], ring[j][1]));
        }
        this.geometry.push(newRing);
    }
    return this.geometry;
};
FeatureWrapper.prototype.bbox = function () {
    if (!this.geometry)
        this.loadGeometry();
    var rings = this.geometry;
    var x1 = Infinity;
    var x2 = -Infinity;
    var y1 = Infinity;
    var y2 = -Infinity;
    for (var i = 0; i < rings.length; i++) {
        var ring = rings[i];
        for (var j = 0; j < ring.length; j++) {
            var coord = ring[j];
            x1 = Math.min(x1, coord.x);
            x2 = Math.max(x2, coord.x);
            y1 = Math.min(y1, coord.y);
            y2 = Math.max(y2, coord.y);
        }
    }
    return [
        x1,
        y1,
        x2,
        y2
    ];
};
FeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON;

var Pbf = index.b;
var GeoJSONWrapper = geojson_wrapper;
vtPbf.exports = fromVectorTileJs;
vtPbf.exports.fromVectorTileJs = fromVectorTileJs;
vtPbf.exports.fromGeojsonVt = fromGeojsonVt;
vtPbf.exports.GeoJSONWrapper = GeoJSONWrapper;
/**
 * Serialize a vector-tile-js-created tile to pbf
 *
 * @param {Object} tile
 * @return {Buffer} uncompressed, pbf-serialized tile data
 */
function fromVectorTileJs(tile) {
    var out = new Pbf();
    writeTile(tile, out);
    return out.finish();
}
/**
 * Serialized a geojson-vt-created tile to pbf.
 *
 * @param {Object} layers - An object mapping layer names to geojson-vt-created vector tile objects
 * @param {Object} [options] - An object specifying the vector-tile specification version and extent that were used to create `layers`.
 * @param {Number} [options.version=1] - Version of vector-tile spec used
 * @param {Number} [options.extent=4096] - Extent of the vector tile
 * @return {Buffer} uncompressed, pbf-serialized tile data
 */
function fromGeojsonVt(layers, options) {
    options = options || {};
    var l = {};
    for (var k in layers) {
        l[k] = new GeoJSONWrapper(layers[k].features, options);
        l[k].name = k;
        l[k].version = options.version;
        l[k].extent = options.extent;
    }
    return fromVectorTileJs({ layers: l });
}
function writeTile(tile, pbf) {
    for (var key in tile.layers) {
        pbf.writeMessage(3, writeLayer, tile.layers[key]);
    }
}
function writeLayer(layer, pbf) {
    pbf.writeVarintField(15, layer.version || 1);
    pbf.writeStringField(1, layer.name || '');
    pbf.writeVarintField(5, layer.extent || 4096);
    var i;
    var context = {
        keys: [],
        values: [],
        keycache: {},
        valuecache: {}
    };
    for (i = 0; i < layer.length; i++) {
        context.feature = layer.feature(i);
        pbf.writeMessage(2, writeFeature, context);
    }
    var keys = context.keys;
    for (i = 0; i < keys.length; i++) {
        pbf.writeStringField(3, keys[i]);
    }
    var values = context.values;
    for (i = 0; i < values.length; i++) {
        pbf.writeMessage(4, writeValue, values[i]);
    }
}
function writeFeature(context, pbf) {
    var feature = context.feature;
    if (feature.id !== undefined) {
        pbf.writeVarintField(1, feature.id);
    }
    pbf.writeMessage(2, writeProperties, context);
    pbf.writeVarintField(3, feature.type);
    pbf.writeMessage(4, writeGeometry, feature);
}
function writeProperties(context, pbf) {
    var feature = context.feature;
    var keys = context.keys;
    var values = context.values;
    var keycache = context.keycache;
    var valuecache = context.valuecache;
    for (var key in feature.properties) {
        var value = feature.properties[key];
        var keyIndex = keycache[key];
        if (value === null)
            continue;
        // don't encode null value properties
        if (typeof keyIndex === 'undefined') {
            keys.push(key);
            keyIndex = keys.length - 1;
            keycache[key] = keyIndex;
        }
        pbf.writeVarint(keyIndex);
        var type = typeof value;
        if (type !== 'string' && type !== 'boolean' && type !== 'number') {
            value = JSON.stringify(value);
        }
        var valueKey = type + ':' + value;
        var valueIndex = valuecache[valueKey];
        if (typeof valueIndex === 'undefined') {
            values.push(value);
            valueIndex = values.length - 1;
            valuecache[valueKey] = valueIndex;
        }
        pbf.writeVarint(valueIndex);
    }
}
function command(cmd, length) {
    return (length << 3) + (cmd & 7);
}
function zigzag(num) {
    return num << 1 ^ num >> 31;
}
function writeGeometry(feature, pbf) {
    var geometry = feature.loadGeometry();
    var type = feature.type;
    var x = 0;
    var y = 0;
    var rings = geometry.length;
    for (var r = 0; r < rings; r++) {
        var ring = geometry[r];
        var count = 1;
        if (type === 1) {
            count = ring.length;
        }
        pbf.writeVarint(command(1, count));
        // moveto
        // do not write polygon closing path as lineto
        var lineCount = type === 3 ? ring.length - 1 : ring.length;
        for (var i = 0; i < lineCount; i++) {
            if (i === 1 && type !== 1) {
                pbf.writeVarint(command(2, lineCount - 1))    // lineto
;
            }
            var dx = ring[i].x - x;
            var dy = ring[i].y - y;
            pbf.writeVarint(zigzag(dx));
            pbf.writeVarint(zigzag(dy));
            x += dx;
            y += dy;
        }
        if (type === 3) {
            pbf.writeVarint(command(7, 1))    // closepath
;
        }
    }
}
function writeValue(value, pbf) {
    var type = typeof value;
    if (type === 'string') {
        pbf.writeStringField(1, value);
    } else if (type === 'boolean') {
        pbf.writeBooleanField(7, value);
    } else if (type === 'number') {
        if (value % 1 !== 0) {
            pbf.writeDoubleField(3, value);
        } else if (value < 0) {
            pbf.writeSVarintField(6, value);
        } else {
            pbf.writeVarintField(5, value);
        }
    }
}

var vtPbfExports = vtPbf.exports;
var vtpbf = /*@__PURE__*/index.g(vtPbfExports);

const defaultOptions = {
    minZoom: 0,
    // min zoom to generate clusters on
    maxZoom: 16,
    // max zoom level to cluster the points on
    minPoints: 2,
    // minimum points to form a cluster
    radius: 40,
    // cluster radius in pixels
    extent: 512,
    // tile extent (radius is calculated relative to it)
    nodeSize: 64,
    // size of the KD-tree leaf node, affects performance
    log: false,
    // whether to log timing info
    // whether to generate numeric ids for input features (in vector tiles)
    generateId: false,
    // a reduce function for calculating custom cluster properties
    reduce: null,
    // (accumulated, props) => { accumulated.sum += props.sum; }
    // properties to use for individual points when running the reducer
    map: props => props    // props => ({sum: props.my_value})
};
const fround = Math.fround || (tmp => x => {
    tmp[0] = +x;
    return tmp[0];
})(new Float32Array(1));
const OFFSET_ZOOM = 2;
const OFFSET_ID = 3;
const OFFSET_PARENT = 4;
const OFFSET_NUM = 5;
const OFFSET_PROP = 6;
class Supercluster {
    constructor(options) {
        this.options = Object.assign(Object.create(defaultOptions), options);
        this.trees = new Array(this.options.maxZoom + 1);
        this.stride = this.options.reduce ? 7 : 6;
        this.clusterProps = [];
    }
    load(points) {
        const {log, minZoom, maxZoom} = this.options;
        if (log)
            console.time('total time');
        const timerId = `prepare ${ points.length } points`;
        if (log)
            console.time(timerId);
        this.points = points;
        // generate a cluster object for each point and index input points into a KD-tree
        const data = [];
        for (let i = 0; i < points.length; i++) {
            const p = points[i];
            if (!p.geometry)
                continue;
            const [lng, lat] = p.geometry.coordinates;
            const x = fround(lngX(lng));
            const y = fround(latY(lat));
            // store internal point/cluster data in flat numeric arrays for performance
            data.push(x, y, // projected point coordinates
            Infinity, // the last zoom the point was processed at
            i, // index of the source feature in the original input array
            -1, // parent cluster id
            1    // number of points in a cluster
);
            if (this.options.reduce)
                data.push(0);    // noop
        }
        let tree = this.trees[maxZoom + 1] = this._createTree(data);
        if (log)
            console.timeEnd(timerId);
        // cluster points on max zoom, then cluster the results on previous zoom, etc.;
        // results in a cluster hierarchy across zoom levels
        for (let z = maxZoom; z >= minZoom; z--) {
            const now = +Date.now();
            // create a new set of clusters for the zoom and index them with a KD-tree
            tree = this.trees[z] = this._createTree(this._cluster(tree, z));
            if (log)
                console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now);
        }
        if (log)
            console.timeEnd('total time');
        return this;
    }
    getClusters(bbox, zoom) {
        let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
        const minLat = Math.max(-90, Math.min(90, bbox[1]));
        let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
        const maxLat = Math.max(-90, Math.min(90, bbox[3]));
        if (bbox[2] - bbox[0] >= 360) {
            minLng = -180;
            maxLng = 180;
        } else if (minLng > maxLng) {
            const easternHem = this.getClusters([
                minLng,
                minLat,
                180,
                maxLat
            ], zoom);
            const westernHem = this.getClusters([
                -180,
                minLat,
                maxLng,
                maxLat
            ], zoom);
            return easternHem.concat(westernHem);
        }
        const tree = this.trees[this._limitZoom(zoom)];
        const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat));
        const data = tree.data;
        const clusters = [];
        for (const id of ids) {
            const k = this.stride * id;
            clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
        }
        return clusters;
    }
    getChildren(clusterId) {
        const originId = this._getOriginId(clusterId);
        const originZoom = this._getOriginZoom(clusterId);
        const errorMsg = 'No cluster with the specified id.';
        const tree = this.trees[originZoom];
        if (!tree)
            throw new Error(errorMsg);
        const data = tree.data;
        if (originId * this.stride >= data.length)
            throw new Error(errorMsg);
        const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));
        const x = data[originId * this.stride];
        const y = data[originId * this.stride + 1];
        const ids = tree.within(x, y, r);
        const children = [];
        for (const id of ids) {
            const k = id * this.stride;
            if (data[k + OFFSET_PARENT] === clusterId) {
                children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
            }
        }
        if (children.length === 0)
            throw new Error(errorMsg);
        return children;
    }
    getLeaves(clusterId, limit, offset) {
        limit = limit || 10;
        offset = offset || 0;
        const leaves = [];
        this._appendLeaves(leaves, clusterId, limit, offset, 0);
        return leaves;
    }
    getTile(z, x, y) {
        const tree = this.trees[this._limitZoom(z)];
        const z2 = Math.pow(2, z);
        const {extent, radius} = this.options;
        const p = radius / extent;
        const top = (y - p) / z2;
        const bottom = (y + 1 + p) / z2;
        const tile = { features: [] };
        this._addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.data, x, y, z2, tile);
        if (x === 0) {
            this._addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.data, z2, y, z2, tile);
        }
        if (x === z2 - 1) {
            this._addTileFeatures(tree.range(0, top, p / z2, bottom), tree.data, -1, y, z2, tile);
        }
        return tile.features.length ? tile : null;
    }
    getClusterExpansionZoom(clusterId) {
        let expansionZoom = this._getOriginZoom(clusterId) - 1;
        while (expansionZoom <= this.options.maxZoom) {
            const children = this.getChildren(clusterId);
            expansionZoom++;
            if (children.length !== 1)
                break;
            clusterId = children[0].properties.cluster_id;
        }
        return expansionZoom;
    }
    _appendLeaves(result, clusterId, limit, offset, skipped) {
        const children = this.getChildren(clusterId);
        for (const child of children) {
            const props = child.properties;
            if (props && props.cluster) {
                if (skipped + props.point_count <= offset) {
                    // skip the whole cluster
                    skipped += props.point_count;
                } else {
                    // enter the cluster
                    skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped);    // exit the cluster
                }
            } else if (skipped < offset) {
                // skip a single point
                skipped++;
            } else {
                // add a single point
                result.push(child);
            }
            if (result.length === limit)
                break;
        }
        return skipped;
    }
    _createTree(data) {
        const tree = new index.K(data.length / this.stride | 0, this.options.nodeSize, Float32Array);
        for (let i = 0; i < data.length; i += this.stride)
            tree.add(data[i], data[i + 1]);
        tree.finish();
        tree.data = data;
        return tree;
    }
    _addTileFeatures(ids, data, x, y, z2, tile) {
        for (const i of ids) {
            const k = i * this.stride;
            const isCluster = data[k + OFFSET_NUM] > 1;
            let tags, px, py;
            if (isCluster) {
                tags = getClusterProperties(data, k, this.clusterProps);
                px = data[k];
                py = data[k + 1];
            } else {
                const p = this.points[data[k + OFFSET_ID]];
                tags = p.properties;
                const [lng, lat] = p.geometry.coordinates;
                px = lngX(lng);
                py = latY(lat);
            }
            const f = {
                type: 1,
                geometry: [[
                        Math.round(this.options.extent * (px * z2 - x)),
                        Math.round(this.options.extent * (py * z2 - y))
                    ]],
                tags
            };
            // assign id
            let id;
            if (isCluster || this.options.generateId) {
                // optionally generate id for points
                id = data[k + OFFSET_ID];
            } else {
                // keep id if already assigned
                id = this.points[data[k + OFFSET_ID]].id;
            }
            if (id !== undefined)
                f.id = id;
            tile.features.push(f);
        }
    }
    _limitZoom(z) {
        return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));
    }
    _cluster(tree, zoom) {
        const {radius, extent, reduce, minPoints} = this.options;
        const r = radius / (extent * Math.pow(2, zoom));
        const data = tree.data;
        const nextData = [];
        const stride = this.stride;
        // loop through each point
        for (let i = 0; i < data.length; i += stride) {
            // if we've already visited the point at this zoom level, skip it
            if (data[i + OFFSET_ZOOM] <= zoom)
                continue;
            data[i + OFFSET_ZOOM] = zoom;
            // find all nearby points
            const x = data[i];
            const y = data[i + 1];
            const neighborIds = tree.within(data[i], data[i + 1], r);
            const numPointsOrigin = data[i + OFFSET_NUM];
            let numPoints = numPointsOrigin;
            // count the number of points in a potential cluster
            for (const neighborId of neighborIds) {
                const k = neighborId * stride;
                // filter out neighbors that are already processed
                if (data[k + OFFSET_ZOOM] > zoom)
                    numPoints += data[k + OFFSET_NUM];
            }
            // if there were neighbors to merge, and there are enough points to form a cluster
            if (numPoints > numPointsOrigin && numPoints >= minPoints) {
                let wx = x * numPointsOrigin;
                let wy = y * numPointsOrigin;
                let clusterProperties;
                let clusterPropIndex = -1;
                // encode both zoom and point index on which the cluster originated -- offset by total length of features
                const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;
                for (const neighborId of neighborIds) {
                    const k = neighborId * stride;
                    if (data[k + OFFSET_ZOOM] <= zoom)
                        continue;
                    data[k + OFFSET_ZOOM] = zoom;
                    // save the zoom (so it doesn't get processed twice)
                    const numPoints2 = data[k + OFFSET_NUM];
                    wx += data[k] * numPoints2;
                    // accumulate coordinates for calculating weighted center
                    wy += data[k + 1] * numPoints2;
                    data[k + OFFSET_PARENT] = id;
                    if (reduce) {
                        if (!clusterProperties) {
                            clusterProperties = this._map(data, i, true);
                            clusterPropIndex = this.clusterProps.length;
                            this.clusterProps.push(clusterProperties);
                        }
                        reduce(clusterProperties, this._map(data, k));
                    }
                }
                data[i + OFFSET_PARENT] = id;
                nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);
                if (reduce)
                    nextData.push(clusterPropIndex);
            } else {
                // left points as unclustered
                for (let j = 0; j < stride; j++)
                    nextData.push(data[i + j]);
                if (numPoints > 1) {
                    for (const neighborId of neighborIds) {
                        const k = neighborId * stride;
                        if (data[k + OFFSET_ZOOM] <= zoom)
                            continue;
                        data[k + OFFSET_ZOOM] = zoom;
                        for (let j = 0; j < stride; j++)
                            nextData.push(data[k + j]);
                    }
                }
            }
        }
        return nextData;
    }
    // get index of the point from which the cluster originated
    _getOriginId(clusterId) {
        return clusterId - this.points.length >> 5;
    }
    // get zoom of the point from which the cluster originated
    _getOriginZoom(clusterId) {
        return (clusterId - this.points.length) % 32;
    }
    _map(data, i, clone) {
        if (data[i + OFFSET_NUM] > 1) {
            const props = this.clusterProps[data[i + OFFSET_PROP]];
            return clone ? Object.assign({}, props) : props;
        }
        const original = this.points[data[i + OFFSET_ID]].properties;
        const result = this.options.map(original);
        return clone && result === original ? Object.assign({}, result) : result;
    }
}
function getClusterJSON(data, i, clusterProps) {
    return {
        type: 'Feature',
        id: data[i + OFFSET_ID],
        properties: getClusterProperties(data, i, clusterProps),
        geometry: {
            type: 'Point',
            coordinates: [
                xLng(data[i]),
                yLat(data[i + 1])
            ]
        }
    };
}
function getClusterProperties(data, i, clusterProps) {
    const count = data[i + OFFSET_NUM];
    const abbrev = count >= 10000 ? `${ Math.round(count / 1000) }k` : count >= 1000 ? `${ Math.round(count / 100) / 10 }k` : count;
    const propIndex = data[i + OFFSET_PROP];
    const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);
    return Object.assign(properties, {
        cluster: true,
        cluster_id: data[i + OFFSET_ID],
        point_count: count,
        point_count_abbreviated: abbrev
    });
}
// longitude/latitude to spherical mercator in [0..1] range
function lngX(lng) {
    return lng / 360 + 0.5;
}
function latY(lat) {
    const sin = Math.sin(lat * Math.PI / 180);
    const y = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
    return y < 0 ? 0 : y > 1 ? 1 : y;
}
// spherical mercator to longitude/latitude
function xLng(x) {
    return (x - 0.5) * 360;
}
function yLat(y) {
    const y2 = (180 - y * 360) * Math.PI / 180;
    return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
}

var geojsonVtDev = {exports: {}};

(function (module, exports) {
	(function (global, factory) {
	    module.exports = factory() ;
	}(this, function () {
	    // calculate simplification data using optimized Douglas-Peucker algorithm
	    function simplify(coords, first, last, sqTolerance) {
	        var maxSqDist = sqTolerance;
	        var mid = last - first >> 1;
	        var minPosToMid = last - first;
	        var index;
	        var ax = coords[first];
	        var ay = coords[first + 1];
	        var bx = coords[last];
	        var by = coords[last + 1];
	        for (var i = first + 3; i < last; i += 3) {
	            var d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
	            if (d > maxSqDist) {
	                index = i;
	                maxSqDist = d;
	            } else if (d === maxSqDist) {
	                // a workaround to ensure we choose a pivot close to the middle of the list,
	                // reducing recursion depth, for certain degenerate inputs
	                // https://github.com/mapbox/geojson-vt/issues/104
	                var posToMid = Math.abs(i - mid);
	                if (posToMid < minPosToMid) {
	                    index = i;
	                    minPosToMid = posToMid;
	                }
	            }
	        }
	        if (maxSqDist > sqTolerance) {
	            if (index - first > 3)
	                simplify(coords, first, index, sqTolerance);
	            coords[index + 2] = maxSqDist;
	            if (last - index > 3)
	                simplify(coords, index, last, sqTolerance);
	        }
	    }
	    // square distance from a point to a segment
	    function getSqSegDist(px, py, x, y, bx, by) {
	        var dx = bx - x;
	        var dy = by - y;
	        if (dx !== 0 || dy !== 0) {
	            var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
	            if (t > 1) {
	                x = bx;
	                y = by;
	            } else if (t > 0) {
	                x += dx * t;
	                y += dy * t;
	            }
	        }
	        dx = px - x;
	        dy = py - y;
	        return dx * dx + dy * dy;
	    }
	    function createFeature(id, type, geom, tags) {
	        var feature = {
	            id: typeof id === 'undefined' ? null : id,
	            type: type,
	            geometry: geom,
	            tags: tags,
	            minX: Infinity,
	            minY: Infinity,
	            maxX: -Infinity,
	            maxY: -Infinity
	        };
	        calcBBox(feature);
	        return feature;
	    }
	    function calcBBox(feature) {
	        var geom = feature.geometry;
	        var type = feature.type;
	        if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
	            calcLineBBox(feature, geom);
	        } else if (type === 'Polygon' || type === 'MultiLineString') {
	            for (var i = 0; i < geom.length; i++) {
	                calcLineBBox(feature, geom[i]);
	            }
	        } else if (type === 'MultiPolygon') {
	            for (i = 0; i < geom.length; i++) {
	                for (var j = 0; j < geom[i].length; j++) {
	                    calcLineBBox(feature, geom[i][j]);
	                }
	            }
	        }
	    }
	    function calcLineBBox(feature, geom) {
	        for (var i = 0; i < geom.length; i += 3) {
	            feature.minX = Math.min(feature.minX, geom[i]);
	            feature.minY = Math.min(feature.minY, geom[i + 1]);
	            feature.maxX = Math.max(feature.maxX, geom[i]);
	            feature.maxY = Math.max(feature.maxY, geom[i + 1]);
	        }
	    }
	    // converts GeoJSON feature into an intermediate projected JSON vector format with simplification data
	    function convert(data, options) {
	        var features = [];
	        if (data.type === 'FeatureCollection') {
	            for (var i = 0; i < data.features.length; i++) {
	                convertFeature(features, data.features[i], options, i);
	            }
	        } else if (data.type === 'Feature') {
	            convertFeature(features, data, options);
	        } else {
	            // single geometry or a geometry collection
	            convertFeature(features, { geometry: data }, options);
	        }
	        return features;
	    }
	    function convertFeature(features, geojson, options, index) {
	        if (!geojson.geometry)
	            return;
	        var coords = geojson.geometry.coordinates;
	        var type = geojson.geometry.type;
	        var tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
	        var geometry = [];
	        var id = geojson.id;
	        if (options.promoteId) {
	            id = geojson.properties[options.promoteId];
	        } else if (options.generateId) {
	            id = index || 0;
	        }
	        if (type === 'Point') {
	            convertPoint(coords, geometry);
	        } else if (type === 'MultiPoint') {
	            for (var i = 0; i < coords.length; i++) {
	                convertPoint(coords[i], geometry);
	            }
	        } else if (type === 'LineString') {
	            convertLine(coords, geometry, tolerance, false);
	        } else if (type === 'MultiLineString') {
	            if (options.lineMetrics) {
	                // explode into linestrings to be able to track metrics
	                for (i = 0; i < coords.length; i++) {
	                    geometry = [];
	                    convertLine(coords[i], geometry, tolerance, false);
	                    features.push(createFeature(id, 'LineString', geometry, geojson.properties));
	                }
	                return;
	            } else {
	                convertLines(coords, geometry, tolerance, false);
	            }
	        } else if (type === 'Polygon') {
	            convertLines(coords, geometry, tolerance, true);
	        } else if (type === 'MultiPolygon') {
	            for (i = 0; i < coords.length; i++) {
	                var polygon = [];
	                convertLines(coords[i], polygon, tolerance, true);
	                geometry.push(polygon);
	            }
	        } else if (type === 'GeometryCollection') {
	            for (i = 0; i < geojson.geometry.geometries.length; i++) {
	                convertFeature(features, {
	                    id: id,
	                    geometry: geojson.geometry.geometries[i],
	                    properties: geojson.properties
	                }, options, index);
	            }
	            return;
	        } else {
	            throw new Error('Input data is not a valid GeoJSON object.');
	        }
	        features.push(createFeature(id, type, geometry, geojson.properties));
	    }
	    function convertPoint(coords, out) {
	        out.push(projectX(coords[0]));
	        out.push(projectY(coords[1]));
	        out.push(0);
	    }
	    function convertLine(ring, out, tolerance, isPolygon) {
	        var x0, y0;
	        var size = 0;
	        for (var j = 0; j < ring.length; j++) {
	            var x = projectX(ring[j][0]);
	            var y = projectY(ring[j][1]);
	            out.push(x);
	            out.push(y);
	            out.push(0);
	            if (j > 0) {
	                if (isPolygon) {
	                    size += (x0 * y - x * y0) / 2;    // area
	                } else {
	                    size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2));    // length
	                }
	            }
	            x0 = x;
	            y0 = y;
	        }
	        var last = out.length - 3;
	        out[2] = 1;
	        simplify(out, 0, last, tolerance);
	        out[last + 2] = 1;
	        out.size = Math.abs(size);
	        out.start = 0;
	        out.end = out.size;
	    }
	    function convertLines(rings, out, tolerance, isPolygon) {
	        for (var i = 0; i < rings.length; i++) {
	            var geom = [];
	            convertLine(rings[i], geom, tolerance, isPolygon);
	            out.push(geom);
	        }
	    }
	    function projectX(x) {
	        return x / 360 + 0.5;
	    }
	    function projectY(y) {
	        var sin = Math.sin(y * Math.PI / 180);
	        var y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
	        return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
	    }
	    /* clip features between two axis-parallel lines:
	 *     |        |
	 *  ___|___     |     /
	 * /   |   \____|____/
	 *     |        |
	 */
	    function clip(features, scale, k1, k2, axis, minAll, maxAll, options) {
	        k1 /= scale;
	        k2 /= scale;
	        if (minAll >= k1 && maxAll < k2)
	            return features;    // trivial accept
	        else if (maxAll < k1 || minAll >= k2)
	            return null;
	        // trivial reject
	        var clipped = [];
	        for (var i = 0; i < features.length; i++) {
	            var feature = features[i];
	            var geometry = feature.geometry;
	            var type = feature.type;
	            var min = axis === 0 ? feature.minX : feature.minY;
	            var max = axis === 0 ? feature.maxX : feature.maxY;
	            if (min >= k1 && max < k2) {
	                // trivial accept
	                clipped.push(feature);
	                continue;
	            } else if (max < k1 || min >= k2) {
	                // trivial reject
	                continue;
	            }
	            var newGeometry = [];
	            if (type === 'Point' || type === 'MultiPoint') {
	                clipPoints(geometry, newGeometry, k1, k2, axis);
	            } else if (type === 'LineString') {
	                clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics);
	            } else if (type === 'MultiLineString') {
	                clipLines(geometry, newGeometry, k1, k2, axis, false);
	            } else if (type === 'Polygon') {
	                clipLines(geometry, newGeometry, k1, k2, axis, true);
	            } else if (type === 'MultiPolygon') {
	                for (var j = 0; j < geometry.length; j++) {
	                    var polygon = [];
	                    clipLines(geometry[j], polygon, k1, k2, axis, true);
	                    if (polygon.length) {
	                        newGeometry.push(polygon);
	                    }
	                }
	            }
	            if (newGeometry.length) {
	                if (options.lineMetrics && type === 'LineString') {
	                    for (j = 0; j < newGeometry.length; j++) {
	                        clipped.push(createFeature(feature.id, type, newGeometry[j], feature.tags));
	                    }
	                    continue;
	                }
	                if (type === 'LineString' || type === 'MultiLineString') {
	                    if (newGeometry.length === 1) {
	                        type = 'LineString';
	                        newGeometry = newGeometry[0];
	                    } else {
	                        type = 'MultiLineString';
	                    }
	                }
	                if (type === 'Point' || type === 'MultiPoint') {
	                    type = newGeometry.length === 3 ? 'Point' : 'MultiPoint';
	                }
	                clipped.push(createFeature(feature.id, type, newGeometry, feature.tags));
	            }
	        }
	        return clipped.length ? clipped : null;
	    }
	    function clipPoints(geom, newGeom, k1, k2, axis) {
	        for (var i = 0; i < geom.length; i += 3) {
	            var a = geom[i + axis];
	            if (a >= k1 && a <= k2) {
	                newGeom.push(geom[i]);
	                newGeom.push(geom[i + 1]);
	                newGeom.push(geom[i + 2]);
	            }
	        }
	    }
	    function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {
	        var slice = newSlice(geom);
	        var intersect = axis === 0 ? intersectX : intersectY;
	        var len = geom.start;
	        var segLen, t;
	        for (var i = 0; i < geom.length - 3; i += 3) {
	            var ax = geom[i];
	            var ay = geom[i + 1];
	            var az = geom[i + 2];
	            var bx = geom[i + 3];
	            var by = geom[i + 4];
	            var a = axis === 0 ? ax : ay;
	            var b = axis === 0 ? bx : by;
	            var exited = false;
	            if (trackMetrics)
	                segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
	            if (a < k1) {
	                // ---|-->  | (line enters the clip region from the left)
	                if (b > k1) {
	                    t = intersect(slice, ax, ay, bx, by, k1);
	                    if (trackMetrics)
	                        slice.start = len + segLen * t;
	                }
	            } else if (a > k2) {
	                // |  <--|--- (line enters the clip region from the right)
	                if (b < k2) {
	                    t = intersect(slice, ax, ay, bx, by, k2);
	                    if (trackMetrics)
	                        slice.start = len + segLen * t;
	                }
	            } else {
	                addPoint(slice, ax, ay, az);
	            }
	            if (b < k1 && a >= k1) {
	                // <--|---  | or <--|-----|--- (line exits the clip region on the left)
	                t = intersect(slice, ax, ay, bx, by, k1);
	                exited = true;
	            }
	            if (b > k2 && a <= k2) {
	                // |  ---|--> or ---|-----|--> (line exits the clip region on the right)
	                t = intersect(slice, ax, ay, bx, by, k2);
	                exited = true;
	            }
	            if (!isPolygon && exited) {
	                if (trackMetrics)
	                    slice.end = len + segLen * t;
	                newGeom.push(slice);
	                slice = newSlice(geom);
	            }
	            if (trackMetrics)
	                len += segLen;
	        }
	        // add the last point
	        var last = geom.length - 3;
	        ax = geom[last];
	        ay = geom[last + 1];
	        az = geom[last + 2];
	        a = axis === 0 ? ax : ay;
	        if (a >= k1 && a <= k2)
	            addPoint(slice, ax, ay, az);
	        // close the polygon if its endpoints are not the same after clipping
	        last = slice.length - 3;
	        if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {
	            addPoint(slice, slice[0], slice[1], slice[2]);
	        }
	        // add the final slice
	        if (slice.length) {
	            newGeom.push(slice);
	        }
	    }
	    function newSlice(line) {
	        var slice = [];
	        slice.size = line.size;
	        slice.start = line.start;
	        slice.end = line.end;
	        return slice;
	    }
	    function clipLines(geom, newGeom, k1, k2, axis, isPolygon) {
	        for (var i = 0; i < geom.length; i++) {
	            clipLine(geom[i], newGeom, k1, k2, axis, isPolygon, false);
	        }
	    }
	    function addPoint(out, x, y, z) {
	        out.push(x);
	        out.push(y);
	        out.push(z);
	    }
	    function intersectX(out, ax, ay, bx, by, x) {
	        var t = (x - ax) / (bx - ax);
	        out.push(x);
	        out.push(ay + (by - ay) * t);
	        out.push(1);
	        return t;
	    }
	    function intersectY(out, ax, ay, bx, by, y) {
	        var t = (y - ay) / (by - ay);
	        out.push(ax + (bx - ax) * t);
	        out.push(y);
	        out.push(1);
	        return t;
	    }
	    function wrap(features, options) {
	        var buffer = options.buffer / options.extent;
	        var merged = features;
	        var left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options);
	        // left world copy
	        var right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options);
	        // right world copy
	        if (left || right) {
	            merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || [];
	            // center world copy
	            if (left)
	                merged = shiftFeatureCoords(left, 1).concat(merged);
	            // merge left into center
	            if (right)
	                merged = merged.concat(shiftFeatureCoords(right, -1));    // merge right into center
	        }
	        return merged;
	    }
	    function shiftFeatureCoords(features, offset) {
	        var newFeatures = [];
	        for (var i = 0; i < features.length; i++) {
	            var feature = features[i], type = feature.type;
	            var newGeometry;
	            if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
	                newGeometry = shiftCoords(feature.geometry, offset);
	            } else if (type === 'MultiLineString' || type === 'Polygon') {
	                newGeometry = [];
	                for (var j = 0; j < feature.geometry.length; j++) {
	                    newGeometry.push(shiftCoords(feature.geometry[j], offset));
	                }
	            } else if (type === 'MultiPolygon') {
	                newGeometry = [];
	                for (j = 0; j < feature.geometry.length; j++) {
	                    var newPolygon = [];
	                    for (var k = 0; k < feature.geometry[j].length; k++) {
	                        newPolygon.push(shiftCoords(feature.geometry[j][k], offset));
	                    }
	                    newGeometry.push(newPolygon);
	                }
	            }
	            newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));
	        }
	        return newFeatures;
	    }
	    function shiftCoords(points, offset) {
	        var newPoints = [];
	        newPoints.size = points.size;
	        if (points.start !== undefined) {
	            newPoints.start = points.start;
	            newPoints.end = points.end;
	        }
	        for (var i = 0; i < points.length; i += 3) {
	            newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);
	        }
	        return newPoints;
	    }
	    // Transforms the coordinates of each feature in the given tile from
	    // mercator-projected space into (extent x extent) tile space.
	    function transformTile(tile, extent) {
	        if (tile.transformed)
	            return tile;
	        var z2 = 1 << tile.z, tx = tile.x, ty = tile.y, i, j, k;
	        for (i = 0; i < tile.features.length; i++) {
	            var feature = tile.features[i], geom = feature.geometry, type = feature.type;
	            feature.geometry = [];
	            if (type === 1) {
	                for (j = 0; j < geom.length; j += 2) {
	                    feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));
	                }
	            } else {
	                for (j = 0; j < geom.length; j++) {
	                    var ring = [];
	                    for (k = 0; k < geom[j].length; k += 2) {
	                        ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));
	                    }
	                    feature.geometry.push(ring);
	                }
	            }
	        }
	        tile.transformed = true;
	        return tile;
	    }
	    function transformPoint(x, y, extent, z2, tx, ty) {
	        return [
	            Math.round(extent * (x * z2 - tx)),
	            Math.round(extent * (y * z2 - ty))
	        ];
	    }
	    function createTile(features, z, tx, ty, options) {
	        var tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
	        var tile = {
	            features: [],
	            numPoints: 0,
	            numSimplified: 0,
	            numFeatures: 0,
	            source: null,
	            x: tx,
	            y: ty,
	            z: z,
	            transformed: false,
	            minX: 2,
	            minY: 1,
	            maxX: -1,
	            maxY: 0
	        };
	        for (var i = 0; i < features.length; i++) {
	            tile.numFeatures++;
	            addFeature(tile, features[i], tolerance, options);
	            var minX = features[i].minX;
	            var minY = features[i].minY;
	            var maxX = features[i].maxX;
	            var maxY = features[i].maxY;
	            if (minX < tile.minX)
	                tile.minX = minX;
	            if (minY < tile.minY)
	                tile.minY = minY;
	            if (maxX > tile.maxX)
	                tile.maxX = maxX;
	            if (maxY > tile.maxY)
	                tile.maxY = maxY;
	        }
	        return tile;
	    }
	    function addFeature(tile, feature, tolerance, options) {
	        var geom = feature.geometry, type = feature.type, simplified = [];
	        if (type === 'Point' || type === 'MultiPoint') {
	            for (var i = 0; i < geom.length; i += 3) {
	                simplified.push(geom[i]);
	                simplified.push(geom[i + 1]);
	                tile.numPoints++;
	                tile.numSimplified++;
	            }
	        } else if (type === 'LineString') {
	            addLine(simplified, geom, tile, tolerance, false, false);
	        } else if (type === 'MultiLineString' || type === 'Polygon') {
	            for (i = 0; i < geom.length; i++) {
	                addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0);
	            }
	        } else if (type === 'MultiPolygon') {
	            for (var k = 0; k < geom.length; k++) {
	                var polygon = geom[k];
	                for (i = 0; i < polygon.length; i++) {
	                    addLine(simplified, polygon[i], tile, tolerance, true, i === 0);
	                }
	            }
	        }
	        if (simplified.length) {
	            var tags = feature.tags || null;
	            if (type === 'LineString' && options.lineMetrics) {
	                tags = {};
	                for (var key in feature.tags)
	                    tags[key] = feature.tags[key];
	                tags['mapbox_clip_start'] = geom.start / geom.size;
	                tags['mapbox_clip_end'] = geom.end / geom.size;
	            }
	            var tileFeature = {
	                geometry: simplified,
	                type: type === 'Polygon' || type === 'MultiPolygon' ? 3 : type === 'LineString' || type === 'MultiLineString' ? 2 : 1,
	                tags: tags
	            };
	            if (feature.id !== null) {
	                tileFeature.id = feature.id;
	            }
	            tile.features.push(tileFeature);
	        }
	    }
	    function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
	        var sqTolerance = tolerance * tolerance;
	        if (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) {
	            tile.numPoints += geom.length / 3;
	            return;
	        }
	        var ring = [];
	        for (var i = 0; i < geom.length; i += 3) {
	            if (tolerance === 0 || geom[i + 2] > sqTolerance) {
	                tile.numSimplified++;
	                ring.push(geom[i]);
	                ring.push(geom[i + 1]);
	            }
	            tile.numPoints++;
	        }
	        if (isPolygon)
	            rewind(ring, isOuter);
	        result.push(ring);
	    }
	    function rewind(ring, clockwise) {
	        var area = 0;
	        for (var i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
	            area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
	        }
	        if (area > 0 === clockwise) {
	            for (i = 0, len = ring.length; i < len / 2; i += 2) {
	                var x = ring[i];
	                var y = ring[i + 1];
	                ring[i] = ring[len - 2 - i];
	                ring[i + 1] = ring[len - 1 - i];
	                ring[len - 2 - i] = x;
	                ring[len - 1 - i] = y;
	            }
	        }
	    }
	    function geojsonvt(data, options) {
	        return new GeoJSONVT(data, options);
	    }
	    function GeoJSONVT(data, options) {
	        options = this.options = extend(Object.create(this.options), options);
	        var debug = options.debug;
	        if (debug)
	            console.time('preprocess data');
	        if (options.maxZoom < 0 || options.maxZoom > 24)
	            throw new Error('maxZoom should be in the 0-24 range');
	        if (options.promoteId && options.generateId)
	            throw new Error('promoteId and generateId cannot be used together.');
	        var features = convert(data, options);
	        this.tiles = {};
	        this.tileCoords = [];
	        if (debug) {
	            console.timeEnd('preprocess data');
	            console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
	            console.time('generate tiles');
	            this.stats = {};
	            this.total = 0;
	        }
	        features = wrap(features, options);
	        // start slicing from the top tile down
	        if (features.length)
	            this.splitTile(features, 0, 0, 0);
	        if (debug) {
	            if (features.length)
	                console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
	            console.timeEnd('generate tiles');
	            console.log('tiles generated:', this.total, JSON.stringify(this.stats));
	        }
	    }
	    GeoJSONVT.prototype.options = {
	        maxZoom: 14,
	        // max zoom to preserve detail on
	        indexMaxZoom: 5,
	        // max zoom in the tile index
	        indexMaxPoints: 100000,
	        // max number of points per tile in the tile index
	        tolerance: 3,
	        // simplification tolerance (higher means simpler)
	        extent: 4096,
	        // tile extent
	        buffer: 64,
	        // tile buffer on each side
	        lineMetrics: false,
	        // whether to calculate line metrics
	        promoteId: null,
	        // name of a feature property to be promoted to feature.id
	        generateId: false,
	        // whether to generate feature ids. Cannot be used with promoteId
	        debug: 0    // logging level (0, 1 or 2)
	    };
	    GeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {
	        var stack = [
	                features,
	                z,
	                x,
	                y
	            ], options = this.options, debug = options.debug;
	        // avoid recursion by using a processing queue
	        while (stack.length) {
	            y = stack.pop();
	            x = stack.pop();
	            z = stack.pop();
	            features = stack.pop();
	            var z2 = 1 << z, id = toID(z, x, y), tile = this.tiles[id];
	            if (!tile) {
	                if (debug > 1)
	                    console.time('creation');
	                tile = this.tiles[id] = createTile(features, z, x, y, options);
	                this.tileCoords.push({
	                    z: z,
	                    x: x,
	                    y: y
	                });
	                if (debug) {
	                    if (debug > 1) {
	                        console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
	                        console.timeEnd('creation');
	                    }
	                    var key = 'z' + z;
	                    this.stats[key] = (this.stats[key] || 0) + 1;
	                    this.total++;
	                }
	            }
	            // save reference to original geometry in tile so that we can drill down later if we stop now
	            tile.source = features;
	            // if it's the first-pass tiling
	            if (!cz) {
	                // stop tiling if we reached max zoom, or if the tile is too simple
	                if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints)
	                    continue;    // if a drilldown to a specific tile
	            } else {
	                // stop tiling if we reached base zoom or our target tile zoom
	                if (z === options.maxZoom || z === cz)
	                    continue;
	                // stop tiling if it's not an ancestor of the target tile
	                var m = 1 << cz - z;
	                if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m))
	                    continue;
	            }
	            // if we slice further down, no need to keep source geometry
	            tile.source = null;
	            if (features.length === 0)
	                continue;
	            if (debug > 1)
	                console.time('clipping');
	            // values we'll use for clipping
	            var k1 = 0.5 * options.buffer / options.extent, k2 = 0.5 - k1, k3 = 0.5 + k1, k4 = 1 + k1, tl, bl, tr, br, left, right;
	            tl = bl = tr = br = null;
	            left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
	            right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);
	            features = null;
	            if (left) {
	                tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
	                bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
	                left = null;
	            }
	            if (right) {
	                tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
	                br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
	                right = null;
	            }
	            if (debug > 1)
	                console.timeEnd('clipping');
	            stack.push(tl || [], z + 1, x * 2, y * 2);
	            stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
	            stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
	            stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
	        }
	    };
	    GeoJSONVT.prototype.getTile = function (z, x, y) {
	        var options = this.options, extent = options.extent, debug = options.debug;
	        if (z < 0 || z > 24)
	            return null;
	        var z2 = 1 << z;
	        x = (x % z2 + z2) % z2;
	        // wrap tile x coordinate
	        var id = toID(z, x, y);
	        if (this.tiles[id])
	            return transformTile(this.tiles[id], extent);
	        if (debug > 1)
	            console.log('drilling down to z%d-%d-%d', z, x, y);
	        var z0 = z, x0 = x, y0 = y, parent;
	        while (!parent && z0 > 0) {
	            z0--;
	            x0 = Math.floor(x0 / 2);
	            y0 = Math.floor(y0 / 2);
	            parent = this.tiles[toID(z0, x0, y0)];
	        }
	        if (!parent || !parent.source)
	            return null;
	        // if we found a parent tile containing the original geometry, we can drill down from it
	        if (debug > 1)
	            console.log('found parent tile z%d-%d-%d', z0, x0, y0);
	        if (debug > 1)
	            console.time('drilling down');
	        this.splitTile(parent.source, z0, x0, y0, z, x, y);
	        if (debug > 1)
	            console.timeEnd('drilling down');
	        return this.tiles[id] ? transformTile(this.tiles[id], extent) : null;
	    };
	    function toID(z, x, y) {
	        return ((1 << z) * y + x) * 32 + z;
	    }
	    function extend(dest, src) {
	        for (var i in src)
	            dest[i] = src[i];
	        return dest;
	    }
	    return geojsonvt;
	})); 
} (geojsonVtDev));

var geojsonVtDevExports = geojsonVtDev.exports;
var geojsonvt = /*@__PURE__*/index.g(geojsonVtDevExports);

//      
// $FlowFixMe[missing-this-annot]
function loadGeoJSONTile(params, callback) {
    const canonical = params.tileID.canonical;
    if (!this._geoJSONIndex) {
        return callback(null, null);    // we couldn't load the file
    }
    const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);
    if (!geoJSONTile) {
        return callback(null, null);    // nothing in the given tile
    }
    const geojsonWrapper = new GeoJSONWrapper$2(geoJSONTile.features);
    // Encode the geojson-vt tile into binary vector tile form.  This
    // is a convenience that allows `FeatureIndex` to operate the same way
    // across `VectorTileSource` and `GeoJSONSource` data.
    let pbf = vtpbf(geojsonWrapper);
    if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {
        // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35)
        pbf = new Uint8Array(pbf);
    }
    callback(null, {
        vectorTile: geojsonWrapper,
        rawData: pbf.buffer
    });
}
/**
 * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}.
 * This class is designed to be easily reused to support custom source types
 * for data formats that can be parsed/converted into an in-memory GeoJSON
 * representation.  To do so, create it with
 * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`.
 * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson).
 *
 * @private
 */
class GeoJSONWorkerSource extends index.d {
    /**
     * @param [loadGeoJSON] Optional method for custom loading/parsing of
     * GeoJSON based on parameters passed from the main-thread Source.
     * See {@link GeoJSONWorkerSource#loadGeoJSON}.
     * @private
     */
    constructor(actor, layerIndex, availableImages, isSpriteLoaded, loadGeoJSON, brightness) {
        super(actor, layerIndex, availableImages, isSpriteLoaded, loadGeoJSONTile, brightness);
        if (loadGeoJSON) {
            this.loadGeoJSON = loadGeoJSON;
        }
    }
    /**
     * Fetches (if appropriate), parses, and index geojson data into tiles. This
     * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile}
     * can correctly serve up tiles.
     *
     * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching/parsing,
     * expecting `callback(error, data)` to be called with either an error or a
     * parsed GeoJSON object.
     *
     * When `loadData` requests come in faster than they can be processed,
     * they are coalesced into a single request using the latest data.
     * See {@link GeoJSONWorkerSource#coalesce}
     *
     * @param params
     * @param callback
     * @private
     */
    loadData(params, callback) {
        const requestParam = params && params.request;
        const perf = requestParam && requestParam.collectResourceTiming;
        this.loadGeoJSON(params, (err, data) => {
            if (err || !data) {
                return callback(err);
            } else if (typeof data !== 'object') {
                return callback(new Error(`Input data given to '${ params.source }' is not a valid GeoJSON object.`));
            } else {
                rewind$1(data, true);
                try {
                    if (params.filter) {
                        const compiled = index.e(params.filter, {
                            type: 'boolean',
                            'property-type': 'data-driven',
                            overridable: false,
                            transition: false
                        });
                        if (compiled.result === 'error')
                            throw new Error(compiled.value.map(err => `${ err.key }: ${ err.message }`).join(', '));
                        const features = data.features.filter(feature => compiled.value.evaluate({ zoom: 0 }, feature));
                        data = {
                            type: 'FeatureCollection',
                            features
                        };
                    }
                    this._geoJSONIndex = params.cluster ? new Supercluster(getSuperclusterOptions(params)).load(data.features) : geojsonvt(data, params.geojsonVtOptions);
                } catch (err) {
                    return callback(err);
                }
                this.loaded = {};
                const result = {};
                if (perf) {
                    const resourceTimingData = index.f(requestParam);
                    // it's necessary to eval the result of getEntriesByName() here via parse/stringify
                    // late evaluation in the main thread causes TypeError: illegal invocation
                    if (resourceTimingData) {
                        result.resourceTiming = {};
                        result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData));
                    }
                }
                callback(null, result);
            }
        });
    }
    /**
    * Implements {@link WorkerSource#reloadTile}.
    *
    * If the tile is loaded, uses the implementation in VectorTileWorkerSource.
    * Otherwise, such as after a setData() call, we load the tile fresh.
    *
    * @param params
    * @param params.uid The UID for this tile.
    * @private
    */
    reloadTile(params, callback) {
        const loaded = this.loaded, uid = params.uid;
        if (loaded && loaded[uid]) {
            return super.reloadTile(params, callback);
        } else {
            return this.loadTile(params, callback);
        }
    }
    /**
     * Fetch and parse GeoJSON according to the given params.  Calls `callback`
     * with `(err, data)`, where `data` is a parsed GeoJSON object.
     *
     * GeoJSON is loaded and parsed from `params.url` if it exists, or else
     * expected as a literal (string or object) `params.data`.
     *
     * @param params
     * @param [params.url] A URL to the remote GeoJSON data.
     * @param [params.data] Literal GeoJSON data. Must be provided if `params.url` is not.
     * @private
     */
    // $FlowFixMe[duplicate-class-member]
    loadGeoJSON(params, callback) {
        // Because of same origin issues, urls must either include an explicit
        // origin or absolute path.
        // ie: /foo/bar.json or http://example.com/bar.json
        // but not ../foo/bar.json
        if (params.request) {
            index.h(params.request, callback);
        } else if (typeof params.data === 'string') {
            try {
                return callback(null, JSON.parse(params.data));
            } catch (e) {
                return callback(new Error(`Input data given to '${ params.source }' is not a valid GeoJSON object.`));
            }
        } else {
            return callback(new Error(`Input data given to '${ params.source }' is not a valid GeoJSON object.`));
        }
    }
    getClusterExpansionZoom(params, callback) {
        try {
            callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId));
        } catch (e) {
            callback(e);
        }
    }
    getClusterChildren(params, callback) {
        try {
            callback(null, this._geoJSONIndex.getChildren(params.clusterId));
        } catch (e) {
            callback(e);
        }
    }
    getClusterLeaves(params, callback) {
        try {
            callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset));
        } catch (e) {
            callback(e);
        }
    }
}
function getSuperclusterOptions({superclusterOptions, clusterProperties}) {
    if (!clusterProperties || !superclusterOptions)
        return superclusterOptions;
    const mapExpressions = {};
    const reduceExpressions = {};
    const globals = {
        accumulated: null,
        zoom: 0
    };
    const feature = { properties: null };
    const propertyNames = Object.keys(clusterProperties);
    for (const key of propertyNames) {
        const [operator, mapExpression] = clusterProperties[key];
        const mapExpressionParsed = index.e(mapExpression);
        const reduceExpressionParsed = index.e(typeof operator === 'string' ? [
            operator,
            ['accumulated'],
            [
                'get',
                key
            ]
        ] : operator);
        mapExpressions[key] = mapExpressionParsed.value;
        reduceExpressions[key] = reduceExpressionParsed.value;
    }
    superclusterOptions.map = pointProperties => {
        feature.properties = pointProperties;
        const properties = {};
        for (const key of propertyNames) {
            properties[key] = mapExpressions[key].evaluate(globals, feature);
        }
        return properties;
    };
    superclusterOptions.reduce = (accumulated, clusterProperties) => {
        feature.properties = clusterProperties;
        for (const key of propertyNames) {
            globals.accumulated = accumulated[key];
            accumulated[key] = reduceExpressions[key].evaluate(globals, feature);
        }
    };
    return superclusterOptions;
}

//      
class Tiled3dWorkerTile {
    constructor(params, brightness) {
        this.tileID = new index.O(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);
        this.tileZoom = params.tileZoom;
        this.uid = params.uid;
        this.zoom = params.zoom;
        this.canonical = params.tileID.canonical;
        this.pixelRatio = params.pixelRatio;
        this.tileSize = params.tileSize;
        this.source = params.source;
        this.overscaling = this.tileID.overscaleFactor();
        this.projection = params.projection;
        this.brightness = brightness;
    }
    parse(data, layerIndex, params, callback) {
        this.status = 'parsing';
        const tileID = new index.O(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);
        const buckets = {};
        const layerFamilies = layerIndex.familiesBySource[params.source];
        const featureIndex = new index.F(tileID, params.promoteId);
        featureIndex.bucketLayerIDs = [];
        return index.l(data).then(gltf => {
            if (!gltf)
                return callback(new Error('Could not parse tile'));
            const nodes = index.j(gltf, 1 / index.t(params.tileID.canonical));
            const hasMapboxMeshFeatures = gltf.json.extensionsUsed && gltf.json.extensionsUsed.includes('MAPBOX_mesh_features');
            const parameters = new index.k(this.zoom, { brightness: this.brightness });
            for (const sourceLayerId in layerFamilies) {
                for (const family of layerFamilies[sourceLayerId]) {
                    const layer = family[0];
                    const extensions = gltf.json.extensionsUsed;
                    layer.recalculate(parameters, []);
                    const bucket = new index.T(nodes, tileID, extensions && extensions.includes('MAPBOX_mesh_features'), this.brightness);
                    // Upload to GPU without waiting for evaluation if we are in diffuse path
                    if (!hasMapboxMeshFeatures)
                        bucket.needsUpload = true;
                    buckets[layer.fqid] = bucket;
                    // do the first evaluation in the worker to avoid stuttering
                    // $FlowIgnore[incompatible-call] layer here is always a ModelStyleLayer
                    bucket.evaluate(layer);
                }
            }
            this.status = 'done';
            // $FlowFixMe flow is complaining about missing properties and buckets not being of type Array
            callback(null, {
                buckets,
                featureIndex
            });
        }).catch(err => callback(new Error(err.message)));
    }
}
// $FlowIgnore[prop-missing] we don't need all Worker source properties
class Tiled3dModelWorkerSource {
    constructor(actor, layerIndex, availableImages, isSpriteLoaded, loadVectorData, brightness) {
        this.actor = actor;
        this.layerIndex = layerIndex;
        this.brightness = brightness;
        this.loading = {};
        this.loaded = {};
    }
    loadTile(params, callback) {
        const uid = params.uid;
        const workerTile = this.loading[uid] = new Tiled3dWorkerTile(params, this.brightness);
        index.i(params.request, (err, data) => {
            const aborted = !this.loading[uid];
            delete this.loading[uid];
            if (aborted || err) {
                workerTile.status = 'done';
                if (!aborted)
                    this.loaded[uid] = workerTile;
                return callback(err);
            }
            if (!data || data.byteLength === 0) {
                workerTile.status = 'done';
                this.loaded[uid] = workerTile;
                return callback();
            }
            const workerTileCallback = (err, result) => {
                workerTile.status = 'done';
                this.loaded = this.loaded || {};
                this.loaded[uid] = workerTile;
                if (err || !result)
                    callback(err);
                else
                    callback(null, result);
            };
            workerTile.parse(data, this.layerIndex, params, workerTileCallback);
        });
    }
    /**
     * Re-parses a tile that has already been loaded.  Yields the same data as
     * {@link WorkerSource#loadTile}.
     */
    // eslint-disable-next-line no-unused-vars
    reloadTile(params, callback) {
        const loaded = this.loaded;
        const uid = params.uid;
        if (loaded && loaded[uid]) {
            const workerTile = loaded[uid];
            workerTile.projection = params.projection;
            workerTile.brightness = params.brightness;
            const done = (err, data) => {
                const reloadCallback = workerTile.reloadCallback;
                if (reloadCallback) {
                    delete workerTile.reloadCallback;
                    this.loadTile(params, callback);
                }
                callback(err, data);
            };
            if (workerTile.status === 'parsing') {
                workerTile.reloadCallback = done;
            } else if (workerTile.status === 'done') {
                // do the request again
                this.loadTile(params, callback);
            }
        }
    }
    /**
     * Aborts loading a tile that is in progress.
     */
    // eslint-disable-next-line no-unused-vars
    abortTile(params, callback) {
        const uid = params.uid;
        const tile = this.loading[uid];
        if (tile) {
            delete this.loading[uid];
        }
        callback();
    }
    /**
     * Removes this tile from any local caches.
     */
    // eslint-disable-next-line no-unused-vars
    removeTile(params, callback) {
        const loaded = this.loaded, uid = params.uid;
        if (loaded && loaded[uid]) {
            delete loaded[uid];
        }
        callback();
    }
}

//      
/**
 * @private
 */
class Worker {
    constructor(self) {
        this.self = self;
        this.actor = new index.A(self, this);
        this.layerIndexes = {};
        this.availableImages = {};
        this.isSpriteLoaded = {};
        this.projections = {};
        this.defaultProjection = index.m({ name: 'mercator' });
        this.workerSourceTypes = {
            vector: index.d,
            geojson: GeoJSONWorkerSource,
            'batched-model': Tiled3dModelWorkerSource
        };
        // [mapId][scope][sourceType][sourceName] => worker source instance
        this.workerSources = {};
        this.demWorkerSources = {};
        this.self.registerWorkerSource = (name, WorkerSource) => {
            if (this.workerSourceTypes[name]) {
                throw new Error(`Worker source with name "${ name }" already registered.`);
            }
            this.workerSourceTypes[name] = WorkerSource;
        };
        // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed.
        this.self.registerRTLTextPlugin = rtlTextPlugin => {
            if (index.n.isParsed()) {
                throw new Error('RTL text plugin already registered.');
            }
            index.n['applyArabicShaping'] = rtlTextPlugin.applyArabicShaping;
            index.n['processBidirectionalText'] = rtlTextPlugin.processBidirectionalText;
            index.n['processStyledBidirectionalText'] = rtlTextPlugin.processStyledBidirectionalText;
        };
    }
    clearCaches(mapId, unused, callback) {
        delete this.layerIndexes[mapId];
        delete this.availableImages[mapId];
        delete this.workerSources[mapId];
        delete this.demWorkerSources[mapId];
        callback();
    }
    checkIfReady(mapID, unused, callback) {
        // noop, used to check if a worker is fully set up and ready to receive messages
        callback();
    }
    setReferrer(mapID, referrer) {
        this.referrer = referrer;
    }
    spriteLoaded(mapId, {scope, isLoaded}) {
        if (!this.isSpriteLoaded[mapId])
            this.isSpriteLoaded[mapId] = {};
        this.isSpriteLoaded[mapId][scope] = isLoaded;
        if (!this.workerSources[mapId] || !this.workerSources[mapId][scope]) {
            return;
        }
        for (const workerSource in this.workerSources[mapId][scope]) {
            const ws = this.workerSources[mapId][scope][workerSource];
            for (const source in ws) {
                if (ws[source] instanceof index.d) {
                    ws[source].isSpriteLoaded = isLoaded;
                    ws[source].fire(new index.o('isSpriteLoaded'));
                }
            }
        }
    }
    setImages(mapId, {scope, images}, callback) {
        if (!this.availableImages[mapId]) {
            this.availableImages[mapId] = {};
        }
        this.availableImages[mapId][scope] = images;
        if (!this.workerSources[mapId] || !this.workerSources[mapId][scope]) {
            callback();
            return;
        }
        for (const workerSource in this.workerSources[mapId][scope]) {
            const ws = this.workerSources[mapId][scope][workerSource];
            for (const source in ws) {
                ws[source].availableImages = images;
            }
        }
        callback();
    }
    setProjection(mapId, config) {
        this.projections[mapId] = index.m(config);
    }
    setBrightness(mapId, brightness, callback) {
        this.brightness = brightness;
        callback();
    }
    setLayers(mapId, params, callback) {
        this.getLayerIndex(mapId, params.scope).replace(params.layers, params.options);
        callback();
    }
    updateLayers(mapId, params, callback) {
        this.getLayerIndex(mapId, params.scope).update(params.layers, params.removedIds, params.options);
        callback();
    }
    loadTile(mapId, params, callback) {
        params.projection = this.projections[mapId] || this.defaultProjection;
        this.getWorkerSource(mapId, params.type, params.source, params.scope).loadTile(params, callback);
    }
    loadDEMTile(mapId, params, callback) {
        this.getDEMWorkerSource(mapId, params.source, params.scope).loadTile(params, callback);
    }
    reloadTile(mapId, params, callback) {
        params.projection = this.projections[mapId] || this.defaultProjection;
        this.getWorkerSource(mapId, params.type, params.source, params.scope).reloadTile(params, callback);
    }
    abortTile(mapId, params, callback) {
        this.getWorkerSource(mapId, params.type, params.source, params.scope).abortTile(params, callback);
    }
    removeTile(mapId, params, callback) {
        this.getWorkerSource(mapId, params.type, params.source, params.scope).removeTile(params, callback);
    }
    removeSource(mapId, params, callback) {
        if (!this.workerSources[mapId] || !this.workerSources[mapId][params.scope] || !this.workerSources[mapId][params.scope][params.type] || !this.workerSources[mapId][params.scope][params.type][params.source]) {
            return;
        }
        const worker = this.workerSources[mapId][params.scope][params.type][params.source];
        delete this.workerSources[mapId][params.scope][params.type][params.source];
        if (worker.removeSource !== undefined) {
            worker.removeSource(params, callback);
        } else {
            callback();
        }
    }
    /**
     * Load a {@link WorkerSource} script at params.url.  The script is run
     * (using importScripts) with `registerWorkerSource` in scope, which is a
     * function taking `(name, workerSourceObject)`.
     *  @private
     */
    loadWorkerSource(map, params, callback) {
        try {
            this.self.importScripts(params.url);
            callback();
        } catch (e) {
            callback(e.toString());
        }
    }
    syncRTLPluginState(map, state, callback) {
        try {
            index.n.setState(state);
            const pluginURL = index.n.getPluginURL();
            if (index.n.isLoaded() && !index.n.isParsed() && pluginURL != null    // Not possible when `isLoaded` is true, but keeps flow happy
) {
                this.self.importScripts(pluginURL);
                const complete = index.n.isParsed();
                const error = complete ? undefined : new Error(`RTL Text Plugin failed to import scripts from ${ pluginURL }`);
                callback(error, complete);
            }
        } catch (e) {
            callback(e.toString());
        }
    }
    setDracoUrl(map, dracoUrl) {
        this.dracoUrl = dracoUrl;
    }
    getAvailableImages(mapId, scope) {
        if (!this.availableImages[mapId]) {
            this.availableImages[mapId] = {};
        }
        let availableImages = this.availableImages[mapId][scope];
        if (!availableImages) {
            availableImages = [];
        }
        return availableImages;
    }
    getLayerIndex(mapId, scope) {
        if (!this.layerIndexes[mapId]) {
            this.layerIndexes[mapId] = {};
        }
        let layerIndex = this.layerIndexes[mapId][scope];
        if (!layerIndex) {
            layerIndex = this.layerIndexes[mapId][scope] = new StyleLayerIndex();
            layerIndex.scope = scope;
        }
        return layerIndex;
    }
    getWorkerSource(mapId, type, source, scope) {
        if (!this.workerSources[mapId])
            this.workerSources[mapId] = {};
        if (!this.workerSources[mapId][scope])
            this.workerSources[mapId][scope] = {};
        if (!this.workerSources[mapId][scope][type])
            this.workerSources[mapId][scope][type] = {};
        if (!this.isSpriteLoaded[mapId])
            this.isSpriteLoaded[mapId] = {};
        if (!this.workerSources[mapId][scope][type][source]) {
            // use a wrapped actor so that we can attach a target mapId param
            // to any messages invoked by the WorkerSource
            const actor = {
                send: (type, data, callback, _, mustQueue, metadata) => {
                    this.actor.send(type, data, callback, mapId, mustQueue, metadata);
                },
                scheduler: this.actor.scheduler
            };
            this.workerSources[mapId][scope][type][source] = new this.workerSourceTypes[type](actor, this.getLayerIndex(mapId, scope), this.getAvailableImages(mapId, scope), this.isSpriteLoaded[mapId][scope], undefined, this.brightness);
        }
        return this.workerSources[mapId][scope][type][source];
    }
    getDEMWorkerSource(mapId, source, scope) {
        if (!this.demWorkerSources[mapId])
            this.demWorkerSources[mapId] = {};
        if (!this.demWorkerSources[mapId][scope])
            this.demWorkerSources[mapId][scope] = {};
        if (!this.demWorkerSources[mapId][scope][source]) {
            this.demWorkerSources[mapId][scope][source] = new RasterDEMTileWorkerSource();
        }
        return this.demWorkerSources[mapId][scope][source];
    }
    enforceCacheSizeLimit(mapId, limit) {
        index.q(limit);
    }
    getWorkerPerformanceMetrics(mapId, params, callback) {
        callback(undefined, void 0);
    }
}
/* global self, WorkerGlobalScope */
if (typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope) {
    // $FlowFixMe[prop-missing]
    self.worker = new Worker(self);
}

return Worker;

}));

define(['./shared'], (function (index) { 'use strict';



return index.s;

}));

//
// Our custom intro provides a specialized "define()" function, called by the
// AMD modules below, that sets up the worker blob URL and then executes the
// main module, storing its exported value as 'mapboxgl'


var mapboxgl$1 = mapboxgl;

return mapboxgl$1;

}));
//# sourceMappingURL=mapbox-gl-unminified.js.map
