/* 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';

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

var cjs = {};

var common = {};

var hasRequiredCommon;

function requireCommon () {
	if (hasRequiredCommon) return common;
	hasRequiredCommon = 1;
	Object.defineProperty(common, '__esModule', { value: true });
	common.setMatrixArrayType = setMatrixArrayType;
	common.toRadian = toRadian;
	common.equals = equals;
	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, 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);
	    };
	return common;
}

var mat2 = {};

var hasRequiredMat2;

function requireMat2 () {
	if (hasRequiredMat2) return mat2;
	hasRequiredMat2 = 1;
	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(mat2, '__esModule', { value: true });
	mat2.create = create;
	mat2.clone = clone;
	mat2.copy = copy;
	mat2.identity = identity;
	mat2.fromValues = fromValues;
	mat2.set = set;
	mat2.transpose = transpose;
	mat2.invert = invert;
	mat2.adjoint = adjoint;
	mat2.determinant = determinant;
	mat2.multiply = multiply;
	mat2.rotate = rotate;
	mat2.scale = scale;
	mat2.fromRotation = fromRotation;
	mat2.fromScaling = fromScaling;
	mat2.str = str;
	mat2.frob = frob;
	mat2.LDU = LDU;
	mat2.add = add;
	mat2.subtract = subtract;
	mat2.exactEquals = exactEquals;
	mat2.equals = equals;
	mat2.multiplyScalar = multiplyScalar;
	mat2.multiplyScalarAndAdd = multiplyScalarAndAdd;
	mat2.sub = mat2.mul = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 2x2 Matrix
	 * @module mat2
	 */
	/**
	 * Creates a new identity mat2
	 *
	 * @returns {mat2} a new 2x2 matrix
	 */
	function create() {
	    var out = new glMatrix.ARRAY_TYPE(4);
	    if (glMatrix.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(a) {
	    var out = new glMatrix.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(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(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(m00, m01, m10, m11) {
	    var out = new glMatrix.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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.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(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(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 = multiply;
	/**
	 * Alias for {@link mat2.subtract}
	 * @function
	 */
	mat2.mul = mul;
	var sub = subtract;
	mat2.sub = sub;
	return mat2;
}

var mat2d = {};

var hasRequiredMat2d;

function requireMat2d () {
	if (hasRequiredMat2d) return mat2d;
	hasRequiredMat2d = 1;
	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(mat2d, '__esModule', { value: true });
	mat2d.create = create;
	mat2d.clone = clone;
	mat2d.copy = copy;
	mat2d.identity = identity;
	mat2d.fromValues = fromValues;
	mat2d.set = set;
	mat2d.invert = invert;
	mat2d.determinant = determinant;
	mat2d.multiply = multiply;
	mat2d.rotate = rotate;
	mat2d.scale = scale;
	mat2d.translate = translate;
	mat2d.fromRotation = fromRotation;
	mat2d.fromScaling = fromScaling;
	mat2d.fromTranslation = fromTranslation;
	mat2d.str = str;
	mat2d.frob = frob;
	mat2d.add = add;
	mat2d.subtract = subtract;
	mat2d.multiplyScalar = multiplyScalar;
	mat2d.multiplyScalarAndAdd = multiplyScalarAndAdd;
	mat2d.exactEquals = exactEquals;
	mat2d.equals = equals;
	mat2d.sub = mat2d.mul = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 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() {
	    var out = new glMatrix.ARRAY_TYPE(6);
	    if (glMatrix.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(a) {
	    var out = new glMatrix.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(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(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(a, b, c, d, tx, ty) {
	    var out = new glMatrix.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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5));
	}
	/**
	 * Alias for {@link mat2d.multiply}
	 * @function
	 */
	var mul = multiply;
	/**
	 * Alias for {@link mat2d.subtract}
	 * @function
	 */
	mat2d.mul = mul;
	var sub = subtract;
	mat2d.sub = sub;
	return mat2d;
}

var mat3 = {};

var hasRequiredMat3;

function requireMat3 () {
	if (hasRequiredMat3) return mat3;
	hasRequiredMat3 = 1;
	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(mat3, '__esModule', { value: true });
	mat3.create = create;
	mat3.fromMat4 = fromMat4;
	mat3.clone = clone;
	mat3.copy = copy;
	mat3.fromValues = fromValues;
	mat3.set = set;
	mat3.identity = identity;
	mat3.transpose = transpose;
	mat3.invert = invert;
	mat3.adjoint = adjoint;
	mat3.determinant = determinant;
	mat3.multiply = multiply;
	mat3.translate = translate;
	mat3.rotate = rotate;
	mat3.scale = scale;
	mat3.fromTranslation = fromTranslation;
	mat3.fromRotation = fromRotation;
	mat3.fromScaling = fromScaling;
	mat3.fromMat2d = fromMat2d;
	mat3.fromQuat = fromQuat;
	mat3.normalFromMat4 = normalFromMat4;
	mat3.projection = projection;
	mat3.str = str;
	mat3.frob = frob;
	mat3.add = add;
	mat3.subtract = subtract;
	mat3.multiplyScalar = multiplyScalar;
	mat3.multiplyScalarAndAdd = multiplyScalarAndAdd;
	mat3.exactEquals = exactEquals;
	mat3.equals = equals;
	mat3.sub = mat3.mul = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 3x3 Matrix
	 * @module mat3
	 */
	/**
	 * Creates a new identity mat3
	 *
	 * @returns {mat3} a new 3x3 matrix
	 */
	function create() {
	    var out = new glMatrix.ARRAY_TYPE(9);
	    if (glMatrix.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(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(a) {
	    var out = new glMatrix.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(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(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
	    var out = new glMatrix.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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8));
	}
	/**
	 * Alias for {@link mat3.multiply}
	 * @function
	 */
	var mul = multiply;
	/**
	 * Alias for {@link mat3.subtract}
	 * @function
	 */
	mat3.mul = mul;
	var sub = subtract;
	mat3.sub = sub;
	return mat3;
}

var mat4 = {};

var hasRequiredMat4;

function requireMat4 () {
	if (hasRequiredMat4) return mat4;
	hasRequiredMat4 = 1;
	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(mat4, '__esModule', { value: true });
	mat4.create = create;
	mat4.clone = clone;
	mat4.copy = copy;
	mat4.fromValues = fromValues;
	mat4.set = set;
	mat4.identity = identity;
	mat4.transpose = transpose;
	mat4.invert = invert;
	mat4.adjoint = adjoint;
	mat4.determinant = determinant;
	mat4.multiply = multiply;
	mat4.translate = translate;
	mat4.scale = scale;
	mat4.rotate = rotate;
	mat4.rotateX = rotateX;
	mat4.rotateY = rotateY;
	mat4.rotateZ = rotateZ;
	mat4.fromTranslation = fromTranslation;
	mat4.fromScaling = fromScaling;
	mat4.fromRotation = fromRotation;
	mat4.fromXRotation = fromXRotation;
	mat4.fromYRotation = fromYRotation;
	mat4.fromZRotation = fromZRotation;
	mat4.fromRotationTranslation = fromRotationTranslation;
	mat4.fromQuat2 = fromQuat2;
	mat4.getTranslation = getTranslation;
	mat4.getScaling = getScaling;
	mat4.getRotation = getRotation;
	mat4.fromRotationTranslationScale = fromRotationTranslationScale;
	mat4.fromRotationTranslationScaleOrigin = fromRotationTranslationScaleOrigin;
	mat4.fromQuat = fromQuat;
	mat4.frustum = frustum;
	mat4.perspectiveNO = perspectiveNO;
	mat4.perspectiveZO = perspectiveZO;
	mat4.perspectiveFromFieldOfView = perspectiveFromFieldOfView;
	mat4.orthoNO = orthoNO;
	mat4.orthoZO = orthoZO;
	mat4.lookAt = lookAt;
	mat4.targetTo = targetTo;
	mat4.str = str;
	mat4.frob = frob;
	mat4.add = add;
	mat4.subtract = subtract;
	mat4.multiplyScalar = multiplyScalar;
	mat4.multiplyScalarAndAdd = multiplyScalarAndAdd;
	mat4.exactEquals = exactEquals;
	mat4.equals = equals;
	mat4.sub = mat4.mul = mat4.ortho = mat4.perspective = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 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() {
	    var out = new glMatrix.ARRAY_TYPE(16);
	    if (glMatrix.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(a) {
	    var out = new glMatrix.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(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(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
	    var out = new glMatrix.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(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(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(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(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(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(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(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.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(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(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(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(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(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.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(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.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(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(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.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.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.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.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {
	        return identity(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(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(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1, Math.abs(a15), Math.abs(b15));
	}
	/**
	 * Alias for {@link mat4.multiply}
	 * @function
	 */
	var mul = multiply;
	/**
	 * Alias for {@link mat4.subtract}
	 * @function
	 */
	mat4.mul = mul;
	var sub = subtract;
	mat4.sub = sub;
	return mat4;
}

var quat = {};

var vec3 = {};

var hasRequiredVec3;

function requireVec3 () {
	if (hasRequiredVec3) return vec3;
	hasRequiredVec3 = 1;
	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(vec3, '__esModule', { value: true });
	vec3.create = create;
	vec3.clone = clone;
	vec3.length = length;
	vec3.fromValues = fromValues;
	vec3.copy = copy;
	vec3.set = set;
	vec3.add = add;
	vec3.subtract = subtract;
	vec3.multiply = multiply;
	vec3.divide = divide;
	vec3.ceil = ceil;
	vec3.floor = floor;
	vec3.min = min;
	vec3.max = max;
	vec3.round = round;
	vec3.scale = scale;
	vec3.scaleAndAdd = scaleAndAdd;
	vec3.distance = distance;
	vec3.squaredDistance = squaredDistance;
	vec3.squaredLength = squaredLength;
	vec3.negate = negate;
	vec3.inverse = inverse;
	vec3.normalize = normalize;
	vec3.dot = dot;
	vec3.cross = cross;
	vec3.lerp = lerp;
	vec3.hermite = hermite;
	vec3.bezier = bezier;
	vec3.random = random;
	vec3.transformMat4 = transformMat4;
	vec3.transformMat3 = transformMat3;
	vec3.transformQuat = transformQuat;
	vec3.rotateX = rotateX;
	vec3.rotateY = rotateY;
	vec3.rotateZ = rotateZ;
	vec3.angle = angle;
	vec3.zero = zero;
	vec3.str = str;
	vec3.exactEquals = exactEquals;
	vec3.equals = equals;
	vec3.forEach = vec3.sqrLen = vec3.len = vec3.sqrDist = vec3.dist = vec3.div = vec3.mul = vec3.sub = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 3 Dimensional Vector
	 * @module vec3
	 */
	/**
	 * Creates a new, empty vec3
	 *
	 * @returns {vec3} a new 3D vector
	 */
	function create() {
	    var out = new glMatrix.ARRAY_TYPE(3);
	    if (glMatrix.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(a) {
	    var out = new glMatrix.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(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(x, y, z) {
	    var out = new glMatrix.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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(out, scale) {
	    scale = scale || 1;
	    var r = glMatrix.RANDOM() * 2 * Math.PI;
	    var z = glMatrix.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(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(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(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(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(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(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(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(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(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2));
	}
	/**
	 * Alias for {@link vec3.subtract}
	 * @function
	 */
	var sub = subtract;
	/**
	 * Alias for {@link vec3.multiply}
	 * @function
	 */
	vec3.sub = sub;
	var mul = multiply;
	/**
	 * Alias for {@link vec3.divide}
	 * @function
	 */
	vec3.mul = mul;
	var div = divide;
	/**
	 * Alias for {@link vec3.distance}
	 * @function
	 */
	vec3.div = div;
	var dist = distance;
	/**
	 * Alias for {@link vec3.squaredDistance}
	 * @function
	 */
	vec3.dist = dist;
	var sqrDist = squaredDistance;
	/**
	 * Alias for {@link vec3.length}
	 * @function
	 */
	vec3.sqrDist = sqrDist;
	var len = length;
	/**
	 * Alias for {@link vec3.squaredLength}
	 * @function
	 */
	vec3.len = len;
	var sqrLen = squaredLength;
	/**
	 * 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.sqrLen = sqrLen;
	var forEach = (function () {
	    var vec = create();
	    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.forEach = forEach;
	return vec3;
}

var vec4 = {};

var hasRequiredVec4;

function requireVec4 () {
	if (hasRequiredVec4) return vec4;
	hasRequiredVec4 = 1;
	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(vec4, '__esModule', { value: true });
	vec4.create = create;
	vec4.clone = clone;
	vec4.fromValues = fromValues;
	vec4.copy = copy;
	vec4.set = set;
	vec4.add = add;
	vec4.subtract = subtract;
	vec4.multiply = multiply;
	vec4.divide = divide;
	vec4.ceil = ceil;
	vec4.floor = floor;
	vec4.min = min;
	vec4.max = max;
	vec4.round = round;
	vec4.scale = scale;
	vec4.scaleAndAdd = scaleAndAdd;
	vec4.distance = distance;
	vec4.squaredDistance = squaredDistance;
	vec4.length = length;
	vec4.squaredLength = squaredLength;
	vec4.negate = negate;
	vec4.inverse = inverse;
	vec4.normalize = normalize;
	vec4.dot = dot;
	vec4.cross = cross;
	vec4.lerp = lerp;
	vec4.random = random;
	vec4.transformMat4 = transformMat4;
	vec4.transformQuat = transformQuat;
	vec4.zero = zero;
	vec4.str = str;
	vec4.exactEquals = exactEquals;
	vec4.equals = equals;
	vec4.forEach = vec4.sqrLen = vec4.len = vec4.sqrDist = vec4.dist = vec4.div = vec4.mul = vec4.sub = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 4 Dimensional Vector
	 * @module vec4
	 */
	/**
	 * Creates a new, empty vec4
	 *
	 * @returns {vec4} a new 4D vector
	 */
	function create() {
	    var out = new glMatrix.ARRAY_TYPE(4);
	    if (glMatrix.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(a) {
	    var out = new glMatrix.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(x, y, z, w) {
	    var out = new glMatrix.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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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.RANDOM() * 2 - 1;
	        v2 = glMatrix.RANDOM() * 2 - 1;
	        s1 = v1 * v1 + v2 * v2;
	    } while (s1 >= 1);
	    do {
	        v3 = glMatrix.RANDOM() * 2 - 1;
	        v4 = glMatrix.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(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(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3));
	}
	/**
	 * Alias for {@link vec4.subtract}
	 * @function
	 */
	var sub = subtract;
	/**
	 * Alias for {@link vec4.multiply}
	 * @function
	 */
	vec4.sub = sub;
	var mul = multiply;
	/**
	 * Alias for {@link vec4.divide}
	 * @function
	 */
	vec4.mul = mul;
	var div = divide;
	/**
	 * Alias for {@link vec4.distance}
	 * @function
	 */
	vec4.div = div;
	var dist = distance;
	/**
	 * Alias for {@link vec4.squaredDistance}
	 * @function
	 */
	vec4.dist = dist;
	var sqrDist = squaredDistance;
	/**
	 * Alias for {@link vec4.length}
	 * @function
	 */
	vec4.sqrDist = sqrDist;
	var len = length;
	/**
	 * Alias for {@link vec4.squaredLength}
	 * @function
	 */
	vec4.len = len;
	var sqrLen = squaredLength;
	/**
	 * 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.sqrLen = sqrLen;
	var forEach = (function () {
	    var vec = create();
	    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.forEach = forEach;
	return vec4;
}

var hasRequiredQuat;

function requireQuat () {
	if (hasRequiredQuat) return quat;
	hasRequiredQuat = 1;
	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(quat, '__esModule', { value: true });
	quat.create = create;
	quat.identity = identity;
	quat.setAxisAngle = setAxisAngle;
	quat.getAxisAngle = getAxisAngle;
	quat.getAngle = getAngle;
	quat.multiply = multiply;
	quat.rotateX = rotateX;
	quat.rotateY = rotateY;
	quat.rotateZ = rotateZ;
	quat.calculateW = calculateW;
	quat.exp = exp;
	quat.ln = ln;
	quat.pow = pow;
	quat.slerp = slerp;
	quat.random = random;
	quat.invert = invert;
	quat.conjugate = conjugate;
	quat.fromMat3 = fromMat3;
	quat.fromEuler = fromEuler;
	quat.str = str;
	quat.setAxes = quat.sqlerp = quat.rotationTo = quat.equals = quat.exactEquals = quat.normalize = quat.sqrLen = quat.squaredLength = quat.len = quat.length = quat.lerp = quat.dot = quat.scale = quat.mul = quat.add = quat.set = quat.copy = quat.fromValues = quat.clone = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	var mat3 = _interopRequireWildcard(requireMat3());
	var vec3 = _interopRequireWildcard(requireVec3());
	var vec4 = _interopRequireWildcard(requireVec4());
	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 (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;
	}
	/**
	 * Quaternion
	 * @module quat
	 */
	/**
	 * Creates a new identity quat
	 *
	 * @returns {quat} a new quaternion
	 */
	function create() {
	    var out = new glMatrix.ARRAY_TYPE(4);
	    if (glMatrix.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(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.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(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(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(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(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(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(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(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.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(out) {
	    // Implementation of http://planning.cs.uiuc.edu/node198.html
	    // TODO: Calling random 3 times is probably not the fastest solution
	    var u1 = glMatrix.RANDOM();
	    var u2 = glMatrix.RANDOM();
	    var u3 = glMatrix.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(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(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(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 = vec4.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.clone = clone;
	var fromValues = vec4.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.fromValues = fromValues;
	var copy = vec4.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.copy = copy;
	var set = vec4.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.set = set;
	var add = vec4.add;
	/**
	 * Alias for {@link quat.multiply}
	 * @function
	 */
	quat.add = add;
	var mul = multiply;
	/**
	 * 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.mul = mul;
	var scale = vec4.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.scale = scale;
	var dot = vec4.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.dot = dot;
	var lerp = vec4.lerp;
	/**
	 * Calculates the length of a quat
	 *
	 * @param {ReadonlyQuat} a vector to calculate length of
	 * @returns {Number} length of a
	 */
	quat.lerp = lerp;
	var length = vec4.length;
	/**
	 * Alias for {@link quat.length}
	 * @function
	 */
	quat.length = length;
	var len = length;
	/**
	 * Calculates the squared length of a quat
	 *
	 * @param {ReadonlyQuat} a vector to calculate squared length of
	 * @returns {Number} squared length of a
	 * @function
	 */
	quat.len = len;
	var squaredLength = vec4.squaredLength;
	/**
	 * Alias for {@link quat.squaredLength}
	 * @function
	 */
	quat.squaredLength = squaredLength;
	var sqrLen = squaredLength;
	/**
	 * Normalize a quat
	 *
	 * @param {quat} out the receiving quaternion
	 * @param {ReadonlyQuat} a quaternion to normalize
	 * @returns {quat} out
	 * @function
	 */
	quat.sqrLen = sqrLen;
	var normalize = vec4.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.normalize = normalize;
	var exactEquals = vec4.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.exactEquals = exactEquals;
	var equals = vec4.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.equals = equals;
	var rotationTo = (function () {
	    var tmpvec3 = vec3.create();
	    var xUnitVec3 = vec3.fromValues(1, 0, 0);
	    var yUnitVec3 = vec3.fromValues(0, 1, 0);
	    return function (out, a, b) {
	        var dot = vec3.dot(a, b);
	        if (dot < -0.999999) {
	            vec3.cross(tmpvec3, xUnitVec3, a);
	            if (vec3.len(tmpvec3) < 0.000001)
	                vec3.cross(tmpvec3, yUnitVec3, a);
	            vec3.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.cross(tmpvec3, a, b);
	            out[0] = tmpvec3[0];
	            out[1] = tmpvec3[1];
	            out[2] = tmpvec3[2];
	            out[3] = 1 + dot;
	            return normalize(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.rotationTo = rotationTo;
	var sqlerp = (function () {
	    var temp1 = create();
	    var temp2 = create();
	    return function (out, a, b, c, d, t) {
	        slerp(temp1, a, d, t);
	        slerp(temp2, b, c, t);
	        slerp(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.sqlerp = sqlerp;
	var setAxes = (function () {
	    var matr = mat3.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(out, fromMat3(out, matr));
	    };
	}());
	quat.setAxes = setAxes;
	return quat;
}

var quat2 = {};

var hasRequiredQuat2;

function requireQuat2 () {
	if (hasRequiredQuat2) return quat2;
	hasRequiredQuat2 = 1;
	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(quat2, '__esModule', { value: true });
	quat2.create = create;
	quat2.clone = clone;
	quat2.fromValues = fromValues;
	quat2.fromRotationTranslationValues = fromRotationTranslationValues;
	quat2.fromRotationTranslation = fromRotationTranslation;
	quat2.fromTranslation = fromTranslation;
	quat2.fromRotation = fromRotation;
	quat2.fromMat4 = fromMat4;
	quat2.copy = copy;
	quat2.identity = identity;
	quat2.set = set;
	quat2.getDual = getDual;
	quat2.setDual = setDual;
	quat2.getTranslation = getTranslation;
	quat2.translate = translate;
	quat2.rotateX = rotateX;
	quat2.rotateY = rotateY;
	quat2.rotateZ = rotateZ;
	quat2.rotateByQuatAppend = rotateByQuatAppend;
	quat2.rotateByQuatPrepend = rotateByQuatPrepend;
	quat2.rotateAroundAxis = rotateAroundAxis;
	quat2.add = add;
	quat2.multiply = multiply;
	quat2.scale = scale;
	quat2.lerp = lerp;
	quat2.invert = invert;
	quat2.conjugate = conjugate;
	quat2.normalize = normalize;
	quat2.str = str;
	quat2.exactEquals = exactEquals;
	quat2.equals = equals;
	quat2.sqrLen = quat2.squaredLength = quat2.len = quat2.length = quat2.dot = quat2.mul = quat2.setReal = quat2.getReal = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	var quat = _interopRequireWildcard(requireQuat());
	var mat4 = _interopRequireWildcard(requireMat4());
	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 (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;
	}
	/**
	 * 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() {
	    var dq = new glMatrix.ARRAY_TYPE(8);
	    if (glMatrix.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(a) {
	    var dq = new glMatrix.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(x1, y1, z1, w1, x2, y2, z2, w2) {
	    var dq = new glMatrix.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.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.create();
	    mat4.getRotation(outer, a);
	    var t = new glMatrix.ARRAY_TYPE(3);
	    mat4.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(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(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(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.copy;
	/**
	 * Gets the dual part of a dual quat
	 * @param  {quat} out dual part
	 * @param  {ReadonlyQuat2} a Dual Quaternion
	 * @return {quat} dual part
	 */
	quat2.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.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.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(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.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.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.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.EPSILON) {
	        return copy(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(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(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 = multiply;
	/**
	 * 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.mul = mul;
	function scale(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 = quat.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.dot = dot;
	function lerp(out, a, b, t) {
	    var mt = 1 - t;
	    if (dot(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(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 = quat.length;
	/**
	 * Alias for {@link quat2.length}
	 * @function
	 */
	quat2.length = length;
	var len = length;
	/**
	 * 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.len = len;
	var squaredLength = quat.squaredLength;
	/**
	 * Alias for {@link quat2.squaredLength}
	 * @function
	 */
	quat2.squaredLength = squaredLength;
	var sqrLen = squaredLength;
	/**
	 * Normalize a dual quat
	 *
	 * @param {quat2} out the receiving dual quaternion
	 * @param {ReadonlyQuat2} a dual quaternion to normalize
	 * @returns {quat2} out
	 * @function
	 */
	quat2.sqrLen = sqrLen;
	function normalize(out, a) {
	    var magnitude = squaredLength(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(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(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(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.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7));
	}
	return quat2;
}

var vec2 = {};

var hasRequiredVec2;

function requireVec2 () {
	if (hasRequiredVec2) return vec2;
	hasRequiredVec2 = 1;
	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(vec2, '__esModule', { value: true });
	vec2.create = create;
	vec2.clone = clone;
	vec2.fromValues = fromValues;
	vec2.copy = copy;
	vec2.set = set;
	vec2.add = add;
	vec2.subtract = subtract;
	vec2.multiply = multiply;
	vec2.divide = divide;
	vec2.ceil = ceil;
	vec2.floor = floor;
	vec2.min = min;
	vec2.max = max;
	vec2.round = round;
	vec2.scale = scale;
	vec2.scaleAndAdd = scaleAndAdd;
	vec2.distance = distance;
	vec2.squaredDistance = squaredDistance;
	vec2.length = length;
	vec2.squaredLength = squaredLength;
	vec2.negate = negate;
	vec2.inverse = inverse;
	vec2.normalize = normalize;
	vec2.dot = dot;
	vec2.cross = cross;
	vec2.lerp = lerp;
	vec2.random = random;
	vec2.transformMat2 = transformMat2;
	vec2.transformMat2d = transformMat2d;
	vec2.transformMat3 = transformMat3;
	vec2.transformMat4 = transformMat4;
	vec2.rotate = rotate;
	vec2.angle = angle;
	vec2.zero = zero;
	vec2.str = str;
	vec2.exactEquals = exactEquals;
	vec2.equals = equals;
	vec2.forEach = vec2.sqrLen = vec2.sqrDist = vec2.dist = vec2.div = vec2.mul = vec2.sub = vec2.len = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	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 (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;
	}
	/**
	 * 2 Dimensional Vector
	 * @module vec2
	 */
	/**
	 * Creates a new, empty vec2
	 *
	 * @returns {vec2} a new 2D vector
	 */
	function create() {
	    var out = new glMatrix.ARRAY_TYPE(2);
	    if (glMatrix.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.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.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(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(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.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(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(a, b) {
	    var a0 = a[0], a1 = a[1];
	    var b0 = b[0], b1 = b[1];
	    return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.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.len = len;
	var sub = subtract;
	/**
	 * Alias for {@link vec2.multiply}
	 * @function
	 */
	vec2.sub = sub;
	var mul = multiply;
	/**
	 * Alias for {@link vec2.divide}
	 * @function
	 */
	vec2.mul = mul;
	var div = divide;
	/**
	 * Alias for {@link vec2.distance}
	 * @function
	 */
	vec2.div = div;
	var dist = distance;
	/**
	 * Alias for {@link vec2.squaredDistance}
	 * @function
	 */
	vec2.dist = dist;
	var sqrDist = squaredDistance;
	/**
	 * Alias for {@link vec2.squaredLength}
	 * @function
	 */
	vec2.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.sqrLen = sqrLen;
	var forEach = (function () {
	    var vec = create();
	    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.forEach = forEach;
	return vec2;
}

var hasRequiredCjs;

function requireCjs () {
	if (hasRequiredCjs) return cjs;
	hasRequiredCjs = 1;
	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 });
	cjs.vec4 = cjs.vec3 = cjs.vec2 = cjs.quat2 = cjs.quat = cjs.mat4 = cjs.mat3 = cjs.mat2d = cjs.mat2 = cjs.glMatrix = void 0;
	var glMatrix = _interopRequireWildcard(requireCommon());
	cjs.glMatrix = glMatrix;
	var mat2 = _interopRequireWildcard(requireMat2());
	cjs.mat2 = mat2;
	var mat2d = _interopRequireWildcard(requireMat2d());
	cjs.mat2d = mat2d;
	var mat3 = _interopRequireWildcard(requireMat3());
	cjs.mat3 = mat3;
	var mat4 = _interopRequireWildcard(requireMat4());
	cjs.mat4 = mat4;
	var quat = _interopRequireWildcard(requireQuat());
	cjs.quat = quat;
	var quat2 = _interopRequireWildcard(requireQuat2());
	cjs.quat2 = quat2;
	var vec2 = _interopRequireWildcard(requireVec2());
	cjs.vec2 = vec2;
	var vec3 = _interopRequireWildcard(requireVec3());
	cjs.vec3 = vec3;
	var vec4 = _interopRequireWildcard(requireVec4());
	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 (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;
	}
	return cjs;
}

var cjsExports = /*@__PURE__*/ requireCjs();

var unitbezier;
var hasRequiredUnitbezier;

function requireUnitbezier () {
	if (hasRequiredUnitbezier) return unitbezier;
	hasRequiredUnitbezier = 1;
	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));
	    }
	};
	return unitbezier;
}

var unitbezierExports = requireUnitbezier();
var UnitBezier = /*@__PURE__*/getDefaultExportFromCjs(unitbezierExports);

var pointGeometry;
var hasRequiredPointGeometry;

function requirePointGeometry () {
	if (hasRequiredPointGeometry) return pointGeometry;
	hasRequiredPointGeometry = 1;
	pointGeometry = Point;
	/**
	 * 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(x, y) {
	    this.x = x;
	    this.y = y;
	}
	Point.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(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.convert = function (a) {
	    if (a instanceof Point) {
	        return a;
	    }
	    if (Array.isArray(a)) {
	        return new Point(a[0], a[1]);
	    }
	    return a;
	};
	return pointGeometry;
}

var pointGeometryExports = requirePointGeometry();
var Point = /*@__PURE__*/getDefaultExportFromCjs(pointGeometryExports);

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;
function degToRad(a) {
    return a * DEG_TO_RAD;
}
function radToDeg(a) {
    return a * RAD_TO_DEG;
}
const TILE_CORNERS = [
    [
        0,
        0
    ],
    [
        1,
        0
    ],
    [
        1,
        1
    ],
    [
        0,
        1
    ]
];
function furthestTileCorner(bearing) {
    const alignedBearing = (bearing + 45 + 360) % 360;
    const cornerIdx = Math.round(alignedBearing / 90) % 4;
    return TILE_CORNERS[cornerIdx];
}
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);
}
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(minX, minY),
        max: new Point(maxX, maxY)
    };
}
function getAABBPointSquareDist(min, max, point) {
    let sqDist = 0;
    for (let i = 0; i < 2; ++i) {
        const v = 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;
}
function polygonizeBounds(min, max, buffer = 0, close = true) {
    const offset = new Point(buffer, buffer);
    const minBuf = min.sub(offset);
    const maxBuf = max.add(offset);
    const polygon = [
        minBuf,
        new Point(maxBuf.x, minBuf.y),
        maxBuf,
        new Point(minBuf.x, maxBuf.y)
    ];
    if (close) {
        polygon.push(minBuf.clone());
    }
    return polygon;
}
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);
        const offset = p1.add(p2).unit().mult(-1 * buffer / Math.sin(interiorAngle / 2));
        output.push(curr.add(offset));
    }
    return output;
}
function bezier(p1x, p1y, p2x, p2y) {
    const bezier2 = new UnitBezier(p1x, p1y, p2x, p2y);
    return function (t) {
        return bezier2.solve(t);
    };
}
const ease = bezier(0.25, 0.1, 0.25, 1);
function clamp(n, min, max) {
    return Math.min(max, Math.max(min, n));
}
function smoothstep(e0, e1, x) {
    x = clamp((x - e0) / (e1 - e0), 0, 1);
    return x * x * (3 - 2 * x);
}
function wrap$1(n, min, max) {
    const d = max - min;
    const w = ((n - min) % d + d) % d + min;
    return w === min ? max : w;
}
function shortestAngle(a, b) {
    const diff = (b - a + 180) % 360 - 180;
    return diff < -180 ? diff + 360 : diff;
}
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;
            if (--remaining === 0)
                callback(error, results);
        });
    });
}
function values(obj) {
    const result = [];
    for (const k in obj) {
        result.push(obj[k]);
    }
    return result;
}
function keysDifference(obj, other) {
    const difference = [];
    for (const i in obj) {
        if (!(i in other)) {
            difference.push(i);
        }
    }
    return difference;
}
function extend$1(dest, ...sources) {
    for (const src of sources) {
        for (const k in src) {
            dest[k] = src[k];
        }
    }
    return dest;
}
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;
function uniqueId() {
    return id++;
}
function uuid() {
    function b(a) {
        return a ? (a ^ Math.random() * (16 >> a / 4)).toString(16) : // @ts-expect-error - TS2365 - Operator '+' cannot be applied to types 'number[]' and 'number'.
        // eslint-disable-next-line
        ([10000000] + -[1000] + -4000 + -8000 + -100000000000).replace(/[018]/g, b);
    }
    return b();
}
function nextPowerOfTwo(value) {
    if (value <= 1)
        return 1;
    return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
}
function prevPowerOfTwo(value) {
    if (value <= 1)
        return 1;
    return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
}
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;
}
function bindAll(fns, context) {
    fns.forEach(fn => {
        if (!context[fn]) {
            return;
        }
        context[fn] = context[fn].bind(context);
    });
}
function endsWith(string, suffix) {
    return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
function mapObject(input, iterator, context) {
    const output = {};
    for (const key in input) {
        output[key] = iterator.call(this, input[key], key, input);
    }
    return output;
}
function filterObject(input, iterator, context) {
    const output = {};
    for (const key in input) {
        if (iterator.call(this, input[key], key, input)) {
            output[key] = input[key];
        }
    }
    return output;
}
function clone(input) {
    if (Array.isArray(input)) {
        return input.map(clone);
    } else if (typeof input === 'object' && input) {
        return mapObject(input, clone);
    } else {
        return input;
    }
}
function mapValue(value, min, max, outMin, outMax) {
    return clamp((value - min) / (max - min) * (outMax - outMin) + outMin, outMin, outMax);
}
function arraysIntersect(a, b) {
    for (let l = 0; l < a.length; l++) {
        if (b.indexOf(a[l]) >= 0)
            return true;
    }
    return false;
}
const warnOnceHistory = {};
function warnOnce(message) {
    if (!warnOnceHistory[message]) {
        if (typeof console !== 'undefined')
            console.warn(message);
        warnOnceHistory[message] = true;
    }
}
function isCounterClockwise(a, b, c) {
    return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
}
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;
}
function sphericalPositionToCartesian([r, azimuthal, polar]) {
    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
    };
}
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;
    let azimuthal = x !== 0 || y !== 0 ? Math.atan2(-y, -x) * RAD_TO_DEG + 90 : 0;
    if (azimuthal < 0) {
        azimuthal += 360;
    }
    return [
        radial,
        azimuthal,
        polar
    ];
}
function isWorker() {
    return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope;
}
function parseCacheControl(cacheControl) {
    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;
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;
    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 !!document.fullscreenElement || !!document.webkitFullscreenElement;
}
function storageAvailable(type) {
    try {
        const storage = self[type];
        storage.setItem('_mapbox_test_', 1);
        storage.removeItem('_mapbox_test_');
        return true;
    } catch (e) {
        return false;
    }
}
function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => {
        return String.fromCharCode(Number('0x' + p1));
    }));
}
function b64DecodeUnicode(str) {
    return decodeURIComponent(atob(str).split('').map(c => {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).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, values2) {
    matrix[col * 4 + 0] = values2[0];
    matrix[col * 4 + 1] = values2[1];
    matrix[col * 4 + 2] = values2[2];
    matrix[col * 4 + 3] = values2[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)
    ];
}
function lowerBound(array, startIndex, finishIndex, target) {
    while (startIndex < finishIndex) {
        const middleIndex = startIndex + finishIndex >> 1;
        if (array[middleIndex] < target) {
            startIndex = middleIndex + 1;
        } else {
            finishIndex = middleIndex;
        }
    }
    return startIndex;
}
function upperBound(array, startIndex, finishIndex, target) {
    while (startIndex < finishIndex) {
        const middleIndex = startIndex + finishIndex >> 1;
        if (array[middleIndex] <= target) {
            startIndex = middleIndex + 1;
        } else {
            finishIndex = middleIndex;
        }
    }
    return startIndex;
}
function contrastFactor(contrast) {
    return contrast > 0 ? 1 / (1.001 - contrast) : 1 + contrast;
}
function saturationFactor(saturation) {
    return saturation > 0 ? 1 - 1 / (1.001 - saturation) : -saturation;
}
function computeColorAdjustmentMatrix(saturation, contrast, brightnessMin, brightnessMax) {
    saturation = saturationFactor(saturation);
    contrast = contrastFactor(contrast);
    const m = cjsExports.mat4.create();
    const sa = saturation / 3;
    const sb = 1 - 2 * sa;
    const saturationMatrix = [
        sb,
        sa,
        sa,
        0,
        sa,
        sb,
        sa,
        0,
        sa,
        sa,
        sb,
        0,
        0,
        0,
        0,
        1
    ];
    const cs = 0.5 - 0.5 * contrast;
    const contrastMatrix = [
        contrast,
        0,
        0,
        0,
        0,
        contrast,
        0,
        0,
        0,
        0,
        contrast,
        0,
        cs,
        cs,
        cs,
        1
    ];
    const hl = brightnessMax - brightnessMin;
    const brightnessMatrix = [
        hl,
        0,
        0,
        0,
        0,
        hl,
        0,
        0,
        0,
        0,
        hl,
        0,
        brightnessMin,
        brightnessMin,
        brightnessMin,
        1
    ];
    cjsExports.mat4.multiply(m, brightnessMatrix, contrastMatrix);
    cjsExports.mat4.multiply(m, m, saturationMatrix);
    return m;
}

const config = {
    API_URL: 'https://api.mapbox.com',
    get API_URL_REGEX() {
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i;
    },
    get API_TILEJSON_REGEX() {
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i;
    },
    get API_SPRITE_REGEX() {
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i;
    },
    get API_FONTS_REGEX() {
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i;
    },
    get API_STYLE_REGEX() {
        return /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i;
    },
    get API_CDN_URL_REGEX() {
        return /^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i;
    },
    get EVENTS_URL() {
        if (!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',
    RASTERARRAYS_URL_PREFIX: 'rasterarrays/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',
    MESHOPT_URL: 'https://api.mapbox.com/mapbox-gl-js/meshopt_base_v0.20.wasm',
    MESHOPT_SIMD_URL: 'https://api.mapbox.com/mapbox-gl-js/meshopt_simd_v0.20.wasm',
    GLYPHS_URL: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
    TILES3D_URL_PREFIX: '3dtiles/v1'
};

function isMapboxHTTPURL(url) {
    return config.API_URL_REGEX.test(url);
}
function isMapboxURL(url) {
    return url.indexOf('mapbox:') === 0;
}
function isMapboxHTTPCDNURL(url) {
    return config.API_CDN_URL_REGEX.test(url);
}
function isMapboxHTTPSpriteURL(url) {
    return config.API_SPRITE_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 isMapboxHTTPFontsURL(url) {
    return config.API_FONTS_REGEX.test(url);
}
function hasCacheDefeatingSku(url) {
    return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);
}

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

let linkEl;
let reducedMotionQuery;
let stubTime;
let canvas;
let hasCanvasFingerprintNoise;
const exported$1 = {
    /**
   * Returns either performance.now() or a value set by setNow.
   * @returns {number} Time value in milliseconds.
   */
    now() {
        if (stubTime !== void 0) {
            return stubTime;
        }
        return performance.now();
    },
    setNow(time) {
        stubTime = time;
    },
    restoreNow() {
        stubTime = void 0;
    },
    frame(fn) {
        const frame = requestAnimationFrame(fn);
        return { cancel: () => cancelAnimationFrame(frame) };
    },
    getImageData(img, padding = 0) {
        const {width, height} = img;
        if (!canvas) {
            canvas = 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 = document.createElement('a');
        linkEl.href = path;
        return linkEl.href;
    },
    get devicePixelRatio() {
        return window.devicePixelRatio;
    },
    get prefersReducedMotion() {
        if (!window.matchMedia)
            return false;
        if (reducedMotionQuery == null) {
            reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
        }
        return reducedMotionQuery.matches;
    },
    /**
   * Returns true if the browser has OffscreenCanvas support and
   * adds noise to Canvas2D operations used for image decoding to prevent fingerprinting.
   */
    hasCanvasFingerprintNoise() {
        if (hasCanvasFingerprintNoise !== void 0) {
            return hasCanvasFingerprintNoise;
        }
        if (!offscreenCanvasSupported()) {
            hasCanvasFingerprintNoise = false;
            return false;
        }
        const offscreenCanvas = new OffscreenCanvas(255 / 3, 1);
        const offscreenCanvasContext = offscreenCanvas.getContext('2d', { willReadFrequently: true });
        let inc = 0;
        for (let i = 0; i < offscreenCanvas.width; ++i) {
            offscreenCanvasContext.fillStyle = `rgba(${ inc++ },${ inc++ },${ inc++ }, 255)`;
            offscreenCanvasContext.fillRect(i, 0, 1, 1);
        }
        const readData = offscreenCanvasContext.getImageData(0, 0, offscreenCanvas.width, offscreenCanvas.height);
        inc = 0;
        for (let i = 0; i < readData.data.length; ++i) {
            if (i % 4 !== 3 && inc++ !== readData.data[i]) {
                hasCanvasFingerprintNoise = true;
                return true;
            }
        }
        hasCanvasFingerprintNoise = false;
        return false;
    }
};

function setQueryParameters(url, params) {
    const paramStart = url.indexOf('?');
    if (paramStart < 0)
        return `${ url }?${ new URLSearchParams(params).toString() }`;
    const searchParams = new URLSearchParams(url.slice(paramStart));
    for (const key in params) {
        searchParams.set(key, params[key]);
    }
    return `${ url.slice(0, paramStart) }?${ searchParams.toString() }`;
}
function stripQueryParameters(url, params = { persistentParams: [] }) {
    const paramStart = url.indexOf('?');
    if (paramStart < 0)
        return url;
    const nextParams = new URLSearchParams();
    const searchParams = new URLSearchParams(url.slice(paramStart));
    for (const param of params.persistentParams) {
        const value = searchParams.get(param);
        if (value)
            nextParams.set(param, value);
    }
    const nextParamsString = nextParams.toString();
    return `${ url.slice(0, paramStart) }${ nextParamsString.length > 0 ? `?${ nextParamsString }` : '' }`;
}

const CACHE_NAME = 'mapbox-tiles';
let cacheLimit = 500;
let cacheCheckThreshold = 50;
const MIN_TIME_UNTIL_EXPIRY = 1000 * 60 * 7;
const PERSISTENT_PARAMS = [
    'language',
    'worldview',
    'jobid'
];
let sharedCache;
function getCaches() {
    try {
        return caches;
    } catch (e) {
    }
}
function cacheOpen() {
    const caches2 = getCaches();
    if (caches2 && sharedCache == null) {
        sharedCache = caches2.open(CACHE_NAME);
    }
}
let responseConstructorSupportsReadableStream;
function prepareBody(response, callback) {
    if (responseConstructorSupportsReadableStream === void 0) {
        try {
            new Response(new ReadableStream());
            responseConstructorSupportsReadableStream = true;
        } catch (e) {
            responseConstructorSupportsReadableStream = false;
        }
    }
    if (responseConstructorSupportsReadableStream) {
        callback(response.body);
    } else {
        response.blob().then(callback);
    }
}
function isNullBodyStatus(status) {
    if (status === 200 || status === 404) {
        return false;
    }
    return [
        101,
        103,
        204,
        205,
        304
    ].includes(status);
}
function cachePut(request, response, requestTime) {
    cacheOpen();
    if (sharedCache == null)
        return;
    const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');
    if (cacheControl['no-store'])
        return;
    const options = {
        status: response.status,
        statusText: response.statusText,
        headers: new Headers()
    };
    response.headers.forEach((v, k) => options.headers.set(k, v));
    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;
    let strippedURL = stripQueryParameters(request.url, { persistentParams: PERSISTENT_PARAMS });
    if (response.status === 206) {
        const range = request.headers.get('Range');
        if (!range)
            return;
        options.status = 200;
        strippedURL = setQueryParameters(strippedURL, { range });
    }
    prepareBody(response, body => {
        const clonedResponse = new Response(isNullBodyStatus(response.status) ? null : body, options);
        cacheOpen();
        if (sharedCache == null)
            return;
        sharedCache.then(cache => cache.put(strippedURL, clonedResponse)).catch(e => warnOnce(e.message));
    });
}
function cacheGet(request, callback) {
    cacheOpen();
    if (sharedCache == null)
        return callback(null);
    sharedCache.then(cache => {
        let strippedURL = stripQueryParameters(request.url, { persistentParams: PERSISTENT_PARAMS });
        const range = request.headers.get('Range');
        if (range)
            strippedURL = setQueryParameters(strippedURL, { range });
        cache.match(strippedURL).then(response => {
            const fresh = isFresh(response);
            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'];
}
let globalEntryCounter = Infinity;
function cacheEntryPossiblyAdded(dispatcher) {
    globalEntryCounter++;
    if (globalEntryCounter > cacheCheckThreshold) {
        dispatcher.getActor().send('enforceCacheSizeLimit', cacheLimit);
        globalEntryCounter = 0;
    }
}
function enforceCacheSizeLimit(limit) {
    cacheOpen();
    if (sharedCache == null)
        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 caches2 = getCaches();
    if (!caches2)
        return;
    const promise = caches2.delete(CACHE_NAME);
    if (callback) {
        promise.catch(callback).then(() => callback());
    }
}
function setCacheLimits(limit, checkThreshold) {
    cacheLimit = limit;
    cacheCheckThreshold = checkThreshold;
}

const exported = {
    supported: false,
    testSupport
};
let glForTesting;
let webpCheckComplete = false;
let webpImgTest;
let webpImgTestOnloadComplete = false;
const window$1 = typeof self !== 'undefined' ? self : {};
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;
    if (webpImgTestOnloadComplete) {
        testWebpTextureUpload(gl);
    } else {
        glForTesting = gl;
    }
}
function testWebpTextureUpload(gl) {
    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);
        if (gl.isContextLost())
            return;
        exported.supported = true;
    } catch (e) {
    }
    gl.deleteTexture(texture);
    webpCheckComplete = true;
}

const ResourceType = {
    Unknown: 'Unknown',
    Style: 'Style',
    Source: 'Source',
    Tile: 'Tile',
    Glyphs: 'Glyphs',
    SpriteImage: 'SpriteImage',
    SpriteJSON: 'SpriteJSON',
    Iconset: 'Iconset',
    Image: 'Image',
    Model: 'Model'
};
if (typeof Object.freeze == 'function') {
    Object.freeze(ResourceType);
}
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 }`;
    }
}
const getReferrer = isWorker() ? // @ts-expect-error - TS2551 - Property 'worker' does not exist on type 'Window & typeof globalThis'. Did you mean 'Worker'? | TS2551 - Property 'worker' does not exist on type 'Window & typeof globalThis'. Did you mean 'Worker'?
() => self.worker && self.worker.referrer : () => (location.protocol === 'blob:' ? parent : self).location.href;
const isFileURL = url => /^file:/.test(url) || /^file:/.test(getReferrer()) && !/^\w+:/.test(url);
function makeFetchRequest(requestParameters, callback) {
    const controller = new AbortController();
    const request = new 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) {
            if (err.message !== 'SecurityError') {
                warnOnce(err.toString());
            }
        }
        if (cachedResponse && responseIsFresh) {
            return finishRequest(cachedResponse);
        }
        const requestTime = Date.now();
        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') {
                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) {
                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 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') {
                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) {
    if (!isFileURL(requestParameters.url)) {
        if (self.fetch && self.Request && self.AbortController && 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, void 0, 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 = document.createElement('a');
    a.href = url;
    return a.protocol === location.protocol && a.host === location.host;
}
const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';
function arrayBufferToImage(data, callback) {
    const img = new Image();
    img.onload = () => {
        callback(null, img);
        URL.revokeObjectURL(img.src);
        img.onload = null;
        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 Blob([new Uint8Array(data)], { type: 'image/png' });
    img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;
}
function arrayBufferToImageBitmap(data, callback) {
    const blob = new Blob([new Uint8Array(data)], { type: 'image/png' });
    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.supported) {
        if (!requestParameters.headers) {
            requestParameters.headers = {};
        }
        requestParameters.headers.accept = 'image/webp,*/*';
    }
    if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {
        const queued = {
            requestParameters,
            callback,
            cancelled: false,
            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) {
            const request2 = imageQueue.shift();
            const {
                requestParameters: requestParameters2,
                callback: callback2,
                cancelled
            } = request2;
            if (!cancelled) {
                request2.cancel = getImage(requestParameters2, callback2).cancel;
            }
        }
    };
    const request = getArrayBuffer(requestParameters, (err, data, cacheControl, expires) => {
        advanceImageRequestQueue();
        if (err) {
            callback(err);
        } else if (data) {
            if (self.createImageBitmap) {
                arrayBufferToImageBitmap(data, (err2, imgBitmap) => callback(err2, imgBitmap, cacheControl, expires));
            } else {
                arrayBufferToImage(data, (err2, img) => callback(err2, img, cacheControl, expires));
            }
        }
    });
    return {
        cancel: () => {
            request.cancel();
            advanceImageRequestQueue();
        }
    };
};
const getVideo = function (urls, callback) {
    const video = document.createElement('video');
    video.muted = true;
    video.onloadstart = function () {
        callback(null, video);
    };
    for (let i = 0; i < urls.length; i++) {
        const s = document.createElement('source');
        if (!sameOrigin(urls[i])) {
            video.crossOrigin = 'Anonymous';
        }
        s.src = urls[i];
        video.appendChild(s);
    }
    return {
        cancel: () => {
        }
    };
};

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 
 */

var hasRequiredMurmurhash3_gc;

function requireMurmurhash3_gc () {
	if (hasRequiredMurmurhash3_gc) return murmurhash3_gc.exports;
	hasRequiredMurmurhash3_gc = 1;
	(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));
	return 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
 */

var hasRequiredMurmurhash2_gc;

function requireMurmurhash2_gc () {
	if (hasRequiredMurmurhash2_gc) return murmurhash2_gc.exports;
	hasRequiredMurmurhash2_gc = 1;
	(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));
	return murmurhash2_gc.exports;
}

var hasRequiredMurmurhashJs;

function requireMurmurhashJs () {
	if (hasRequiredMurmurhashJs) return murmurhashJs.exports;
	hasRequiredMurmurhashJs = 1;
	var murmur3 = requireMurmurhash3_gc();
	var murmur2 = requireMurmurhash2_gc();
	murmurhashJs.exports = murmur3;
	murmurhashJs.exports.murmur3 = murmur3;
	murmurhashJs.exports.murmur2 = murmur2;
	return murmurhashJs.exports;
}

var murmurhashJsExports = requireMurmurhashJs();
var murmur3 = /*@__PURE__*/getDefaultExportFromCjs(murmurhashJsExports);

class Event {
    constructor(type, ...eventData) {
        extend$1(this, eventData[0] || {});
        this.type = type;
    }
}
class ErrorEvent extends Event {
    constructor(error, data = {}) {
        super('error', extend$1({ error }, data));
    }
}
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 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;
    }
    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(e, eventData) {
        const event = typeof e === 'string' ? new Event(e, eventData) : e;
        const type = event.type;
        if (this.listens(type)) {
            event.target = this;
            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) {
                const eventedParentData = typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData;
                extend$1(event, eventedParentData);
                parent.fire(event);
            }
        } 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 csscolorparser = {};

var hasRequiredCsscolorparser;

function requireCsscolorparser () {
	if (hasRequiredCsscolorparser) return csscolorparser;
	hasRequiredCsscolorparser = 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 {
	    csscolorparser.parseCSSColor = parseCSSColor;
	} catch (e) {
	}
	return csscolorparser;
}

var csscolorparserExports = requireCsscolorparser();

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 void 0;
        }
        if (input instanceof Color) {
            return input;
        }
        if (typeof input !== 'string') {
            return void 0;
        }
        const rgba = csscolorparserExports.parseCSSColor(input);
        if (!rgba) {
            return void 0;
        }
        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)"
   */
    toStringPremultipliedAlpha() {
        const [r, g, b, a] = this.a === 0 ? [
            0,
            0,
            0,
            0
        ] : [
            this.r * 255 / this.a,
            this.g * 255 / this.a,
            this.b * 255 / this.a,
            this.a
        ];
        return `rgba(${ Math.round(r) },${ Math.round(g) },${ Math.round(b) },${ a })`;
    }
    toString() {
        const [r, g, b, a] = [
            this.r,
            this.g,
            this.b,
            this.a
        ];
        return `rgba(${ Math.round(r * 255) },${ Math.round(g * 255) },${ Math.round(b * 255) },${ a })`;
    }
    toRenderColor(lut) {
        const {r, g, b, a} = this;
        return new RenderColor(lut, r, g, b, a);
    }
    clone() {
        return new Color(this.r, this.g, this.b, this.a);
    }
}
class RenderColor {
    constructor(lut, r, g, b, a) {
        if (!lut) {
            this.r = r;
            this.g = g;
            this.b = b;
            this.a = a;
        } else {
            const N = lut.image.height;
            const N2 = N * N;
            r = a === 0 ? 0 : r / a * (N - 1);
            g = a === 0 ? 0 : g / a * (N - 1);
            b = a === 0 ? 0 : b / a * (N - 1);
            const r0 = Math.floor(r);
            const g0 = Math.floor(g);
            const b0 = Math.floor(b);
            const r1 = Math.ceil(r);
            const g1 = Math.ceil(g);
            const b1 = Math.ceil(b);
            const rw = r - r0;
            const gw = g - g0;
            const bw = b - b0;
            const data = lut.image.data;
            const i0 = (r0 + g0 * N2 + b0 * N) * 4;
            const i1 = (r0 + g0 * N2 + b1 * N) * 4;
            const i2 = (r0 + g1 * N2 + b0 * N) * 4;
            const i3 = (r0 + g1 * N2 + b1 * N) * 4;
            const i4 = (r1 + g0 * N2 + b0 * N) * 4;
            const i5 = (r1 + g0 * N2 + b1 * N) * 4;
            const i6 = (r1 + g1 * N2 + b0 * N) * 4;
            const i7 = (r1 + g1 * N2 + b1 * N) * 4;
            if (i0 < 0 || i7 >= data.length) {
                throw new Error('out of range');
            }
            this.r = number(number(number(data[i0], data[i1], bw), number(data[i2], data[i3], bw), gw), number(number(data[i4], data[i5], bw), number(data[i6], data[i7], bw), gw), rw) / 255 * a;
            this.g = number(number(number(data[i0 + 1], data[i1 + 1], bw), number(data[i2 + 1], data[i3 + 1], bw), gw), number(number(data[i4 + 1], data[i5 + 1], bw), number(data[i6 + 1], data[i7 + 1], bw), gw), rw) / 255 * a;
            this.b = number(number(number(data[i0 + 2], data[i1 + 2], bw), number(data[i2 + 2], data[i3 + 2], bw), gw), number(number(data[i4 + 2], data[i5 + 2], bw), number(data[i6 + 2], data[i7 + 2], bw), gw), rw) / 255 * a;
            this.a = 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 an HSLA array of values representing the color, unpremultiplied by A.
   *
   * @returns An array of HSLA color values.
   */
    toHslaArray() {
        if (this.a === 0) {
            return [
                0,
                0,
                0,
                0
            ];
        }
        const {r, g, b, a} = this;
        const red = Math.min(Math.max(r / a, 0), 1);
        const green = Math.min(Math.max(g / a, 0), 1);
        const blue = Math.min(Math.max(b / a, 0), 1);
        const min = Math.min(red, green, blue);
        const max = Math.max(red, green, blue);
        const l = (min + max) / 2;
        if (min === max) {
            return [
                0,
                0,
                l * 100,
                a
            ];
        }
        const delta = max - min;
        const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
        let h = 0;
        if (max === red) {
            h = (green - blue) / delta + (green < blue ? 6 : 0);
        } else if (max === green) {
            h = (blue - red) / delta + 2;
        } else if (max === blue) {
            h = (red - green) / delta + 4;
        }
        h *= 60;
        return [
            Math.min(Math.max(h, 0), 360),
            Math.min(Math.max(s * 100, 0), 100),
            Math.min(Math.max(l * 100, 0), 100),
            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);

function number(a, b, t) {
    return a * (1 - t) + b * t;
}
function color(from, to, t) {
    return new Color(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$1(from, to, t) {
    return from.map((d, i) => {
        return number(d, to[i], t);
    });
}

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

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

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

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;
    }
}

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(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(ValueType),
    ResolvedImageType
];
function checkSubtype(expected, t) {
    if (t.kind === 'error') {
        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;
        }
    });
}

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() {
        return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale;
    }
}

class FormattedSection {
    constructor(text, image, scale, fontStack, textColor) {
        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);
    }
    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.toRenderColor(null).toArray());
            }
            serialized.push(options);
        }
        return serialized;
    }
}

class ImageIdWithOptions {
    constructor(id, options) {
        this.id = id;
        this.options = options || { params: {} };
        if (!this.options.transform) {
            this.options.transform = new DOMMatrix([
                1,
                0,
                0,
                1,
                0,
                0
            ]);
        } else {
            const {a, b, c, d, e, f} = this.options.transform;
            this.options.transform = new DOMMatrix([
                a,
                b,
                c,
                d,
                e,
                f
            ]);
        }
    }
    static deserializeId(serialized) {
        return JSON.parse(serialized).id;
    }
    static deserializeFromString(serialized) {
        const deserializedObject = JSON.parse(serialized);
        ({ params: deserializedObject.options.params });
        const {a, b, c, d, e, f} = deserializedObject.options.transform;
        new DOMMatrix([
            a,
            b,
            c,
            d,
            e,
            f
        ]);
        return new ImageIdWithOptions(deserializedObject.id, deserializedObject.options);
    }
    scaleSelf(factor) {
        this.options.transform = this.options.transform.scale(factor);
        return this;
    }
    serialize() {
        const serialisedObject = { id: this.id };
        if (this.options) {
            serialisedObject.options = this.options;
        }
        const {a, b, c, d, e, f} = this.options.transform;
        serialisedObject.options.transform = {
            a,
            b,
            c,
            d,
            e,
            f
        };
        return JSON.stringify(serialisedObject);
    }
}

class ResolvedImage {
    constructor(options) {
        this.namePrimary = options.namePrimary;
        if (options.nameSecondary) {
            this.nameSecondary = options.nameSecondary;
        }
        if (options.optionsPrimary) {
            this.optionsPrimary = options.optionsPrimary;
        }
        if (options.optionsSecondary) {
            this.optionsSecondary = options.optionsSecondary;
        }
        this.available = options.available;
    }
    toString() {
        if (this.namePrimary && this.nameSecondary) {
            return `[${ this.namePrimary },${ this.nameSecondary }]`;
        }
        return this.namePrimary;
    }
    getPrimary() {
        return new ImageIdWithOptions(this.namePrimary, { params: this.optionsPrimary ? this.optionsPrimary.params || {} : {} });
    }
    getSerializedPrimary() {
        return this.getPrimary().serialize();
    }
    getSecondary() {
        if (this.nameSecondary) {
            return new ImageIdWithOptions(this.nameSecondary, { params: this.optionsSecondary ? this.optionsSecondary.params || {} : {} });
        }
        return null;
    }
    static from(image) {
        return typeof image === 'string' ? ResolvedImage.build(image) : image;
    }
    static build(namePrimary, nameSecondary, optionsPrimary, optionsSecondary) {
        if (!namePrimary)
            return null;
        return new ResolvedImage({
            namePrimary,
            nameSecondary,
            optionsPrimary,
            optionsSecondary,
            available: false
        });
    }
}

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) {
        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) {
        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(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) {
        return value.toStringPremultipliedAlpha();
    } else if (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);
        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) {
            return ['rgba'].concat(this.value.toRenderColor(null).toArray());
        } else if (this.value instanceof Formatted) {
            return this.value.serialize();
        } else {
            return this.value;
        }
    }
}

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

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 type2 = args[1];
                if (typeof type2 !== 'string' || !(type2 in types$1) || type2 === 'object')
                    return context.error('The item type argument of "array" must be one of string, number, boolean', 1);
                itemType = types$1[type2];
                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(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(`The expression ${ JSON.stringify(this.args[i].serialize()) } evaluated to ${ toString$1(typeOf(value)) } but was expected to be of type ${ toString$1(this.type) }.`);
            }
        }
        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()));
    }
}

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.parseObjectValue(arg['font-scale'], i, 'font-scale', NumberType);
                    if (!scale)
                        return null;
                }
                let font = null;
                if (arg['text-font']) {
                    font = context.parseObjectValue(arg['text-font'], i, 'text-font', array(StringType));
                    if (!font)
                        return null;
                }
                let textColor = null;
                if (arg['text-color']) {
                    textColor = context.parseObjectValue(arg['text-color'], i, 'text-color', 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], i, 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() {
        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;
    }
}

function isImageOptions(value) {
    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
        return true;
    }
    return false;
}
class ImageExpression {
    constructor(inputPrimary, inputSecondary, inputPrimaryParams, inputSecondaryParams) {
        this._imageWarnHistory = {};
        this.type = ResolvedImageType;
        this.inputPrimary = inputPrimary;
        this.inputSecondary = inputSecondary;
        this.inputPrimaryParams = inputPrimaryParams;
        this.inputSecondaryParams = inputSecondaryParams;
    }
    static parse(args, context) {
        if (args.length < 2) {
            return context.error(`Expected two or more arguments.`);
        }
        let nextArgId = 1;
        const imageExpression = [];
        function tryParseImage() {
            if (nextArgId < args.length) {
                const imageName = context.parse(args[nextArgId], nextArgId++, StringType);
                if (!imageName) {
                    context.error(imageExpression.length ? `Secondary image variant is not a string.` : `No image name provided.`);
                    return false;
                }
                imageExpression.push({
                    image: imageName,
                    options: void 0
                });
                return true;
            }
            return true;
        }
        function tryParseOptions() {
            if (nextArgId < args.length) {
                if (!isImageOptions(args[nextArgId])) {
                    return true;
                }
                const params = args[nextArgId].params;
                const optionsContext = context.concat(nextArgId);
                if (!params) {
                    nextArgId++;
                    return true;
                }
                if (typeof params !== 'object' || params.constructor !== Object) {
                    optionsContext.error(`Image options "params" should be an object`);
                    return false;
                }
                const parsed = {};
                const childContext = optionsContext.concat(void 0, 'params');
                for (const key in params) {
                    if (!key) {
                        childContext.error(`Image parameter name should be non-empty`);
                        return false;
                    }
                    const value = childContext.concat(void 0, key).parse(params[key], void 0, ColorType, void 0, { typeAnnotation: 'coerce' });
                    if (!value) {
                        return false;
                    }
                    parsed[key] = value;
                }
                imageExpression[imageExpression.length - 1].options = parsed;
                nextArgId++;
                return true;
            }
            return true;
        }
        for (let i = 0; i < 2; i++) {
            if (!tryParseImage() || !tryParseOptions()) {
                return;
            }
        }
        return new ImageExpression(imageExpression[0].image, imageExpression[1] ? imageExpression[1].image : void 0, imageExpression[0].options, imageExpression[1] ? imageExpression[1].options : void 0);
    }
    evaluateParams(ctx, params) {
        const result = {};
        if (params) {
            for (const key in params) {
                if (params[key]) {
                    try {
                        const color = params[key].evaluate(ctx);
                        const msg = `Ignoring image parameter "${ key }" with semi-transparent color ${ color.toString() }`;
                        if (color.a !== 1) {
                            if (!this._imageWarnHistory[msg]) {
                                console.warn(msg);
                                this._imageWarnHistory[msg] = true;
                            }
                            continue;
                        }
                        result[key] = color;
                    } catch (err) {
                        continue;
                    }
                }
            }
        } else {
            return void 0;
        }
        if (Object.keys(result).length === 0) {
            return void 0;
        }
        return { params: result };
    }
    evaluate(ctx) {
        const value = ResolvedImage.build(this.inputPrimary.evaluate(ctx), this.inputSecondary ? this.inputSecondary.evaluate(ctx) : void 0, this.inputPrimaryParams ? this.evaluateParams(ctx, this.inputPrimaryParams) : void 0, this.inputSecondaryParams ? this.evaluateParams(ctx, this.inputSecondaryParams) : void 0);
        if (value && ctx.availableImages) {
            value.available = ctx.availableImages.indexOf(value.namePrimary) > -1;
            if (value.nameSecondary && value.available && ctx.availableImages) {
                value.available = ctx.availableImages.indexOf(value.nameSecondary) > -1;
            }
        }
        return value;
    }
    eachChild(fn) {
        fn(this.inputPrimary);
        if (this.inputPrimaryParams) {
            for (const key in this.inputPrimaryParams) {
                if (this.inputPrimaryParams[key]) {
                    fn(this.inputPrimaryParams[key]);
                }
            }
        }
        if (this.inputSecondary) {
            fn(this.inputSecondary);
            if (this.inputSecondaryParams) {
                for (const key in this.inputSecondaryParams) {
                    if (this.inputSecondaryParams[key]) {
                        fn(this.inputSecondaryParams[key]);
                    }
                }
            }
        }
    }
    outputDefined() {
        return false;
    }
    serializeParams(params) {
        const result = {};
        if (params) {
            for (const key in params) {
                if (params[key]) {
                    result[key] = params[key].serialize();
                }
            }
        } else {
            return void 0;
        }
        return { params: result };
    }
    serialize() {
        const serialized = [
            'image',
            this.inputPrimary.serialize()
        ];
        if (this.inputPrimaryParams) {
            serialized.push(this.serializeParams(this.inputPrimaryParams));
        }
        if (this.inputSecondary) {
            serialized.push(this.inputSecondary.serialize());
            if (this.inputSecondaryParams) {
                serialized.push(this.serializeParams(this.inputSecondaryParams));
            }
        }
        return serialized;
    }
}

function getType(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
};
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(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(typeOf(value), arrayLength);
            } else {
                return null;
            }
            for (let i = 0; i < arrayLength; i++) {
                const member = args[1][i];
                let parsedMember;
                if (getType(member) === 'array') {
                    parsedMember = context.parse(member, void 0, type.itemType);
                } else {
                    const memberType = getType(member);
                    if (memberType !== type.itemType.kind) {
                        return context.error(`Expected ${ type.itemType.kind } but found ${ memberType }.`);
                    }
                    parsedMember = context.registry['literal'].parse([
                        'literal',
                        member === void 0 ? 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) {
                    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(input[0] / 255, input[1] / 255, input[2] / 255, input[3]);
                    }
                }
            }
            throw new RuntimeError(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(`Could not convert ${ JSON.stringify(value) } to number.`);
        } else if (this.type.kind === 'formatted') {
            return Formatted.fromString(toString(this.args[0].evaluate(ctx)));
        } else if (this.type.kind === 'resolvedImage') {
            return ResolvedImage.build(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;
    }
}

const geometryTypes = [
    'Unknown',
    'Point',
    'LineString',
    'Polygon'
];
class EvaluationContext {
    constructor(scope, 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.scope = scope;
        this.options = options;
    }
    id() {
        return this.feature && this.feature.id !== void 0 ? 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;
            const dX = x * scale - c[0];
            const dY = y * scale - c[1];
            const bX = this.featureDistanceData.bearing[0];
            const bY = this.featureDistanceData.bearing[1];
            const dist = bX * dX + bY * dY;
            return dist;
        }
        return 0;
    }
    parseColor(input) {
        let cached = this._parseColorCache[input];
        if (!cached) {
            cached = this._parseColorCache[input] = Color.parse(input);
        }
        return cached;
    }
    getConfig(id) {
        return this.options ? this.options.get(id) : null;
    }
}

class CompoundExpression {
    constructor(name, type, evaluate, args, overloadIndex) {
        this.name = name;
        this.type = type;
        this._evaluate = evaluate;
        this.args = args;
        this._overloadIndex = overloadIndex;
    }
    evaluate(ctx) {
        if (!this._evaluate) {
            const definition = CompoundExpression.definitions[this.name];
            this._evaluate = Array.isArray(definition) ? definition[2] : definition.overloads[this._overloadIndex][1];
        }
        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);
        }
        const type = Array.isArray(definition) ? definition[0] : definition.type;
        const availableOverloads = Array.isArray(definition) ? [[
                definition[1],
                definition[2]
            ]] : definition.overloads;
        const overloadParams = [];
        let signatureContext = null;
        let overloadIndex = -1;
        for (const [params, evaluate] of availableOverloads) {
            if (Array.isArray(params) && params.length !== args.length - 1)
                continue;
            overloadParams.push(params);
            overloadIndex++;
            signatureContext = new ParsingContext$1(context.registry, context.path, null, context.scope, void 0, context._scope, context.options);
            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] : // @ts-expect-error - TS2339 - Property 'type' does not exist on type 'Varargs | Evaluate'.
                params.type;
                const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);
                if (!parsed) {
                    argParseFailed = true;
                    break;
                }
                parsedArgs.push(parsed);
            }
            if (argParseFailed) {
                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, overloadIndex);
            }
        }
        if (overloadParams.length === 1) {
            context.errors.push(...signatureContext.errors);
        } else {
            const expected = overloadParams.length ? overloadParams : availableOverloads.map(([params]) => params);
            const signatures = expected.map(stringifySignature).join(' | ');
            const actualTypes = [];
            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) {
            registry[name] = CompoundExpression;
        }
    }
}
function stringifySignature(signature) {
    if (Array.isArray(signature)) {
        return `(${ signature.map(toString$1).join(', ') })`;
    } else {
        return `(${ toString$1(signature.type) }...)`;
    }
}

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 = options['case-sensitive'] === void 0 ? context.parse(false, 1, BooleanType) : context.parseObjectValue(options['case-sensitive'], 1, 'case-sensitive', BooleanType);
        if (!caseSensitive)
            return null;
        const diacriticSensitive = options['diacritic-sensitive'] === void 0 ? context.parse(false, 1, BooleanType) : context.parseObjectValue(options['diacritic-sensitive'], 1, 'diacritic-sensitive', BooleanType);
        if (!diacriticSensitive)
            return null;
        let locale = null;
        if (options['locale']) {
            locale = context.parseObjectValue(options['locale'], 1, 'locale', 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() {
        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
        ];
    }
}

/**
 * Rearranges items so that all items in the [left, k] are the smallest.
 * The k-th element will have the (k - left + 1)-th smallest value in [left, right].
 *
 * @template T
 * @param {T[]} arr the array to partially sort (in place)
 * @param {number} k middle index for partial sorting (as defined above)
 * @param {number} [left=0] left index of the range to sort
 * @param {number} [right=arr.length-1] right index
 * @param {(a: T, b: T) => number} [compare = (a, b) => a - b] compare function
 */
function quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) {
    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));
            quickselect(arr, k, newLeft, newRight, compare);
        }
        const t = arr[k];
        let i = left;
        /** @type {number} */
        let j = right;
        swap$2(arr, left, k);
        if (compare(arr[right], t) > 0)
            swap$2(arr, left, right);
        while (i < j) {
            swap$2(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$2(arr, left, j);
        else {
            j++;
            swap$2(arr, j, right);
        }
        if (j <= k)
            left = j + 1;
        if (k <= j)
            right = j - 1;
    }
}
/**
 * @template T
 * @param {T[]} arr
 * @param {number} i
 * @param {number} j
 */
function swap$2(arr, i, j) {
    const tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
/**
 * @template T
 * @param {T} a
 * @param {T} b
 * @returns {number}
 */
function defaultCompare(a, b) {
    return a < b ? -1 : a > b ? 1 : 0;
}

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 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(rings[i]);
        if (area === 0)
            continue;
        rings[i].area = Math.abs(area);
        if (ccw === void 0)
            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 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];
}
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];
}
function twoSided(p1, p2, q1, q2) {
    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;
}
function segmentIntersectSegment(a, b, 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 (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) {
        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) {
    for (let i = 0; i < line.length; ++i) {
        if (!pointWithinPolygon(line[i], polygon)) {
            return false;
        }
    }
    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
        ];
    }
}

const 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
const RE = 6378.137;
// equatorial radius
const FE = 1 / 298.257223563;
// flattening
const E2 = FE * (2 - FE);
const 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.
 */
class CheapRuler {
    /**
     * Creates a ruler object from tile coordinates (y and z).
     *
     * @param {number} y
     * @param {number} z
     * @param {keyof typeof factors} [units='kilometers']
     * @returns {CheapRuler}
     * @example
     * const ruler = cheapRuler.fromTile(1567, 12);
     * //=ruler
     */
    static fromTile(y, z, units) {
        const n = Math.PI * (1 - 2 * (y + 0.5) / Math.pow(2, z));
        const 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;
     */
    static get units() {
        return factors;
    }
    /**
     * Creates a ruler instance for very fast approximations to common geodesic measurements around a certain latitude.
     *
     * @param {number} lat latitude
     * @param {keyof typeof factors} [units='kilometers']
     * @example
     * const ruler = cheapRuler(35.05, 'miles');
     * //=ruler
     */
    constructor(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
        const m = RAD * RE * (units ? factors[units] : 1);
        const coslat = Math.cos(lat * RAD);
        const w2 = 1 / (1 - E2 * (1 - coslat * coslat));
        const 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
    }
    /**
     * Given two points of the form [longitude, latitude], returns the distance.
     *
     * @param {[number, number]} a point [longitude, latitude]
     * @param {[number, number]} b point [longitude, latitude]
     * @returns {number} distance
     * @example
     * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);
     * //=distance
     */
    distance(a, b) {
        const dx = wrap(a[0] - b[0]) * this.kx;
        const dy = (a[1] - b[1]) * this.ky;
        return Math.sqrt(dx * dx + dy * dy);
    }
    /**
     * Returns the bearing between two points in angles.
     *
     * @param {[number, number]} a point [longitude, latitude]
     * @param {[number, number]} b point [longitude, latitude]
     * @returns {number} bearing
     * @example
     * const bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]);
     * //=bearing
     */
    bearing(a, b) {
        const dx = wrap(b[0] - a[0]) * this.kx;
        const 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 {[number, number]} p point [longitude, latitude]
     * @param {number} dist distance
     * @param {number} bearing
     * @returns {[number, number]} point [longitude, latitude]
     * @example
     * const point = ruler.destination([30.5, 50.5], 0.1, 90);
     * //=point
     */
    destination(p, dist, bearing) {
        const 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 {[number, number]} p point [longitude, latitude]
     * @param {number} dx easting
     * @param {number} dy northing
     * @returns {[number, number]} point [longitude, latitude]
     * @example
     * const point = ruler.offset([30.5, 50.5], 10, 10);
     * //=point
     */
    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 {[number, 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
     */
    lineDistance(points) {
        let total = 0;
        for (let 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 {[number, 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
     */
    area(polygon) {
        let sum = 0;
        for (let i = 0; i < polygon.length; i++) {
            const ring = polygon[i];
            for (let 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 {[number, number][]} line
     * @param {number} dist distance
     * @returns {[number, number]} point [longitude, latitude]
     * @example
     * const point = ruler.along(line, 2.5);
     * //=point
     */
    along(line, dist) {
        let sum = 0;
        if (dist <= 0)
            return line[0];
        for (let i = 0; i < line.length - 1; i++) {
            const p0 = line[i];
            const p1 = line[i + 1];
            const 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 {[number, number]} p point [longitude, latitude]
     * @param {[number, number]} a segment point 1 [longitude, latitude]
     * @param {[number, number]} b 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
     */
    pointToSegmentDistance(p, a, b) {
        let [x, y] = a;
        let dx = wrap(b[0] - x) * this.kx;
        let dy = (b[1] - y) * this.ky;
        if (dx !== 0 || dy !== 0) {
            const 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 {[number, number][]} line
     * @param {[number, number]} p point [longitude, latitude]
     * @returns {{point: [number, number], index: number, t: number}} {point, index, t}
     * @example
     * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point;
     * //=point
     */
    pointOnLine(line, p) {
        let minDist = Infinity;
        let minX = line[0][0];
        let minY = line[0][1];
        let minI = 0;
        let minT = 0;
        for (let i = 0; i < line.length - 1; i++) {
            let x = line[i][0];
            let y = line[i][1];
            let dx = wrap(line[i + 1][0] - x) * this.kx;
            let dy = (line[i + 1][1] - y) * this.ky;
            let 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;
            const 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 {[number, number]} start point [longitude, latitude]
     * @param {[number, number]} stop point [longitude, latitude]
     * @param {[number, number][]} line
     * @returns {[number, number][]} line part of a line
     * @example
     * const line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1);
     * //=line2
     */
    lineSlice(start, stop, line) {
        let p1 = this.pointOnLine(line, start);
        let p2 = this.pointOnLine(line, stop);
        if (p1.index > p2.index || p1.index === p2.index && p1.t > p2.t) {
            const tmp = p1;
            p1 = p2;
            p2 = tmp;
        }
        const slice = [p1.point];
        const l = p1.index + 1;
        const r = p2.index;
        if (!equals$1(line[l], slice[0]) && l <= r)
            slice.push(line[l]);
        for (let i = l + 1; i <= r; i++) {
            slice.push(line[i]);
        }
        if (!equals$1(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 start distance
     * @param {number} stop stop distance
     * @param {[number, number][]} line
     * @returns {[number, number][]} part of a line
     * @example
     * const line2 = ruler.lineSliceAlong(10, 20, line1);
     * //=line2
     */
    lineSliceAlong(start, stop, line) {
        let sum = 0;
        const slice = [];
        for (let i = 0; i < line.length - 1; i++) {
            const p0 = line[i];
            const p1 = line[i + 1];
            const 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 {[number, number]} p point [longitude, latitude]
     * @param {number} buffer
     * @returns {[number, number, number, number]} bbox ([w, s, e, n])
     * @example
     * const bbox = ruler.bufferPoint([30.5, 50.5], 0.01);
     * //=bbox
     */
    bufferPoint(p, buffer) {
        const v = buffer / this.ky;
        const 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 {[number, number, number, number]} bbox ([w, s, e, n])
     * @param {number} buffer
     * @returns {[number, number, number, number]} bbox ([w, s, e, n])
     * @example
     * const bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2);
     * //=bbox
     */
    bufferBBox(bbox, buffer) {
        const v = buffer / this.ky;
        const 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 {[number, number]} p point [longitude, latitude]
     * @param {[number, number, number, number]} bbox ([w, s, e, n])
     * @returns {boolean}
     * @example
     * const inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]);
     * //=inside
     */
    insideBBox(p, bbox) {
        // eslint-disable-line
        return wrap(p[0] - bbox[0]) >= 0 && wrap(p[0] - bbox[2]) <= 0 && p[1] >= bbox[1] && p[1] <= bbox[3];
    }
}
/**
 * @param {[number, number]} a
 * @param {[number, number]} b
 */
function equals$1(a, b) {
    return a[0] === b[0] && a[1] === b[1];
}
/**
 * @param {[number, number]} a
 * @param {[number, number]} b
 * @param {number} t
 * @returns {[number, number]}
 */
function interpolate(a, b, t) {
    const dx = wrap(b[0] - a[0]);
    const dy = b[1] - a[1];
    return [
        a[0] + dx * t,
        a[1] + dy * t
    ];
}
/**
 * normalize a degree value into [-180..180] range
 * @param {number} deg
 */
function wrap(deg) {
    while (deg < -180)
        deg += 360;
    while (deg > 180)
        deg -= 360;
    return deg;
}

class TinyQueue {
    constructor(data = [], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0) {
        this.data = data;
        this.length = this.data.length;
        this.compare = compare;
        if (this.length > 0) {
            for (let i = (this.length >> 1) - 1; i >= 0; i--)
                this._down(i);
        }
    }
    push(item) {
        this.data.push(item);
        this._up(this.length++);
    }
    pop() {
        if (this.length === 0)
            return undefined;
        const top = this.data[0];
        const bottom = this.data.pop();
        if (--this.length > 0) {
            this.data[0] = bottom;
            this._down(0);
        }
        return top;
    }
    peek() {
        return this.data[0];
    }
    _up(pos) {
        const {data, compare} = this;
        const item = data[pos];
        while (pos > 0) {
            const parent = pos - 1 >> 1;
            const current = data[parent];
            if (compare(item, current) >= 0)
                break;
            data[pos] = current;
            pos = parent;
        }
        data[pos] = item;
    }
    _down(pos) {
        const {data, compare} = this;
        const halfLength = this.length >> 1;
        const item = data[pos];
        while (pos < halfLength) {
            let bestChild = (pos << 1) + 1;
            // initially it is the left child
            const right = bestChild + 1;
            if (right < this.length && compare(data[right], data[bestChild]) < 0) {
                bestChild = right;
            }
            if (compare(data[bestChild], item) >= 0)
                break;
            data[pos] = data[bestChild];
            pos = bestChild;
        }
        data[pos] = item;
    }
}

var EXTENT = 8192;

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;
}
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;
}
function bboxToBBoxDistance(bbox1, bbox2, ruler) {
    if (isDefaultBBOX(bbox1) || isDefaultBBOX(bbox2)) {
        return NaN;
    }
    let dx = 0;
    let dy = 0;
    if (bbox1[2] < bbox2[0]) {
        dx = bbox2[0] - bbox1[2];
    }
    if (bbox1[0] > bbox2[2]) {
        dx = bbox1[0] - bbox2[2];
    }
    if (bbox1[1] > bbox2[3]) {
        dy = bbox1[1] - bbox2[3];
    }
    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;
}
function segmentToSegmentDistance(p1, p2, q1, q2, ruler) {
    const dist1 = Math.min(// @ts-expect-error - TS2345 - Argument of type 'Position' is not assignable to parameter of type 'Point'.
    ruler.pointToSegmentDistance(p1, q1, q2), // @ts-expect-error - TS2345 - Argument of type 'Position' is not assignable to parameter of type 'Point'.
    ruler.pointToSegmentDistance(p2, q1, q2));
    const dist2 = Math.min(// @ts-expect-error - TS2345 - Argument of type 'Position' is not assignable to parameter of type 'Point'.
    ruler.pointToSegmentDistance(q1, p1, p2), // @ts-expect-error - TS2345 - Argument of type 'Position' is not assignable to parameter of type 'Point'.
    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);
    if (tempDist < miniDist)
        distQueue.push({
            dist: tempDist,
            range1: r1,
            range2: r2
        });
}
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 TinyQueue([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;
        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 TinyQueue([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;
        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, 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, geometry.type === 'Point' ? [geometry.coordinates] : geometry.coordinates, geometry.type === 'LineString', ruler);
    }
    if (geometry.type === 'MultiLineString') {
        return pointSetToLinesDistance(lngLatPoints, false, geometry.coordinates, ruler);
    }
    if (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon') {
        return pointSetToPolygonsDistance(lngLatPoints, false, 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', 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, 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, 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$1(originGeometry)) {
        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', 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, 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
        ];
    }
}

function coerceValue(type, value) {
    switch (type) {
    case 'string':
        return toString(value);
    case 'number':
        return +value;
    case 'boolean':
        return !!value;
    case 'color':
        return Color.parse(value);
    case 'formatted': {
            return Formatted.fromString(toString(value));
        }
    case 'resolvedImage': {
            return ResolvedImage.build(toString(value));
        }
    }
    return value;
}
function clampToAllowedNumber(value, min, max, step) {
    if (step !== void 0) {
        value = step * Math.round(value / step);
    }
    if (min !== void 0 && value < min) {
        value = min;
    }
    if (max !== void 0 && value > max) {
        value = max;
    }
    return value;
}
class Config {
    constructor(type, key, scope) {
        this.type = type;
        this.key = key;
        this.scope = scope;
    }
    static parse(args, context) {
        let type = context.expectedType;
        if (type === null || type === void 0) {
            type = ValueType;
        }
        if (args.length < 2 || args.length > 3) {
            return context.error(`Invalid number of arguments for 'config' expression.`);
        }
        const configKey = context.parse(args[1], 1);
        if (!(configKey instanceof Literal)) {
            return context.error(`Key name of 'config' expression must be a string literal.`);
        }
        if (args.length >= 3) {
            const configScope = context.parse(args[2], 2);
            if (!(configScope instanceof Literal)) {
                return context.error(`Scope of 'config' expression must be a string literal.`);
            }
            return new Config(type, toString(configKey.value), toString(configScope.value));
        }
        return new Config(type, toString(configKey.value));
    }
    evaluate(ctx) {
        const FQIDSeparator = '\x1F';
        const configKey = [
            this.key,
            this.scope,
            ctx.scope
        ].filter(Boolean).join(FQIDSeparator);
        const config = ctx.getConfig(configKey);
        if (!config)
            return null;
        const {type, value, values, minValue, maxValue, stepValue} = config;
        const defaultValue = config.default.evaluate(ctx);
        let result = defaultValue;
        if (value) {
            const originalScope = ctx.scope;
            ctx.scope = (originalScope || '').split(FQIDSeparator).slice(1).join(FQIDSeparator);
            result = value.evaluate(ctx);
            ctx.scope = originalScope;
        }
        if (type) {
            result = coerceValue(type, result);
        }
        if (result !== void 0 && (minValue !== void 0 || maxValue !== void 0 || stepValue !== void 0)) {
            if (typeof result === 'number') {
                result = clampToAllowedNumber(result, minValue, maxValue, stepValue);
            } else if (Array.isArray(result)) {
                result = result.map(item => typeof item === 'number' ? clampToAllowedNumber(item, minValue, maxValue, stepValue) : item);
            }
        }
        if (value !== void 0 && result !== void 0 && values && !values.includes(result)) {
            result = defaultValue;
            if (type) {
                result = coerceValue(type, result);
            }
        }
        if (type && type !== this.type || result !== void 0 && typeOf(result) !== this.type) {
            result = coerceValue(this.type.kind, result);
        }
        return result;
    }
    eachChild() {
    }
    outputDefined() {
        return false;
    }
    serialize() {
        const res = [
            'config',
            this.key
        ];
        if (this.scope) {
            res.concat(this.key);
        }
        return res;
    }
}

function isFeatureConstant(e) {
    if (e instanceof CompoundExpression) {
        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) {
        return false;
    }
    if (e instanceof Distance) {
        return false;
    }
    let result = true;
    e.eachChild(arg => {
        if (result && !isFeatureConstant(arg)) {
            result = false;
        }
    });
    return result;
}
function isStateConstant(e) {
    if (e instanceof CompoundExpression) {
        if (e.name === 'feature-state') {
            return false;
        }
    }
    let result = true;
    e.eachChild(arg => {
        if (result && !isStateConstant(arg)) {
            result = false;
        }
    });
    return result;
}
function getConfigDependencies(e) {
    if (e instanceof Config) {
        const singleConfig = /* @__PURE__ */
        new Set([e.key]);
        return singleConfig;
    }
    let result = /* @__PURE__ */
    new Set();
    e.eachChild(arg => {
        result = /* @__PURE__ */
        new Set([
            ...result,
            ...getConfigDependencies(arg)
        ]);
    });
    return result;
}
function isGlobalPropertyConstant(e, properties) {
    if (e instanceof CompoundExpression && 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
        ];
    }
}

class ParsingContext {
    constructor(registry, path = [], expectedType, scope = new Scope(), errors = [], _scope, options) {
        this.registry = registry;
        this.path = path;
        this.key = path.map(part => {
            if (typeof part === 'string') {
                return `['${ part }']`;
            }
            return `[${ part }]`;
        }).join('');
        this.scope = scope;
        this.errors = errors;
        this.expectedType = expectedType;
        this._scope = _scope;
        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, null, expectedType, bindings)._parse(expr, options);
        }
        return this._parse(expr, options);
    }
    /**
   * @param expr the JSON expression to parse
   * @param index the optional argument index if parent object being is an argument of another expression
   * @param key key of parent object 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
   */
    parseObjectValue(expr, index, key, expectedType, bindings, options = {}) {
        return this.concat(index, key, expectedType, bindings)._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(type, [parsed]);
            } else if (typeAnnotation === 'coerce') {
                return new Coercion(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]] : void 0;
            if (Expr) {
                let parsed = Expr.parse(expr, this);
                if (!parsed)
                    return null;
                if (this.expectedType) {
                    const expected = this.expectedType;
                    const actual = parsed.type;
                    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 (!(parsed instanceof Literal) && parsed.type.kind !== 'resolvedImage' && isConstant(parsed)) {
                    const ec = new EvaluationContext(this._scope, this.options);
                    try {
                        parsed = new Literal(parsed.type, parsed.evaluate(ec));
                    } catch (e) {
                        this.error(e.message);
                        return null;
                    }
                }
                return parsed;
            }
            return Coercion.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, key, expectedType, bindings) {
        let path = typeof index === 'number' ? this.path.concat(index) : this.path;
        path = typeof key === 'string' ? path.concat(key) : path;
        const scope = bindings ? this.scope.concat(bindings) : this.scope;
        return new ParsingContext(this.registry, path, expectedType || null, scope, this.errors, this._scope, 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(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) {
        return isConstant(expression.boundExpression);
    } else if (expression instanceof CompoundExpression && expression.name === 'error') {
        return false;
    } else if (expression instanceof CollatorExpression) {
        return false;
    } else if (expression instanceof Within) {
        return false;
    } else if (expression instanceof Distance) {
        return false;
    } else if (expression instanceof Config) {
        return false;
    }
    const isTypeAnnotation = expression instanceof Coercion || expression instanceof Assertion;
    let childrenConstant = true;
    expression.eachChild(child => {
        if (isTypeAnnotation) {
            childrenConstant = childrenConstant && isConstant(child);
        } else {
            childrenConstant = childrenConstant && child instanceof Literal;
        }
    });
    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',
        'raster-particle-speed'
    ]);
}

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) {
                return currentIndex;
            }
            lowerIndex = currentIndex + 1;
        } else if (currentValue > input) {
            upperIndex = currentIndex - 1;
        } else {
            throw new RuntimeError('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;
    }
}

const Xn = 0.95047, 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;
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);
}
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(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)
    };
}
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, dynamicStops, stops) {
        this.type = type;
        this.operator = operator;
        this.interpolation = interpolation;
        this.input = input;
        this.dynamicStops = dynamicStops;
        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(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
            };
        } else {
            return context.error(`Unknown interpolation type ${ String(interpolation[0]) }`, 1, 0);
        }
        if (args.length - 1 < 3) {
            return context.error(`Expected at least 3 arguments, but found only ${ args.length - 1 }.`);
        }
        if (args.length - 1 > 3 && (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;
        }
        if (args.length - 1 === 3) {
            const dynamicStops = context.parse(rest[0], 3, ValueType);
            if (!dynamicStops)
                return null;
            return new Interpolate(outputType, operator, interpolation, input, dynamicStops, stops);
        }
        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, null, stops);
    }
    evaluate(ctx) {
        let labels = this.labels;
        let outputs = this.outputs;
        if (this.dynamicStops) {
            const dynamicStopsValue = this.dynamicStops.evaluate(ctx);
            if (dynamicStopsValue.length % 2 !== 0) {
                throw new RuntimeError('Expected an even number of arguments.');
            }
            labels = [];
            outputs = [];
            for (let i = 0; i < dynamicStopsValue.length; i += 2) {
                const label = dynamicStopsValue[i];
                const output = new Literal(NumberType, dynamicStopsValue[i + 1]);
                if (typeof label !== 'number') {
                    throw new RuntimeError('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.');
                }
                if (labels.length && labels[labels.length - 1] >= label) {
                    throw new RuntimeError('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.');
                }
                labels.push(label);
                outputs.push(output);
            }
            if (labels.length === 0) {
                throw new RuntimeError('Expected at least one input/output pair.');
            }
        }
        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$1[this.type.kind.toLowerCase()](outputLower, outputUpper, t);
        } 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()
        ];
        if (this.dynamicStops) {
            serialized.push(this.dynamicStops.serialize());
        } else {
            for (let i = 0; i < this.labels.length; i++) {
                serialized.push(this.labels[i], this.outputs[i].serialize());
            }
        }
        return serialized;
    }
}
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);
    }
}

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, void 0, { typeAnnotation: 'omit' });
            if (!parsed)
                return null;
            outputType = outputType || parsed.type;
            parsedArgs.push(parsed);
        }
        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);
            if (result && result instanceof ResolvedImage && !result.available) {
                if (!firstImage) {
                    firstImage = result;
                }
                result = null;
                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;
    }
}

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;
    }
}

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(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 array2 = this.input.evaluate(ctx);
        if (index < 0) {
            throw new RuntimeError(`Array index out of bounds: ${ index } < 0.`);
        }
        if (index > array2.length - 1) {
            throw new RuntimeError(`Array index out of bounds: ${ index } > ${ array2.length - 1 }.`);
        }
        if (index === Math.floor(index)) {
            return array2[index];
        }
        const lowerIndex = Math.floor(index);
        const upperIndex = Math.ceil(index);
        const lowerValue = array2[lowerIndex];
        const upperValue = array2[upperIndex];
        if (typeof lowerValue !== 'number' || typeof upperValue !== 'number') {
            throw new RuntimeError(`Cannot interpolate between non-number values at index ${ index }.`);
        }
        const fraction = index - lowerIndex;
        return lowerValue * (1 - fraction) + upperValue * fraction;
    }
    eachChild(fn) {
        fn(this.index);
        fn(this.input);
    }
    outputDefined() {
        return false;
    }
    serialize() {
        return [
            'at',
            this.index.serialize(),
            this.input.serialize()
        ];
    }
}

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(`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(`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()
        ];
    }
}

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(`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(`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 !== void 0) {
            const fromIndex = this.fromIndex.serialize();
            return [
                'index-of',
                this.needle.serialize(),
                this.haystack.serialize(),
                fromIndex
            ];
        }
        return [
            'index-of',
            this.needle.serialize(),
            this.haystack.serialize()
        ];
    }
}

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()
        ];
        const sortedLabels = Object.keys(this.cases).sort();
        const groupedByOutput = [];
        const outputLookup = {};
        for (const label of sortedLabels) {
            const outputIndex = outputLookup[this.cases[label]];
            if (outputIndex === void 0) {
                outputLookup[this.cases[label]] = groupedByOutput.length;
                groupedByOutput.push([
                    this.cases[label],
                    [label]
                ]);
            } else {
                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) {
                serialized.push(coerceLabel(labels[0]));
            } else {
                serialized.push(labels.map(coerceLabel));
            }
            serialized.push(this.outputs[outputIndex].serialize());
        }
        serialized.push(this.otherwise.serialize());
        return serialized;
    }
}

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;
    }
}

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(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(`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 !== void 0) {
            const endIndex = this.endIndex.serialize();
            return [
                'slice',
                this.input.serialize(),
                this.beginIndex.serialize(),
                endIndex
            ];
        }
        return [
            'slice',
            this.input.serialize(),
            this.beginIndex.serialize()
        ];
    }
}

function isComparableType(op, type) {
    if (op === '==' || op === '!=') {
        return type.kind === 'boolean' || type.kind === 'string' || type.kind === 'number' || type.kind === 'null' || type.kind === 'value';
    } else {
        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;
}
function makeComparison(op, compareBasic, compareWithCollator) {
    const isOrderComparison = op !== '==' && op !== '!=';
    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';
        }
        static parse(args, context) {
            if (args.length !== 3 && args.length !== 4)
                return context.error(`Expected two or three arguments.`);
            const op2 = args[0];
            let lhs = context.parse(args[1], 1, ValueType);
            if (!lhs)
                return null;
            if (!isComparableType(op2, lhs.type)) {
                return context.concat(1).error(`"${ op2 }" comparisons are not supported for type '${ toString$1(lhs.type) }'.`);
            }
            let rhs = context.parse(args[2], 2, ValueType);
            if (!rhs)
                return null;
            if (!isComparableType(op2, rhs.type)) {
                return context.concat(2).error(`"${ op2 }" 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) {
                if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {
                    lhs = new Assertion(rhs.type, [lhs]);
                } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {
                    rhs = new Assertion(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 lt2 = typeOf(lhs);
                const rt = typeOf(rhs);
                if (lt2.kind !== rt.kind || !(lt2.kind === 'string' || lt2.kind === 'number')) {
                    throw new RuntimeError(`Expected arguments for "${ op }" to be (string, string) or (number, number), but found (${ lt2.kind }, ${ rt.kind }) instead.`);
                }
            }
            if (this.collator && !isOrderComparison && this.hasUntypedArgument) {
                const lt2 = typeOf(lhs);
                const rt = typeOf(rhs);
                if (lt2.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 {
    // 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.parseObjectValue(options['locale'], 2, 'locale', StringType);
            if (!locale)
                return null;
        }
        let currency = null;
        if (options['currency']) {
            currency = context.parseObjectValue(options['currency'], 2, 'currency', StringType);
            if (!currency)
                return null;
        }
        let unit = null;
        if (options['unit']) {
            unit = context.parseObjectValue(options['unit'], 2, 'unit', StringType);
            if (!unit)
                return null;
        }
        let minFractionDigits = null;
        if (options['min-fraction-digits']) {
            minFractionDigits = context.parseObjectValue(options['min-fraction-digits'], 2, 'min-fraction-digits', NumberType);
            if (!minFractionDigits)
                return null;
        }
        let maxFractionDigits = null;
        if (options['max-fraction-digits']) {
            maxFractionDigits = context.parseObjectValue(options['max-fraction-digits'], 2, 'max-fraction-digits', 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) : void 0,
            unit: this.unit ? this.unit.evaluate(ctx) : void 0,
            minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : void 0,
            maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : void 0
        }).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(`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;
    }
}

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,
    'array': Assertion,
    'at': At,
    'boolean': Assertion,
    'case': Case,
    'coalesce': Coalesce,
    'collator': CollatorExpression,
    'format': FormatExpression,
    'image': ImageExpression,
    'in': In,
    'index-of': IndexOf,
    'interpolate': Interpolate,
    'interpolate-hcl': Interpolate,
    'interpolate-lab': Interpolate,
    'length': Length,
    'let': Let,
    'literal': Literal,
    'match': Match,
    'number': Assertion,
    'number-format': NumberFormat,
    'object': Assertion,
    'slice': Slice,
    'step': Step,
    'string': Assertion,
    'to-boolean': Coercion,
    'to-color': Coercion,
    'to-number': Coercion,
    'to-string': Coercion,
    'var': Var,
    'within': Within,
    'distance': Distance,
    'config': Config
};
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(error);
    return new Color(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(error);
    const colorFunction = `hsla(${ h }, ${ s }%, ${ l }%, ${ alpha })`;
    const color = Color.parse(colorFunction);
    if (!color)
        throw new RuntimeError(`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 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.register(expressions, {
    'error': [
        ErrorType,
        [StringType],
        (ctx, [v]) => {
            throw new RuntimeError(v.evaluate(ctx));
        }
    ],
    'typeof': [
        StringType,
        [ValueType],
        (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx)))
    ],
    'to-rgba': [
        array(NumberType, 4),
        [ColorType],
        (ctx, [v]) => {
            return v.evaluate(ctx).toRenderColor(null).toArray();
        }
    ],
    'to-hsla': [
        array(NumberType, 4),
        [ColorType],
        (ctx, [v]) => {
            return v.evaluate(ctx).toRenderColor(null).toHslaArray();
        }
    ],
    '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))
            ]
        ]
    },
    '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
    ],
    'raster-particle-speed': [
        NumberType,
        [],
        ctx => ctx.globals.rasterParticleSpeed || 0
    ],
    'sky-radial-progress': [
        NumberType,
        [],
        ctx => ctx.globals.skyRadialProgress || 0
    ],
    'accumulated': [
        ValueType,
        [],
        ctx => ctx.globals.accumulated === void 0 ? 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);
            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() !== void 0
    ],
    'filter-type-in': [
        BooleanType,
        [array(StringType)],
        (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0
    ],
    'filter-id-in': [
        BooleanType,
        [array(ValueType)],
        (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0
    ],
    'filter-in-small': [
        BooleanType,
        [
            StringType,
            array(ValueType)
        ],
        // assumes v is an array literal
        (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0
    ],
    'filter-in-large': [
        BooleanType,
        [
            StringType,
            array(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(`Invalid seed input: ${ seed }`);
            }
            const random = mulberry32(seedVal)();
            return min + random * (max - min);
        }
    ]
});

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 supportsLineProgressExpression(spec) {
    return expressionHasParameter(spec.expression, 'line-progress');
}
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 !== void 0;
    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.parse(stop[1])
                ];
            });
        }
        if (parameters.default) {
            parameters.default = Color.parse(parameters.default);
        } else {
            parameters.default = Color.parse(propertySpec.default);
        }
    }
    if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) {
        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;
        hashedStops = /* @__PURE__ */
        Object.create(null);
        for (const stop of parameters.stops) {
            hashedStops[stop[0]] = stop[1];
        }
        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] === void 0) {
                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.interpolationFactor.bind(void 0, 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 !== void 0 ? parameters.base : 1
        } : null;
        return {
            kind: 'camera',
            interpolationType,
            interpolationFactor: Interpolate.interpolationFactor.bind(void 0, 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] : void 0;
                if (value === void 0) {
                    return coalesce(parameters.default, propertySpec.default);
                }
                return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);
            }
        };
    }
}
function coalesce(a, b, c) {
    if (a !== void 0)
        return a;
    if (b !== void 0)
        return b;
    if (c !== void 0)
        return c;
}
function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {
    const evaluated = typeof input === keyType ? hashedStops[input] : void 0;
    return coalesce(evaluated, parameters.default, propertySpec.default);
}
function evaluateIntervalFunction(parameters, propertySpec, input) {
    if (getType(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 !== void 0 ? parameters.base : 1;
    if (getType(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$1[propertySpec.type] || identityFunction;
    if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {
        const colorspace = colorSpaces[parameters.colorSpace];
        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(void 0, args);
                const evaluatedUpper = outputUpper.evaluate.apply(void 0, args);
                if (evaluatedLower === void 0 || evaluatedUpper === void 0) {
                    return void 0;
                }
                return interp(evaluatedLower, evaluatedUpper, t);
            }
        };
    }
    return interp(outputLower, outputUpper, t);
}
function evaluateIdentityFunction(parameters, propertySpec, input) {
    if (propertySpec.type === 'color') {
        input = Color.parse(input);
    } else if (propertySpec.type === 'formatted') {
        input = Formatted.fromString(input.toString());
    } else if (propertySpec.type === 'resolvedImage') {
        input = ResolvedImage.build(input.toString());
    } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {
        input = void 0;
    }
    return coalesce(input, parameters.default, propertySpec.default);
}
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, scope, options) {
        this.expression = expression;
        this._warningHistory = {};
        this._evaluator = new EvaluationContext(scope, options);
        this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;
        this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;
        this.configDependencies = getConfigDependencies(expression);
    }
    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);
            if (val === null || val === void 0 || typeof val === 'number' && val !== val) {
                return this._defaultValue;
            }
            if (this._enumValues && !(val in this._enumValues)) {
                throw new RuntimeError(`Expected value to be one of ${ Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ') }, but found ${ JSON.stringify(val) } instead.`);
            }
            return val;
        } catch (e) {
            if (!this._warningHistory[e.message]) {
                this._warningHistory[e.message] = true;
                if (typeof console !== 'undefined') {
                    console.warn(`Failed to evaluate expression "${ JSON.stringify(this.expression.serialize()) }". ${ e.message }`);
                }
            }
            return this._defaultValue;
        }
    }
}
function isExpression(expression) {
    return Array.isArray(expression) && expression.length > 0 && typeof expression[0] === 'string' && expression[0] in expressions;
}
function createExpression(expression, propertySpec, scope, options) {
    const parser = new ParsingContext$1(expressions, [], propertySpec ? getExpectedType(propertySpec) : void 0, void 0, void 0, scope, options);
    const parsed = parser.parse(expression, void 0, void 0, void 0, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : void 0);
    if (!parsed) {
        return error(parser.errors);
    }
    return success(new StyleExpression(parsed, propertySpec, scope, options));
}
class ZoomConstantExpression {
    constructor(kind, expression, isLightConstant, isLineProgressConstant) {
        this.kind = kind;
        this._styleExpression = expression;
        this.isLightConstant = isLightConstant;
        this.isLineProgressConstant = isLineProgressConstant;
        this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression);
        this.configDependencies = getConfigDependencies(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, isLineProgressConstant) {
        this.kind = kind;
        this.zoomStops = zoomStops;
        this._styleExpression = expression;
        this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression);
        this.isLightConstant = isLightConstant;
        this.isLineProgressConstant = isLineProgressConstant;
        this.configDependencies = getConfigDependencies(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.interpolationFactor(this.interpolationType, input, lower, upper);
        } else {
            return 0;
        }
    }
}
function createPropertyExpression(expression, propertySpec, scope, options) {
    expression = createExpression(expression, propertySpec, scope, 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('', 'data expressions not supported')]);
    }
    const isZoomConstant = isGlobalPropertyConstant(parsed, [
        'zoom',
        'pitch',
        'distance-from-center'
    ]);
    if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {
        return error([new ParsingError('', 'zoom expressions not supported')]);
    }
    const isLightConstant = isGlobalPropertyConstant(parsed, ['measure-light']);
    if (!isLightConstant && !supportsLightExpression(propertySpec)) {
        return error([new ParsingError('', 'measure-light expression not supported')]);
    }
    const isLineProgressConstant = isGlobalPropertyConstant(parsed, ['line-progress']);
    if (!isLineProgressConstant && !supportsLineProgressExpression(propertySpec)) {
        return error([new ParsingError('', 'line-progress expression not supported')]);
    }
    const canRelaxZoomRestriction = propertySpec.expression && propertySpec.expression.relaxZoomRestriction;
    const zoomCurve = findZoomCurve(parsed);
    if (!zoomCurve && !isZoomConstant && !canRelaxZoomRestriction) {
        return error([new ParsingError('', '"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) {
        return error([zoomCurve]);
    } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {
        return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]);
    }
    if (!zoomCurve) {
        return success(isFeatureConstant$1 && isLineProgressConstant ? // @ts-expect-error - TS2339 - Property 'value' does not exist on type 'unknown'.
        new ZoomConstantExpression('constant', expression.value, isLightConstant, isLineProgressConstant) : // @ts-expect-error - TS2339 - Property 'value' does not exist on type 'unknown'.
        new ZoomConstantExpression('source', expression.value, isLightConstant, isLineProgressConstant));
    }
    const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : void 0;
    return success(isFeatureConstant$1 && isLineProgressConstant ? // @ts-expect-error - TS2339 - Property 'value' does not exist on type 'unknown'.
    new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType, isLightConstant, isLineProgressConstant) : // @ts-expect-error - TS2339 - Property 'value' does not exist on type 'unknown'.
    new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType, isLightConstant, isLineProgressConstant));
}
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, scope, options) {
    if (isFunction(value)) {
        return new StylePropertyFunction(value, specification);
    } else if (isExpression(value) || Array.isArray(value) && value.length > 0) {
        const expression = createPropertyExpression(value, specification, scope, options);
        if (expression.result === 'error') {
            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.parse(value);
        }
        return {
            kind: 'constant',
            configDependencies: /* @__PURE__ */
            new Set(),
            evaluate: () => constant
        };
    }
}
function findZoomCurve(expression) {
    let result = null;
    if (expression instanceof Let) {
        result = findZoomCurve(expression.result);
    } else if (expression instanceof Coalesce) {
        for (const arg of expression.args) {
            result = findZoomCurve(arg);
            if (result) {
                break;
            }
        }
    } else if ((expression instanceof Step || expression instanceof Interpolate) && expression.input instanceof CompoundExpression && expression.input.name === 'zoom') {
        result = expression;
    }
    if (result instanceof ParsingError) {
        return result;
    }
    expression.eachChild(child => {
        const childResult = findZoomCurve(child);
        if (childResult instanceof ParsingError) {
            result = childResult;
        } else if (result && childResult && result !== childResult) {
            result = new ParsingError('', '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(types[spec.value] || ValueType, spec.length);
    }
    return types[spec.type];
}
function getDefaultValue(spec) {
    if (spec.type === 'color' && (isFunction(spec.default) || Array.isArray(spec.default))) {
        return new Color(0, 0, 0, 0);
    } else if (spec.type === 'color') {
        return Color.parse(spec.default) || null;
    } else if (spec.default === void 0) {
        return null;
    } else {
        return spec.default;
    }
}

var gridIndex;
var hasRequiredGridIndex;

function requireGridIndex () {
	if (hasRequiredGridIndex) return gridIndex;
	hasRequiredGridIndex = 1;
	gridIndex = GridIndex;
	var NUM_PARAMS = 3;
	function GridIndex(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.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.prototype._insertReadonly = function () {
	    throw 'Cannot insert into a GridIndex created from an ArrayBuffer.';
	};
	GridIndex.prototype._insertCell = function (x1, y1, x2, y2, cellIndex, uid) {
	    this.cells[cellIndex].push(uid);
	};
	GridIndex.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.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.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.prototype._convertFromCellCoord = function (x) {
	    return (x - this.padding) / this.scale;
	};
	GridIndex.prototype._convertToCellCoord = function (x) {
	    return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));
	};
	GridIndex.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;
	};
	return gridIndex;
}

var gridIndexExports = requireGridIndex();
var Grid = /*@__PURE__*/getDefaultExportFromCjs(gridIndexExports);

const registry = {};
function register(klass, name, options = {}) {
    Object.defineProperty(klass, '_classRegistryKey', {
        value: name,
        writable: false
    });
    registry[name] = {
        klass,
        omit: options.omit || []
    };
}
register(Object, 'Object');
Grid.serialize = function serialize2(grid, transferables) {
    const buffer = grid.toArrayBuffer();
    if (transferables) {
        transferables.add(buffer);
    }
    return { buffer };
};
Grid.deserialize = function deserialize2(serialized) {
    return new Grid(serialized.buffer);
};
Object.defineProperty(Grid, 'name', { value: 'Grid' });
register(Grid, 'Grid');
if (typeof DOMMatrix !== 'undefined') {
    register(DOMMatrix, 'DOMMatrix');
}
register(Color, 'Color');
register(Error, 'Error');
register(Formatted, 'Formatted');
register(FormattedSection, 'FormattedSection');
register(AJAXError, 'AJAXError');
register(ResolvedImage, 'ResolvedImage');
register(StylePropertyFunction, 'StylePropertyFunction');
register(StyleExpression, 'StyleExpression', { omit: ['_evaluator'] });
register(ImageIdWithOptions, 'ImageIdWithOptions');
register(ZoomDependentExpression, 'ZoomDependentExpression');
register(ZoomConstantExpression, 'ZoomConstantExpression');
register(CompoundExpression, 'CompoundExpression', { omit: ['_evaluate'] });
for (const name in expressions) {
    if (!registry[expressions[name]._classRegistryKey])
        register(expressions[name], `Expression${ name }`);
}
function isArrayBuffer(val) {
    return val && typeof ArrayBuffer !== 'undefined' && (val instanceof ArrayBuffer || val.constructor && val.constructor.name === 'ArrayBuffer');
}
function isImageBitmap(val) {
    return self.ImageBitmap && val instanceof ImageBitmap;
}
function serialize(input, transferables) {
    if (input === null || input === void 0 || 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)) {
        if (transferables) {
            transferables.add(input.buffer);
        }
        return input;
    }
    if (input instanceof 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 (input instanceof Set) {
        const properties = { '$name': 'Set' };
        let idx = 0;
        for (const value of input.values()) {
            properties[++idx] = 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 ? // (Temporary workaround) allow a class to provide static
        // `serialize()` and `deserialize()` methods to bypass the generic
        // approach.
        // This temporary workaround lets us use the generic serialization
        // approach for objects whose members include instances of dynamic
        // StructArray types. Once we refactor StructArray to be static,
        // we can remove this complexity.
        klass.serialize(input, transferables) : {};
        if (!klass.serialize) {
            for (const key in input) {
                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(input) {
    if (input === null || input === void 0 || 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 ImageData) {
        return input;
    }
    if (Array.isArray(input)) {
        return input.map(deserialize);
    }
    if (typeof input === 'object') {
        const name = input.$name || 'Object';
        if (name === 'Map') {
            const map = /* @__PURE__ */
            new Map();
            for (const key of Object.keys(input)) {
                if (key === '$name')
                    continue;
                const value = input[key];
                map.set(key, deserialize(value));
            }
            return map;
        }
        if (name === 'Set') {
            const set = /* @__PURE__ */
            new Set();
            for (const key of Object.keys(input)) {
                if (key === '$name')
                    continue;
                const value = input[key];
                set.add(deserialize(value));
            }
            return set;
        }
        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)) {
            if (key === '$name')
                continue;
            const value = input[key];
            result[key] = deserialize(value);
        }
        return result;
    }
    throw new Error(`can't deserialize object of type ${ typeof input }`);
}

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 >= 66736 && char <= 66815,
    // '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    // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F,
              // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F,
              // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF,
              // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF,
              // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F,
              // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F,
              // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF,
              // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF,
              // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF,
};

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) {
    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;
}
function charHasUprightVerticalOrientation(char) {
    if (char === 746 || char === 747) {
        return true;
    }
    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 && 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 && char <= 12305) && !(char >= 12308 && char <= 12319) && char !== 12336) {
            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) {
            return true;
        }
    }
    if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) {
        if (char !== 65288 && char !== 65289 && char !== 65293 && !(char >= 65306 && char <= 65310) && char !== 65339 && char !== 65341 && char !== 65343 && !(char >= 65371 && char <= 65503) && char !== 65507 && !(char >= 65512 && char <= 65519)) {
            return true;
        }
    }
    if (unicodeBlockLookup['Small Form Variants'](char)) {
        if (!(char >= 65112 && char <= 65118) && !(char >= 65123 && 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;
}
function charHasNeutralVerticalOrientation(char) {
    if (unicodeBlockLookup['Latin-1 Supplement'](char)) {
        if (char === 167 || char === 169 || char === 174 || char === 177 || char === 188 || char === 189 || char === 190 || char === 215 || char === 247) {
            return true;
        }
    }
    if (unicodeBlockLookup['General Punctuation'](char)) {
        if (char === 8214 || char === 8224 || char === 8225 || char === 8240 || char === 8241 || char === 8251 || char === 8252 || char === 8258 || char === 8263 || char === 8264 || char === 8265 || char === 8273) {
            return true;
        }
    }
    if (unicodeBlockLookup['Letterlike Symbols'](char))
        return true;
    if (unicodeBlockLookup['Number Forms'](char))
        return true;
    if (unicodeBlockLookup['Miscellaneous Technical'](char)) {
        if (char >= 8960 && char <= 8967 || char >= 8972 && char <= 8991 || char >= 8996 && char <= 9000 || char === 9003 || char >= 9085 && char <= 9114 || char >= 9150 && char <= 9165 || char === 9167 || char >= 9169 && char <= 9179 || char >= 9186 && char <= 9215) {
            return true;
        }
    }
    if (unicodeBlockLookup['Control Pictures'](char) && char !== 9251)
        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 && char <= 9759)) {
            return true;
        }
    }
    if (unicodeBlockLookup['Miscellaneous Symbols and Arrows'](char)) {
        if (char >= 11026 && char <= 11055 || char >= 11088 && char <= 11097 || char >= 11192 && 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 || char === 8756 || char === 8757 || char >= 9984 && char <= 10087 || char >= 10102 && char <= 10131 || char === 65532 || char === 65533) {
        return true;
    }
    return false;
}
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) {
    return char >= 1424 && char <= 2303 || unicodeBlockLookup['Arabic Presentation Forms-A'](char) || unicodeBlockLookup['Arabic Presentation Forms-B'](char);
}
function charInSupportedScript(char, canRenderRTL) {
    if (!canRenderRTL && charInRTLScript(char)) {
        return false;
    }
    if (char >= 2304 && char <= 3583 || // Main blocks for Indic scripts and Sinhala
        char >= 3840 && char <= 4255 || // Main blocks for Tibetan and Myanmar
        unicodeBlockLookup['Khmer'](char)) {
        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;
let pluginStatus = status.unavailable;
let pluginURL = null;
const triggerPluginCompletionEvent = function (error) {
    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) {
    callback({
        pluginStatus,
        pluginURL
    });
    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();
    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;
    },
    isLoading() {
        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());
    }
}

class PropertyValue {
    constructor(property, value, scope, options) {
        this.property = property;
        this.value = value;
        this.expression = normalizePropertyExpression(value === void 0 ? property.specification.default : value, property.specification, scope, options);
    }
    isDataDriven() {
        return this.expression.kind === 'source' || this.expression.kind === 'composite';
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);
    }
}
class TransitionablePropertyValue {
    constructor(property, scope, options) {
        this.property = property;
        this.value = new PropertyValue(property, void 0, scope, 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);
    }
}
class Transitionable {
    constructor(properties, scope, options) {
        this._properties = properties;
        this._values = Object.create(properties.defaultTransitionablePropertyValues);
        this._scope = scope;
        this._options = options;
        this.configDependencies = /* @__PURE__ */
        new Set();
    }
    getValue(name) {
        return clone(this._values[name].value.value);
    }
    setValue(name, value) {
        if (!this._values.hasOwnProperty(name)) {
            this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._scope, this._options);
        }
        this._values[name].value = new PropertyValue(this._values[name].property, value === null ? void 0 : clone(value), this._scope, this._options);
        if (this._values[name].value.expression.configDependencies) {
            this.configDependencies = /* @__PURE__ */
            new Set([
                ...this.configDependencies,
                ...this._values[name].value.expression.configDependencies
            ]);
        }
    }
    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.hasOwnProperty(name)) {
                    this.setValue(name, value);
                }
            }
        }
    }
    getTransition(name) {
        return clone(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(value) || void 0;
    }
    serialize() {
        const result = {};
        for (const property of Object.keys(this._values)) {
            const value = this.getValue(property);
            if (value !== void 0) {
                result[property] = value;
            }
            const transition = this.getTransition(property);
            if (transition !== void 0) {
                result[`${ property }-transition`] = transition;
            }
        }
        return result;
    }
    transitioned(parameters, prior) {
        const result = new Transitioning(this._properties);
        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);
        for (const property of Object.keys(this._values)) {
            result._values[property] = this._values[property].untransitioned();
        }
        return result;
    }
}
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) {
            return finalValue;
        } else if (now > this.end) {
            this.prior = null;
            return finalValue;
        } else if (this.value.isDataDriven()) {
            this.prior = null;
            return finalValue;
        } else if (now < this.begin) {
            return prior.possiblyEvaluate(parameters, canonical, availableImages);
        } else {
            const t = (now - this.begin) / (this.end - this.begin);
            return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));
        }
    }
}
class Transitioning {
    constructor(properties) {
        this._properties = properties;
        this._values = Object.create(properties.defaultTransitioningPropertyValues);
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        const result = new PossiblyEvaluated(this._properties);
        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;
    }
}
class Layout {
    constructor(properties, scope, options) {
        this._properties = properties;
        this._values = Object.create(properties.defaultPropertyValues);
        this._scope = scope;
        this._options = options;
        this.configDependencies = /* @__PURE__ */
        new Set();
    }
    getValue(name) {
        return clone(this._values[name].value);
    }
    setValue(name, value) {
        this._values[name] = new PropertyValue(this._values[name].property, value === null ? void 0 : clone(value), this._scope, this._options);
        if (this._values[name].expression.configDependencies) {
            this.configDependencies = /* @__PURE__ */
            new Set([
                ...this.configDependencies,
                ...this._values[name].expression.configDependencies
            ]);
        }
    }
    serialize() {
        const result = {};
        for (const property of Object.keys(this._values)) {
            const value = this.getValue(property);
            if (value !== void 0) {
                result[property] = value;
            }
        }
        return result;
    }
    possiblyEvaluate(parameters, canonical, availableImages) {
        const result = new PossiblyEvaluated(this._properties);
        for (const property of Object.keys(this._values)) {
            result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);
        }
        return result;
    }
}
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);
    }
}
class PossiblyEvaluated {
    constructor(properties) {
        this._properties = properties;
        this._values = Object.create(properties.defaultPossiblyEvaluatedValues);
    }
    get(name) {
        return this._values[name];
    }
}
class DataConstantProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters) {
        return value.expression.evaluate(parameters);
    }
    interpolate(a, b, t) {
        const interp = interpolate$1[this.specification.type];
        if (interp) {
            return interp(a, b, t);
        } else {
            return a;
        }
    }
}
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') {
            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 (a.value.kind !== 'constant' || b.value.kind !== 'constant') {
            return a;
        }
        if (a.value.value === void 0 || b.value.value === void 0) {
            return new PossiblyEvaluatedPropertyValue(this, {
                kind: 'constant',
                value: void 0
            }, a.parameters);
        }
        const interp = interpolate$1[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 {
            return value.evaluate(parameters, feature, featureState, canonical, availableImages);
        }
    }
}
class ColorRampProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters, canonical, availableImages) {
        return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages);
    }
    interpolate() {
        return false;
    }
}
class DirectionProperty {
    constructor(specification) {
        this.specification = specification;
    }
    possiblyEvaluate(value, parameters) {
        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) {
        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)
        };
    }
}
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, void 0);
            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');

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","optional":true},"fog":{"type":"fog"},"snow":{"type":"snow","experimental":true},"rain":{"type":"rain","experimental":true},"camera":{"type":"camera"},"color-theme":{"type":"colorTheme"},"indoor":{"type":"indoor","experimental":true},"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"},"featuresets":{"experimental":true,"type":"featuresets"}},"featuresets":{"experimental":true,"*":{"type":"featureset"}},"featureset":{"experimental":true,"metadata":{"experimental":true,"type":"*"},"selectors":{"experimental":true,"type":"array","value":"selector"}},"selector":{"experimental":true,"layer":{"experimental":true,"type":"string","required":true},"properties":{"experimental":true,"type":"selectorProperty","required":false},"featureNamespace":{"experimental":true,"type":"string","required":false},"_uniqueFeatureID":{"experimental":true,"type":"boolean","private":true,"required":false}},"selectorProperty":{"experimental":true,"*":{"experimental":true,"type":"*"}},"model":{"type":"string","required":true},"import":{"id":{"type":"string","required":true},"url":{"type":"string","required":true},"config":{"type":"config"},"data":{"type":"$root"},"color-theme":{"type":"colorTheme","optional":true}},"config":{"*":{"type":"*"}},"schema":{"*":{"type":"option"}},"option":{"default":{"type":"*","property-type":"data-constant","expression":{},"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,"property-type":"data-constant"},"shadow-quality":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1,"expression":{"parameters":["zoom"]},"experimental":true},"shadow-intensity":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"properties_light_ambient":{"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"properties_light_flat":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"property-type":"data-constant","expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","property-type":"data-constant","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"sources":{"*":{"type":"source"}},"source":["source_vector","source_raster","source_raster_dem","source_raster_array","source_geojson","source_video","source_image","source_model"],"source_vector":{"type":{"required":true,"type":"enum","values":{"vector":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"scheme":{"type":"enum","values":{"xyz":1,"tms":1},"default":"xyz"},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"attribution":{"type":"string"},"promoteId":{"type":"promoteId"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_raster":{"type":{"required":true,"type":"enum","values":{"raster":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"tileSize":{"type":"number","default":512},"scheme":{"type":"enum","values":{"xyz":1,"tms":1},"default":"xyz"},"attribution":{"type":"string"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_raster_dem":{"type":{"required":true,"type":"enum","values":{"raster-dem":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"tileSize":{"type":"number","default":512},"attribution":{"type":"string"},"encoding":{"type":"enum","values":{"terrarium":1,"mapbox":1},"default":"mapbox"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_raster_array":{"experimental":true,"type":{"required":true,"type":"enum","values":{"raster-array":1}},"url":{"type":"string"},"tiles":{"type":"array","value":"string"},"bounds":{"type":"array","value":"number","length":4,"default":[-180,-85.051129,180,85.051129]},"minzoom":{"type":"number","default":0},"maxzoom":{"type":"number","default":22},"tileSize":{"type":"number","default":512},"attribution":{"type":"string"},"rasterLayers":{"type":"*"},"volatile":{"type":"boolean","default":false},"*":{"type":"*"}},"source_geojson":{"type":{"required":true,"type":"enum","values":{"geojson":1}},"data":{"type":"*"},"maxzoom":{"type":"number","default":18},"minzoom":{"type":"number","default":0},"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"},"dynamic":{"type":"boolean","default":false}},"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":{},"raster-particle":{"experimental":true},"hillshade":{},"model":{"experimental":true},"background":{},"sky":{},"slot":{},"clip":{}},"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_clip","layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_raster-particle","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_clip":{"clip-layer-types":{"type":"array","value":"enum","values":{"model":1,"symbol":1},"default":[],"expression":{},"property-type":"data-constant"},"clip-layer-scope":{"type":"array","value":"string","default":[],"expression":{},"property-type":"data-constant"}},"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"},"fill-elevation-reference":{"type":"enum","values":{"none":1,"hd-road-base":1,"hd-road-markup":1},"default":"none","experimental":true,"private":true,"expression":{},"property-type":"data-constant"}},"layout_circle":{"circle-sort-key":{"type":"number","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"circle-elevation-reference":{"type":"enum","values":{"none":1,"hd-road-markup":1},"default":"none","experimental":true,"expression":{},"property-type":"data-constant"},"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","experimental":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,"none":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"},"line-z-offset":{"type":"number","experimental":true,"default":0,"expression":{"parameters":["zoom","feature","line-progress"]},"property-type":"data-driven"},"line-elevation-reference":{"type":"enum","values":{"none":1,"sea":1,"ground":1,"hd-road-markup":1},"default":"none","experimental":true,"expression":{},"property-type":"data-constant"},"line-cross-slope":{"type":"number","experimental":true,"expression":{},"property-type":"constant"},"visibility":{"type":"enum","values":{"visible":1,"none":1},"default":"visible","expression":{},"property-type":"constant"},"line-width-unit":{"type":"enum","values":{"pixels":1,"meters":1},"default":"pixels","experimental":true,"private":true,"expression":{"parameters":["zoom"]},"property-type":"data-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"},"symbol-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1,"hd-road-markup":1},"default":"ground","experimental":true,"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-size-scale-range":{"type":"array","value":"number","length":2,"default":[0.8,2],"minimum":0.1,"maximum":10,"experimental":true,"private":true,"expression":{},"property-type":"data-constant"},"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-size-scale-range":{"type":"array","value":"number","length":2,"default":[0.8,2],"minimum":0.1,"maximum":10,"experimental":true,"private":true,"expression":{},"property-type":"data-constant"},"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_raster-particle":{"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_hillshade":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_raster":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_raster-particle":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_clip":{"type":"boolean","default":false,"property-type":"data-driven","expression":{"parameters":["zoom","feature"]}},"filter_model":{"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}}},"snow":{"density":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","property-type":"data-constant","default":"#ffffff","experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"opacity":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","property-type":"data-constant","default":"#ffffff","experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"center-thinning":{"type":"number","property-type":"data-constant","default":0.4,"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","property-type":"data-constant","transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","property-type":"data-constant","default":0.71,"minimum":0,"maximum":5,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","property-type":"data-constant","default":1,"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","property-type":"data-constant","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"opacity":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","property-type":"data-constant","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","property-type":"data-constant","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"center-thinning":{"type":"number","property-type":"data-constant","default":0.57,"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","property-type":"data-constant","transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","property-type":"data-constant","transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","property-type":"data-constant","default":0.7,"minimum":0,"maximum":1,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective","property-type":"data-constant"}},"colorTheme":{"data":{"type":"string","property-type":"data-constant","expression":{}}},"indoor":{"floorplanFeaturesetId":{"type":"string","experimental":true,"property-type":"data-constant","expression":{}},"buildingFeaturesetId":{"type":"string","experimental":true,"property-type":"data-constant","expression":{}}},"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_raster-particle","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"},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"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-height-alignment":{"type":"enum","experimental":true,"values":{"terrain":1,"flat":1},"default":"flat","property-type":"data-constant"},"fill-extrusion-base-alignment":{"type":"enum","experimental":true,"values":{"terrain":1,"flat":1},"default":"terrain","property-type":"data-constant"},"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","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"property-type":"data-constant","type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"property-type":"data-constant","type":"number","experimental":true,"default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"property-type":"data-constant","type":"number","experimental":true,"default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"property-type":"data-constant","type":"number","experimental":true,"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","experimental":true,"default":"#ffffff","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"property-type":"data-constant","type":"number","experimental":true,"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","experimental":true,"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","experimental":true,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"property-type":"data-constant","type":"number","experimental":true,"default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"property-type":"data-constant","type":"number","experimental":true,"default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"property-type":"data-constant","type":"boolean","default":true,"experimental":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{},"property-type":"data-constant"},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true,"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","line-progress"]},"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-trim-fade-range":{"type":"array","value":"number","experimental":true,"length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"line-trim-color":{"type":"color","experimental":true,"default":"transparent","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-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"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true,"property-type":"data-constant"}},"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-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"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","feature-state"]},"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"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-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{},"property-type":"data-constant"},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{},"property-type":"data-constant"},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{},"property-type":"data-constant"},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{},"property-type":"data-constant"},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"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","length":2,"value":"number","property-type":"data-constant","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"raster-array-band":{"type":"string","required":false,"experimental":true,"property-type":"data-constant"},"raster-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"experimental":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string","required":false,"property-type":"data-constant"},"raster-particle-count":{"type":"number","default":512,"minimum":1,"property-type":"data-constant"},"raster-particle-color":{"type":"color","expression":{"interpolated":true,"parameters":["raster-particle-speed"]},"property-type":"color-ramp"},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1,"property-type":"data-constant"},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1,"property-type":"data-constant"},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"hillshade-accent-color":{"type":"color","default":"#000000","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-constant"}},"paint_background":{"background-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":[]},"experimental":true,"property-type":"data-constant"},"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":["feature","feature-state","zoom"]},"property-type":"data-driven"},"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,"property-type":"data-constant"},"model-receive-shadows":{"type":"boolean","default":true,"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"},"model-front-cutoff":{"type":"array","private":true,"value":"number","property-type":"data-constant","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]}},"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":"*"}}}');

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);
}

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;
    }
}
function createFilter(filter, scope = '', options = null, layerType = 'fill') {
    if (filter === null || filter === void 0) {
        return {
            filter: () => true,
            needGeometry: false,
            needFeature: false
        };
    }
    if (!isExpressionFilter(filter)) {
        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) }
        `);
    }
    let filterFunc = null;
    let filterSpec = null;
    if (layerType !== 'background' && layerType !== 'sky' && layerType !== 'slot') {
        filterSpec = spec[`filter_${ layerType }`];
        const compiledStaticFilter = createExpression(staticFilter, filterSpec, scope, options);
        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);
        }
    }
    let dynamicFilterFunc = null;
    let needFeature = null;
    if (staticFilter !== filterExp) {
        const compiledDynamicFilter = createExpression(filterExp, filterSpec, scope, options);
        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, void 0, void 0, featureTileCoord, featureDistanceData);
            needFeature = !isFeatureConstant(compiledDynamicFilter.value.expression);
        }
    }
    filterFunc = filterFunc;
    const needGeometry = geometryNeeded(staticFilter);
    return {
        filter: filterFunc,
        dynamicFilter: dynamicFilterFunc ? dynamicFilterFunc : void 0,
        needGeometry,
        needFeature: !!needFeature
    };
}
function extractStaticFilter(filter) {
    if (!isDynamicFilter(filter)) {
        return filter;
    }
    let result = deepUnbundle(filter);
    unionDynamicBranches(result);
    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));
    }
}
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);
    }
    for (let i = 1; i < filter.length; i++) {
        unionDynamicBranches(filter[i]);
    }
}
function isDynamicFilter(filter) {
    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 = /* @__PURE__ */
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;
}
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)) : // @ts-expect-error - TS2769 - No overload matches this call.
    op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) : // @ts-expect-error - TS2769 - No overload matches this call.
    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
    ];
}

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;
}
function getScopeFromFQID(fqid) {
    const sep = fqid.indexOf(FQIDSeparator);
    return sep >= 0 ? fqid.slice(sep + 1) : '';
}

const TRANSITION_SUFFIX = '-transition';
const drapedLayers = /* @__PURE__ */
new Set([
    'fill',
    'line',
    'background',
    'hillshade',
    'raster'
]);
class StyleLayer extends Evented {
    constructor(layer, properties, scope, lut, options) {
        super();
        this.id = layer.id;
        this.fqid = makeFQID(this.id, scope);
        this.type = layer.type;
        this.scope = scope;
        this.lut = lut;
        this.options = options;
        this._featureFilter = {
            filter: () => true,
            needGeometry: false,
            needFeature: false
        };
        this._filterCompiled = false;
        this.configDependencies = /* @__PURE__ */
        new Set();
        if (layer.type === 'custom')
            return;
        layer = layer;
        this.metadata = layer.metadata;
        this.minzoom = layer.minzoom;
        this.maxzoom = layer.maxzoom;
        if (layer.type && layer.type !== 'background' && layer.type !== 'sky' && layer.type !== 'slot') {
            this.source = layer.source;
            this.sourceLayer = layer['source-layer'];
            this.filter = layer.filter;
            const filterSpec = spec[`filter_${ layer.type }`];
            const compiledStaticFilter = createExpression(this.filter, filterSpec);
            if (compiledStaticFilter.result !== 'error') {
                this.configDependencies = /* @__PURE__ */
                new Set([
                    ...this.configDependencies,
                    ...compiledStaticFilter.value.configDependencies
                ]);
            }
        }
        if (layer.slot)
            this.slot = layer.slot;
        if (properties.layout) {
            this._unevaluatedLayout = new Layout(properties.layout, this.scope, options);
            this.configDependencies = /* @__PURE__ */
            new Set([
                ...this.configDependencies,
                ...this._unevaluatedLayout.configDependencies
            ]);
        }
        if (properties.paint) {
            this._transitionablePaint = new Transitionable(properties.paint, this.scope, options);
            for (const property in layer.paint) {
                this.setPaintProperty(property, layer.paint[property]);
            }
            for (const property in layer.layout) {
                this.setLayoutProperty(property, layer.layout[property]);
            }
            this.configDependencies = /* @__PURE__ */
            new Set([
                ...this.configDependencies,
                ...this._transitionablePaint.configDependencies
            ]);
            this._transitioningPaint = this._transitionablePaint.untransitioned();
            this.paint = new PossiblyEvaluated(properties.paint);
        }
    }
    // No-op in the StyleLayer class, must be implemented by each concrete StyleLayer
    onAdd(_map) {
    }
    // No-op in the StyleLayer class, must be implemented by each concrete StyleLayer
    onRemove(_map) {
    }
    isDraped(_sourceCache) {
        return !this.is3D() && drapedLayers.has(this.type);
    }
    getLayoutProperty(name) {
        if (name === 'visibility') {
            return this.visibility;
        }
        return this._unevaluatedLayout.getValue(name);
    }
    setLayoutProperty(name, value) {
        if (this.type === 'custom' && name === 'visibility') {
            this.visibility = value;
            return;
        }
        const layout = this._unevaluatedLayout;
        const specProps = layout._properties.properties;
        if (!specProps[name])
            return;
        layout.setValue(name, value);
        this.configDependencies = /* @__PURE__ */
        new Set([
            ...this.configDependencies,
            ...layout.configDependencies
        ]);
        if (name === 'visibility') {
            this.possiblyEvaluateVisibility();
        }
    }
    possiblyEvaluateVisibility() {
        if (!this._unevaluatedLayout._values.visibility) {
            return;
        }
        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) {
        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]) {
                paint.setTransition(propName, value || void 0);
            }
            return false;
        }
        if (!specProps[name])
            return false;
        const transitionable = paint._values[name];
        const wasDataDriven = transitionable.value.isDataDriven();
        const oldValue = transitionable.value;
        paint.setValue(name, value);
        this.configDependencies = /* @__PURE__ */
        new Set([
            ...this.configDependencies,
            ...paint.configDependencies
        ]);
        this._handleSpecialPaintPropertyUpdate(name);
        const newValue = paint._values[name].value;
        const isDataDriven = newValue.isDataDriven();
        const isPattern = endsWith(name, 'pattern') || name === 'line-dasharray';
        return isDataDriven || wasDataDriven || isPattern || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue);
    }
    _handleSpecialPaintPropertyUpdate(_) {
    }
    getProgramIds() {
        return null;
    }
    // eslint-disable-next-line no-unused-vars
    getDefaultProgramParams(name, zoom, lut) {
        return null;
    }
    // eslint-disable-next-line no-unused-vars
    _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) {
        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, void 0, availableImages);
        }
        this.paint = this._transitioningPaint.possiblyEvaluate(parameters, void 0, 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 !== void 0 && !(key === 'layout' && !Object.keys(value).length) && !(key === 'paint' && !Object.keys(value).length);
        });
    }
    is3D() {
        return false;
    }
    isSky() {
        return false;
    }
    isTileClipped() {
        return false;
    }
    hasOffscreenPass() {
        return false;
    }
    hasShadowPass() {
        return false;
    }
    canCastShadows() {
        return false;
    }
    hasLightBeamPass() {
        return false;
    }
    cutoffRange() {
        return 0;
    }
    tileCoverLift() {
        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(options) {
        if (!this._filterCompiled) {
            this._featureFilter = createFilter(this.filter, this.scope, options);
            this._filterCompiled = true;
        }
    }
    invalidateCompiledFilter() {
        this._filterCompiled = false;
    }
    dynamicFilter() {
        return this._featureFilter.dynamicFilter;
    }
    dynamicFilterNeedsFeature() {
        return this._featureFilter.needFeature;
    }
    getLayerRenderingStats() {
        return this._stats;
    }
    resetLayerRenderingStats(painter) {
        if (this._stats) {
            if (painter.renderPass === 'shadow') {
                this._stats.numRenderedVerticesInShadowPass = 0;
            } else {
                this._stats.numRenderedVerticesInTransparentPass = 0;
            }
        }
    }
    // @ts-expect-error - TS2355 - A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.
    queryRadius(_bucket) {
    }
    queryIntersectsFeature(_queryGeometry, _feature, _featureState, _geometry, _zoom, _transform, _pixelPosMatrix, _elevationHelper, _layoutVertexArrayOffset) {
    }
}

const viewTypes = {
    'Int8': Int8Array,
    'Uint8': Uint8Array,
    'Int16': Int16Array,
    'Uint16': Uint16Array,
    'Int32': Int32Array,
    'Uint32': Uint32Array,
    'Float32': Float32Array
};
class Struct {
    /**
   * @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;
class StructArray {
    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) {
        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('StructArray#_refreshViews() must be implemented by each concrete StructArray layout');
    }
    emplace(..._) {
        throw new Error('StructArray#emplace() must be implemented by each concrete StructArray layout');
    }
    emplaceBack(..._) {
        throw new Error('StructArray#emplaceBack() must be implemented by each concrete StructArray layout');
    }
    destroy() {
        this.int8 = this.uint8 = this.int16 = this.uint16 = this.int32 = this.uint32 = this.float32 = null;
        this.arrayBuffer = null;
    }
}
function 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;
}

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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
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');
class StructArrayLayout2ub4f20 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(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 o1 = i * 20;
        const o4 = i * 5;
        this.uint8[o1 + 0] = v0;
        this.uint8[o1 + 1] = v1;
        this.float32[o4 + 1] = v2;
        this.float32[o4 + 2] = v3;
        this.float32[o4 + 3] = v4;
        this.float32[o4 + 4] = v5;
        return i;
    }
}
StructArrayLayout2ub4f20.prototype.bytesPerElement = 20;
register(StructArrayLayout2ub4f20, 'StructArrayLayout2ub4f20');
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');
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');
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');
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');
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');
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');
class StructArrayLayout11f44 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) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) {
        const o4 = i * 11;
        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;
        return i;
    }
}
StructArrayLayout11f44.prototype.bytesPerElement = 44;
register(StructArrayLayout11f44, 'StructArrayLayout11f44');
class StructArrayLayout9f36 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) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) {
        const o4 = i * 9;
        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;
        return i;
    }
}
StructArrayLayout9f36.prototype.bytesPerElement = 36;
register(StructArrayLayout9f36, 'StructArrayLayout9f36');
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');
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');
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');
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');
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');
class StructArrayLayout1i2 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.int16 = new Int16Array(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.int16[o2 + 0] = v0;
        return i;
    }
}
StructArrayLayout1i2.prototype.bytesPerElement = 2;
register(StructArrayLayout1i2, 'StructArrayLayout1i2');
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;
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;
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;
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');
class GlyphOffsetArray extends StructArrayLayout1f4 {
    getoffsetX(index) {
        return this.float32[index * 1 + 0];
    }
}
register(GlyphOffsetArray, 'GlyphOffsetArray');
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;
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');
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');
class FillExtrusionWallStruct extends Struct {
    get a_join_normal_inside0() {
        return this._structArray.int16[this._pos2 + 0];
    }
    get a_join_normal_inside1() {
        return this._structArray.int16[this._pos2 + 1];
    }
    get a_join_normal_inside2() {
        return this._structArray.int16[this._pos2 + 2];
    }
}
FillExtrusionWallStruct.prototype.size = 6;
class FillExtrusionWallArray extends StructArrayLayout3i6 {
    /**
   * Return the FillExtrusionWallStruct at the given location in the array.
   * @param {number} index The index of the element.
   * @private
   */
    get(index) {
        return new FillExtrusionWallStruct(this, index);
    }
}
register(FillExtrusionWallArray, 'FillExtrusionWallArray');

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 !== void 0)
                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
            }]);
    }
}
SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;
register(SegmentVector, 'SegmentVector');

function packUint8ToFloat(a, b) {
    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]
]);

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);
        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();
        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(String(value));
}
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;
    }
    set(_program, _name, _v) {
        throw new Error('Uniform#set() must be implemented by each concrete Uniform');
    }
}
class Uniform1i extends Uniform {
    constructor(context) {
        super(context);
        this.current = 0;
    }
    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;
    }
    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
        ];
    }
    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
        ];
    }
    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
        ];
    }
    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.transparent.toRenderColor(null);
    }
    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 = new Float32Array(16);
class UniformMatrix4f extends Uniform {
    constructor(context) {
        super(context);
        this.current = emptyMat4;
    }
    set(program, name, v) {
        if (!this.fetchUniformLocation(program, name))
            return;
        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;
    }
    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;
    }
    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)
    ];
}
class ConstantBinder {
    constructor(value, names, type, context) {
        this.value = value;
        this.uniformNames = names.map(name => `u_${ name }`);
        this.type = type;
        this.context = context;
    }
    setUniform(program, uniform, globals, currentValue, uniformName) {
        const value = currentValue.constantOr(this.value);
        if (value instanceof Color) {
            uniform.set(program, uniformName, value.toRenderColor(this.ignoreLut ? null : this.context.lut));
        } else {
            uniform.set(program, uniformName, value);
        }
    }
    getBinding(context, _) {
        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);
    }
    getBinding(context, name) {
        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;
        const value = this.expression.kind === 'composite' || this.expression.kind === 'source' ? this.expression.evaluate(new EvaluationParameters(0, { brightness }), feature, {}, canonical, availableImages, formattedSection) : this.expression.kind === 'constant' && this.expression.value;
        if (this.lutExpression && (this.lutExpression.kind === 'composite' || this.lutExpression.kind === 'source'))
            this.ignoreLut = this.lutExpression.evaluate(new EvaluationParameters(0, { brightness }), feature, {}, canonical, availableImages, formattedSection) === 'none';
        this.paintVertexArray.resize(newLength);
        this._setPaintValue(start, newLength, value, this.context);
    }
    updatePaintArray(start, end, feature, featureState, availableImages, spritePositions, brightness) {
        const value = this.expression.kind === 'composite' || this.expression.kind === 'source' ? this.expression.evaluate({
            zoom: 0,
            brightness
        }, feature, featureState, void 0, availableImages) : this.expression.kind === 'constant' && this.expression.value;
        if (this.lutExpression && (this.lutExpression.kind === 'composite' || this.lutExpression.kind === 'source'))
            this.ignoreLut = this.lutExpression.evaluate({
                zoom: 0,
                brightness
            }, feature, featureState, void 0, availableImages) === 'none';
        this._setPaintValue(start, end, value, this.context);
    }
    _setPaintValue(start, end, value, context) {
        if (this.type === 'color') {
            const color = packColor(value.toRenderColor(this.ignoreLut ? null : context.lut));
            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 {
                const dynamicDraw = this.lutExpression && this.lutExpression.kind !== 'constant' && (this.lutExpression.isStateDependent || !this.lutExpression.isLightConstant) || this.expression.kind !== 'constant' && (this.expression.isStateDependent || !this.expression.isLightConstant);
                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, dynamicDraw);
            }
        }
    }
    destroy() {
        if (this.paintVertexBuffer) {
            this.paintVertexBuffer.destroy();
        }
    }
}
class CompositeExpressionBinder {
    constructor(expression, names, type, useIntegerZoom, context, PaintVertexArray) {
        this.expression = expression;
        this.uniformNames = names.map(name => `u_${ name }_t`);
        this.type = type;
        this.useIntegerZoom = useIntegerZoom;
        this.context = context;
        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) {
        const min = this.expression.evaluate(new EvaluationParameters(this.context.zoom, { brightness }), feature, {}, canonical, availableImages, formattedSection);
        const max = this.expression.evaluate(new EvaluationParameters(this.context.zoom + 1, { brightness }), feature, {}, canonical, availableImages, formattedSection);
        if (this.lutExpression && (this.lutExpression.kind === 'composite' || this.lutExpression.kind === 'source'))
            this.ignoreLut = this.lutExpression.evaluate(new EvaluationParameters(this.context.zoom, { brightness }), feature, {}, canonical, availableImages, formattedSection) === 'none';
        const start = this.paintVertexArray.length;
        this.paintVertexArray.resize(newLength);
        this._setPaintValue(start, newLength, min, max, this.context);
    }
    updatePaintArray(start, end, feature, featureState, availableImages, spritePositions, brightness) {
        const min = this.expression.evaluate({
            zoom: this.context.zoom,
            brightness
        }, feature, featureState, void 0, availableImages);
        const max = this.expression.evaluate({
            zoom: this.context.zoom + 1,
            brightness
        }, feature, featureState, void 0, availableImages);
        if (this.lutExpression && (this.lutExpression.kind === 'composite' || this.lutExpression.kind === 'source'))
            this.ignoreLut = this.lutExpression.evaluate({
                zoom: this.context.zoom,
                brightness
            }, feature, featureState, void 0, availableImages) === 'none';
        this._setPaintValue(start, end, min, max, this.context);
    }
    _setPaintValue(start, end, min, max, context) {
        if (this.type === 'color') {
            const minColor = packColor(min.toRenderColor(this.ignoreLut ? null : context.lut));
            const maxColor = packColor(min.toRenderColor(this.ignoreLut ? null : context.lut));
            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.context.zoom, this.context.zoom + 1), 0, 1);
        uniform.set(program, uniformName, factor);
    }
    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, _availableImages) {
        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();
    }
}
class ProgramConfiguration {
    constructor(layer, context, filterProperties = () => true) {
        this.binders = {};
        this._buffers = [];
        this.context = context;
        const keys = [];
        for (const property in layer.paint._values) {
            const value = layer.paint.get(property);
            const valueUseTheme = layer.paint.get(`${ property }-use-theme`);
            if (property.endsWith('-use-theme'))
                continue;
            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' || valueUseTheme && valueUseTheme.value.kind !== 'constant';
            if (expression.kind === 'constant' && !sourceException) {
                this.binders[property] = isPattern ? new PatternConstantBinder(expression.value, names) : new ConstantBinder(expression.value, names, type, context);
                keys.push(`/u_${ property }`);
            } else if (expression.kind === 'source' || sourceException || isPattern) {
                const StructArrayLayout = layoutType(property, type, 'source');
                this.binders[property] = isPattern ? // @ts-expect-error - TS2345 - Argument of type 'PossiblyEvaluatedValue<any>' is not assignable to parameter of type 'CompositeExpression'.
                new PatternCompositeBinder(expression, names, type, StructArrayLayout, layer.id) : new SourceExpressionBinder(expression, names, type, StructArrayLayout);
                keys.push(`/a_${ property }`);
            } else {
                const StructArrayLayout = layoutType(property, type, 'composite');
                this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, context, StructArrayLayout);
                keys.push(`/z_${ property }`);
            }
            if (valueUseTheme) {
                this.binders[property].ignoreLut = valueUseTheme.constantOr('default') === 'none';
                const expressionLUT = valueUseTheme.value;
                this.binders[property].lutExpression = expressionLUT;
                this.binders[property].checkUseTheme = true;
            }
        }
        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];
            binder.context = this.context;
            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)
                binder.populatePaintArray(newLength, feature, imagePositions, availableImages, canonical, brightness, formattedSection);
            else if (binder.lutExpression) {
                if (binder instanceof ConstantBinder && binder.lutExpression && (binder.lutExpression.kind === 'composite' || binder.lutExpression.kind === 'source'))
                    binder.ignoreLut = binder.lutExpression.evaluate(new EvaluationParameters(0, { brightness }), feature, {}, canonical, availableImages, formattedSection) === 'none';
            }
        }
    }
    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, isBrightnessChanged, brightness) {
        let dirty = false;
        const keys = Object.keys(featureStates);
        const featureStateUpdate = keys.length !== 0 && !isBrightnessChanged;
        const ids = featureStateUpdate ? keys : featureMap.uniqueIds;
        this.context.lut = layer.lut;
        for (const property in this.binders) {
            const binder = this.binders[property];
            binder.context = this.context;
            const isExpressionNotConst = binder.expression && binder.expression.kind && binder.expression.kind !== 'constant';
            if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder) && isExpressionNotConst && (binder.expression.isStateDependent === true || binder.expression.isLightConstant === false)) {
                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) {
        for (const {name, property, binding} of binderUniforms) {
            if (this.binders[property].checkUseTheme && this.binders[property] instanceof ConstantBinder) {
                const pvalue = properties.get(`${ property }-use-theme`);
                if (pvalue.isConstant())
                    this.binders[property].ignoreLut = pvalue.constantOr('default') === 'none';
            }
            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, context, filterProperties = () => true) {
        this.programConfigurations = {};
        for (const layer of layers) {
            this.programConfigurations[layer.id] = new ProgramConfiguration(layer, context, 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 !== void 0) {
            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, isBrightnessChanged, brightness) {
        for (const layer of layers) {
            this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, this._featureMapWithoutIds, vtLayer, layer, availableImages, imagePositions, isBrightnessChanged, 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-occlusion-opacity': ['occlusion_opacity'],
    'icon-occlusion-opacity': ['occlusion_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'],
    'symbol-z-offset': ['z_offset'],
    '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];
    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');

const GLOBE_RADIUS = EXTENT / Math.PI / 2;
const GLOBE_ZOOM_THRESHOLD_MIN = 5;
const GLOBE_ZOOM_THRESHOLD_MAX = 6;
const GLOBE_SCALE_MATCH_LATITUDE = 45;
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;

function csLatLngToECEF(cosLat, sinLat, lng, radius = GLOBE_RADIUS) {
    lng = degToRad(lng);
    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(radToDeg(lng), radToDeg(lat));
}
function latLngToECEF(lat, lng, radius) {
    return csLatLngToECEF(Math.cos(degToRad(lat)), Math.sin(degToRad(lat)), lng, radius);
}
const earthRadius = 6371008.8;
const earthCircumference = 2 * Math.PI * earthRadius;
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({
            lng: this.lng - lngAccuracy,
            lat: this.lat - latAccuracy
        }, {
            lng: this.lng + lngAccuracy,
            lat: this.lat + latAccuracy
        });
    }
    toEcef(altitude) {
        const altInEcef = altitude * GLOBE_RADIUS / earthRadius;
        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(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>]');
    }
}
class LngLatBounds {
    constructor(sw, ne) {
        if (!sw) ; else if (ne) {
            this.setSouthWest(sw).setNorthEast(ne);
        } else if (sw.length === 4) {
            const bounds = sw;
            this.setSouthWest([
                bounds[0],
                bounds[1]
            ]).setNorthEast([
                bounds[2],
                bounds[3]
            ]);
        } else {
            const bounds = sw;
            this.setSouthWest(bounds[0]).setNorthEast(bounds[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 ? new LngLat(ne.lng, ne.lat) : LngLat.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 ? new LngLat(sw.lng, sw.lat) : LngLat.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) {
            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)) {
            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.convert(lngLatObj));
            }
        } else if (typeof obj === 'object' && obj !== null && obj.hasOwnProperty('lat') && (obj.hasOwnProperty('lon') || obj.hasOwnProperty('lng'))) {
            return this.extend(LngLat.convert(obj));
        } else {
            return this;
        }
        if (!sw && !ne) {
            this._sw = new LngLat(sw2.lng, sw2.lat);
            this._ne = new LngLat(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((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(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(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.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) {
            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)
            return;
        if (input instanceof LngLatBounds)
            return input;
        return new LngLatBounds(input);
    }
}

const DEFAULT_MIN_ZOOM = 0;
const DEFAULT_MAX_ZOOM = 25.5;
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, DEFAULT_MAX_ZOOM);
    const constrainedScale = Math.pow(2, constrainedZoom);
    return getLatitudeScale(lat) * earthCircumference / (constrainedScale * 512);
}
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));
    return circumferenceAtEquator * 2 * exp / (exp * exp + 1) / EXTENT / (1 << canonical.z);
}
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.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(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() {
        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(mx1, my1);
    reproject(mid);
    const err = pointToLineDist(mid.x, mid.y, start.x, start.y, end.x, end.y);
    if (err >= tolerance) {
        addResampled(resampled, mx0, my0, mx1, my1, start, mid, reproject, tolerance);
        addResampled(resampled, mx1, my1, mx2, my2, mid, end, reproject, tolerance);
    } else {
        resampled.push(end);
    }
}
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 (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;
}

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) {
        warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');
    }
    return point;
}
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);
            } else {
                const line = [];
                for (const p of geometry[i]) {
                    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;
}

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);
}
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, {
            zoom: options.zoom,
            lut: options.lut
        });
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
    }
    updateFootprints(_id, _footprints) {
    }
    populate(features, options, canonical, tileTransform) {
        const styleLayer = this.layers[0];
        const bucketFeatures = [];
        let circleSortKey = null;
        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);
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const sortKey = circleSortKey ? circleSortKey.evaluate(evaluationFeature, {}, canonical) : void 0;
            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) => {
                return a.sortKey - b.sortKey;
            });
        }
        let globeProjection = null;
        if (tileTransform.projection.name === 'globe') {
            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, layers, isBrightnessChanged, brightness) {
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, 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;
                if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT)
                    continue;
                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 index2 = 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(index2, index2 + 1, index2 + 2);
                this.indexArray.emplaceBack(index2, index2 + 2, index2 + 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;
        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++) {
        const v = line[i - 1], w = line[i];
        if (distToSegmentSquared(p, v, w) < radiusSquared)
            return true;
    }
    return false;
}
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));
}
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(boxX1, boxY1),
        new Point(boxX1, boxY2),
        new Point(boxX2, boxY2),
        new Point(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];
    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;
    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]);
}
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) {
    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(translate2) {
    return Math.sqrt(translate2[0] * translate2[0] + translate2[1] * translate2[1]);
}
function translate(queryGeometry, translate2, translateAnchor, bearing, pixelsToTileUnits) {
    if (!translate2[0] && !translate2[1]) {
        return queryGeometry;
    }
    const pt = Point.convert(translate2)._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(translate2, translateAnchor, bearing, pixelsToTileUnits) {
    const pt = Point.convert(translate2)._mult(pixelsToTileUnits);
    if (translateAnchor === 'viewport') {
        pt._rotate(-bearing);
    }
    return pt;
}

let layout$e;
const getLayoutProperties$c = () => layout$e || (layout$e = new Properties({
    'circle-sort-key': new DataDrivenProperty(spec['layout_circle']['circle-sort-key']),
    'circle-elevation-reference': new DataConstantProperty(spec['layout_circle']['circle-elevation-reference']),
    'visibility': new DataConstantProperty(spec['layout_circle']['visibility'])
}));
let paint$d;
const getPaintProperties$d = () => paint$d || (paint$d = 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']),
    'circle-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'circle-stroke-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

var whootsJs = {exports: {}};

var hasRequiredWhootsJs;

function requireWhootsJs () {
	if (hasRequiredWhootsJs) return whootsJs.exports;
	hasRequiredWhootsJs = 1;
	(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));
	return whootsJs.exports;
}

var whootsJsExports = requireWhootsJs();

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) {
            return false;
        }
        const zDifference = this.canonical.z - parent.canonical.z;
        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 [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) {
    const dim = 1 << Math.min(z, 22);
    let xy = dim * (y % dim) + x % dim;
    if (wrap && z < 22) {
        const bitsAvailable = 2 * (22 - z);
        xy += dim * dim * ((wrap < 0 ? -2 * wrap - 1 : 2 * wrap) % (1 << bitsAvailable));
    }
    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;
}
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',
        'expandedProjMatrix'
    ]
});

const layout$d = 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$d;

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

class Ray2D {
    constructor(pos_, dir_) {
        this.pos = pos_;
        this.dir = dir_;
    }
    intersectsPlane(pt, normal, out) {
        const D = cjsExports.vec2.dot(normal, this.dir);
        if (Math.abs(D) < 0.000001) {
            return false;
        }
        const t = ((pt[0] - this.pos[0]) * normal[0] + (pt[1] - this.pos[1]) * normal[1]) / D;
        out[0] = this.pos[0] + this.dir[0] * t;
        out[1] = this.pos[1] + this.dir[1] * t;
        return true;
    }
}
class Ray {
    constructor(pos_, dir_) {
        this.pos = pos_;
        this.dir = dir_;
    }
    intersectsPlane(pt, normal, out) {
        const D = cjsExports.vec3.dot(normal, this.dir);
        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 (cjsExports.vec3.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) {
            const t = Math.max(-b / 2, 0);
            const gx = px + dx * t;
            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) {
                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 = cjsExports.vec3.transformMat4(TLClip, TLClip, invProj);
        const TR = cjsExports.vec3.transformMat4(TRClip, TRClip, invProj);
        const BR = cjsExports.vec3.transformMat4(BRClip, BRClip, invProj);
        const BL = cjsExports.vec3.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) {
        cjsExports.vec3.sub(vec, point, origin);
        const projection = cjsExports.vec3.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 += cjsExports.vec3.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 (cjsExports.vec4.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 = [];
        this.frustumEdges = [
            cjsExports.vec3.sub([], this.points[NEAR_BR], this.points[NEAR_BL]),
            cjsExports.vec3.sub([], this.points[NEAR_TL], this.points[NEAR_BL]),
            cjsExports.vec3.sub([], this.points[FAR_TL], this.points[NEAR_TL]),
            cjsExports.vec3.sub([], this.points[FAR_TR], this.points[NEAR_TR]),
            cjsExports.vec3.sub([], this.points[FAR_BR], this.points[NEAR_BR]),
            cjsExports.vec3.sub([], this.points[FAR_BL], this.points[NEAR_BL])
        ];
        for (const edge of this.frustumEdges) {
            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);
        const frustumCoords = clipSpaceCorners.map(v => {
            const s = cjsExports.vec4.transformMat4([], v, invProj);
            const k = 1 / s[3] / worldSize * scale;
            return cjsExports.vec4.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 = cjsExports.vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);
            const b = cjsExports.vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);
            const n = cjsExports.vec3.normalize([], cjsExports.vec3.cross([], a, b));
            const d = -cjsExports.vec3.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) {
        for (let i = 0; i < faces.length; i++) {
            if (!pointsInsideOfPlane(vertices, faces[i])) {
                return 0;
            }
        }
        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 = cjsExports.vec3.cross([], edge, frustumEdge);
                const len = cjsExports.vec3.length(axis);
                if (len === 0) {
                    continue;
                }
                cjsExports.vec3.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;
    }
    containsPoint(point) {
        for (const plane of this.planes) {
            const normal = [
                plane[0],
                plane[1],
                plane[2]
            ];
            const distance = plane[3];
            if (cjsExports.vec3.dot(normal, point) + distance < 0) {
                return false;
            }
        }
        return true;
    }
}
class Aabb {
    static fromPoints(points) {
        const min = [
            Infinity,
            Infinity,
            Infinity
        ];
        const max = [
            -Infinity,
            -Infinity,
            -Infinity
        ];
        for (const p of points) {
            cjsExports.vec3.min(min, min, p);
            cjsExports.vec3.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) {
            cjsExports.vec3.transformMat4(corners[i], corners[i], transform);
        }
        return Aabb.fromPoints(corners);
    }
    // A fast version of applyTransform. Note that it breaks down for non-uniform
    // scale and complex projection matrices.
    static applyTransformFast(aabb, transform) {
        const min = [
            transform[12],
            transform[13],
            transform[14]
        ];
        const max = [...min];
        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 3; j++) {
                const value = transform[j * 4 + i];
                const a = value * aabb.min[j];
                const b = value * aabb.max[j];
                min[i] += Math.min(a, b);
                max[i] += Math.max(a, b);
            }
        }
        return new Aabb(min, max);
    }
    static projectAabbCorners(aabb, transform) {
        const corners = aabb.getCorners();
        for (let i = 0; i < corners.length; ++i) {
            cjsExports.vec3.transformMat4(corners[i], corners[i], transform);
        }
        return corners;
    }
    constructor(min_, max_) {
        this.min = min_;
        this.max = max_;
        this.center = cjsExports.vec3.scale([], cjsExports.vec3.add([], this.min, this.max), 0.5);
    }
    quadrant(index) {
        const split = [
            index % 2 === 0,
            index < 2
        ];
        const qMin = cjsExports.vec3.clone(this.min);
        const qMax = cjsExports.vec3.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];
        }
        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) {
        if (!this.intersectsAabb(frustum.bounds)) {
            return 0;
        }
        return intersectsFrustum(frustum, this.getCorners());
    }
    intersectsFlat(frustum) {
        if (!this.intersectsAabb(frustum.bounds)) {
            return 0;
        }
        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;
            }
        }
        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');

function globeMetersToEcef(d) {
    return d * GLOBE_RADIUS / earthRadius;
}
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 globePointCoordinate(tr, x, y, clampToHorizon = true) {
    const point0 = cjsExports.vec3.scale([], tr._camera.position, tr.worldSize);
    const point1 = [
        x,
        y,
        1,
        1
    ];
    cjsExports.vec4.transformMat4(point1, point1, tr.pixelMatrixInverse);
    cjsExports.vec4.scale(point1, point1, 1 / point1[3]);
    const p0p1 = cjsExports.vec3.sub([], point1, point0);
    const dir = cjsExports.vec3.normalize([], p0p1);
    const m = tr.globeMatrix;
    const globeCenter = [
        m[12],
        m[13],
        m[14]
    ];
    const p0toCenter = cjsExports.vec3.sub([], globeCenter, point0);
    const p0toCenterDist = cjsExports.vec3.length(p0toCenter);
    const centerDir = cjsExports.vec3.normalize([], p0toCenter);
    const radius = tr.worldSize / (2 * Math.PI);
    const cosAngle = cjsExports.vec3.dot(centerDir, dir);
    const origoTangentAngle = Math.asin(radius / p0toCenterDist);
    const origoDirAngle = Math.acos(cosAngle);
    if (origoTangentAngle < origoDirAngle) {
        if (!clampToHorizon)
            return null;
        const clampedP1 = [];
        const origoToP1 = [];
        cjsExports.vec3.scale(clampedP1, dir, p0toCenterDist / cosAngle);
        cjsExports.vec3.normalize(origoToP1, cjsExports.vec3.sub(origoToP1, clampedP1, p0toCenter));
        cjsExports.vec3.normalize(dir, cjsExports.vec3.add(dir, p0toCenter, cjsExports.vec3.scale(dir, origoToP1, Math.tan(origoTangentAngle) * p0toCenterDist)));
    }
    const pointOnGlobe = [];
    const ray = new Ray(point0, dir);
    ray.closestPointOnSphere(globeCenter, radius, pointOnGlobe);
    const xa = cjsExports.vec3.normalize([], getColumn(m, 0));
    const ya = cjsExports.vec3.normalize([], getColumn(m, 1));
    const za = cjsExports.vec3.normalize([], getColumn(m, 2));
    const xp = cjsExports.vec3.dot(xa, pointOnGlobe);
    const yp = cjsExports.vec3.dot(ya, pointOnGlobe);
    const zp = cjsExports.vec3.dot(za, pointOnGlobe);
    const lat = radToDeg(Math.asin(-yp / radius));
    let lng = radToDeg(Math.atan2(xp, zp));
    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 = cjsExports.vec3.sub([], p0, center);
        this.b = cjsExports.vec3.sub([], p1, center);
        this.center = center;
        const an = cjsExports.vec3.normalize([], this.a);
        const bn = cjsExports.vec3.normalize([], this.b);
        this.angle = Math.acos(cjsExports.vec3.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);
}
function localExtremum(arc, dim) {
    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];
    }
    const bounds = tileCornersToBounds(id);
    const corners = boundsToECEF(bounds);
    return Aabb.fromPoints(corners);
}
function interpolateVec3(from, to, phase) {
    cjsExports.vec3.scale(from, from, 1 - phase);
    return cjsExports.vec3.scaleAndAdd(from, from, to, phase);
}
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;
    const nw = [
        w,
        n,
        0
    ];
    const ne = [
        e,
        n,
        0
    ];
    const sw = [
        w,
        s,
        0
    ];
    const se = [
        e,
        s,
        0
    ];
    const worldToECEFMatrix = cjsExports.mat4.invert([], tr.globeMatrix);
    cjsExports.vec3.transformMat4(nw, nw, worldToECEFMatrix);
    cjsExports.vec3.transformMat4(ne, ne, worldToECEFMatrix);
    cjsExports.vec3.transformMat4(sw, sw, worldToECEFMatrix);
    cjsExports.vec3.transformMat4(se, se, worldToECEFMatrix);
    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) {
        cjsExports.vec3.transformMat4(corner, corner, globeMatrix);
        cjsExports.vec3.scale(corner, corner, scale);
    }
}
function aabbForTileOnGlobe(tr, numTiles, tileId, extendToPoles) {
    const scale = numTiles / tr.worldSize;
    const m = tr.globeMatrix;
    if (tileId.z <= 1) {
        const corners2 = globeTileBounds(tileId).getCorners();
        transformPoints(corners2, m, scale);
        return Aabb.fromPoints(corners2);
    }
    const bounds = tileCornersToBounds(tileId, extendToPoles);
    const corners = boundsToECEF(bounds, GLOBE_RADIUS + globeMetersToEcef(tr._tileCoverLift));
    transformPoints(corners, m, scale);
    const mx = Number.MAX_VALUE;
    const cornerMax = [
        -mx,
        -mx,
        -mx
    ];
    const cornerMin = [
        mx,
        mx,
        mx
    ];
    if (bounds.contains(tr.center)) {
        for (const corner of corners) {
            cjsExports.vec3.min(cornerMin, cornerMin, corner);
            cjsExports.vec3.max(cornerMax, cornerMax, corner);
        }
        cornerMax[2] = 0;
        const point = tr.point;
        const center = [
            point.x * scale,
            point.y * scale,
            0
        ];
        cjsExports.vec3.min(cornerMin, cornerMin, center);
        cjsExports.vec3.max(cornerMax, cornerMax, center);
        return new Aabb(cornerMin, cornerMax);
    }
    if (tr._tileCoverLift > 0) {
        for (const corner of corners) {
            cjsExports.vec3.min(cornerMin, cornerMin, corner);
            cjsExports.vec3.max(cornerMax, cornerMax, corner);
        }
        return new Aabb(cornerMin, cornerMax);
    }
    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);
    if (dx > 0.5) {
        dx -= 1;
    } else if (dx < -0.5) {
        dx += 1;
    }
    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;
        cjsExports.vec3.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);
        for (let i = 0; i < corners.length; i++) {
            interpolateVec3(corners[i], mercatorCorners[i], phase);
        }
        const mercatorMidpoint = cjsExports.vec3.add([], mercatorCorners[closestArcIdx], mercatorCorners[(closestArcIdx + 1) % 4]);
        cjsExports.vec3.scale(mercatorMidpoint, mercatorMidpoint, 0.5);
        interpolateVec3(arcExtremum, mercatorMidpoint, phase);
    }
    for (const corner of corners) {
        cjsExports.vec3.min(cornerMin, cornerMin, corner);
        cjsExports.vec3.max(cornerMax, cornerMax, corner);
    }
    cornerMin[2] = Math.min(arcStart[2], arcEnd[2]);
    cjsExports.vec3.min(cornerMin, cornerMin, arcExtremum);
    cjsExports.vec3.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(lngFromMercatorX(x * s), y === (1 << z) - 1 && extendToPoles ? -90 : latFromMercatorY((y + 1) * s));
    const ne = new LngLat(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);
    let w = x * tileScale;
    let e = w + tileScale;
    let n = y * tileScale;
    let s = n + tileScale;
    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;
    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, radius = GLOBE_RADIUS) {
    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, radius),
        csLatLngToECEF(cosS, sinS, e, radius),
        csLatLngToECEF(cosN, sinN, e, radius),
        csLatLngToECEF(cosN, sinN, w, 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);
    cjsExports.vec3.transformMat4(origin, origin, normalizationMatrix);
    cjsExports.vec3.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]);
}
const tempMatrix = new Float64Array(16);
function globeNormalizeECEF(bounds) {
    const scale = globeECEFNormalizationScale(bounds);
    const m = cjsExports.mat4.fromScaling(tempMatrix, [
        scale,
        scale,
        scale
    ]);
    return cjsExports.mat4.translate(m, m, cjsExports.vec3.negate([], bounds.min));
}
function globeDenormalizeECEF(bounds) {
    const m = cjsExports.mat4.fromTranslation(tempMatrix, bounds.min);
    const scale = 1 / globeECEFNormalizationScale(bounds);
    return cjsExports.mat4.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) {
    const scale = globeECEFUnitsToPixelScale(worldSize);
    const offset = [
        x,
        y,
        -worldSize / (2 * Math.PI)
    ];
    const m = cjsExports.mat4.identity(new Float64Array(16));
    cjsExports.mat4.translate(m, m, offset);
    cjsExports.mat4.scale(m, m, [
        scale,
        scale,
        scale
    ]);
    cjsExports.mat4.rotateX(m, m, degToRad(-lat));
    cjsExports.mat4.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;
    const m = calculateGlobePosMatrix(x, y, tr.worldSize / tr._pixelsPerMercatorPixel, 0, 0);
    return cjsExports.mat4.multiply(m, m, globeDenormalizeECEF(globeTileBounds(id)));
}
function calculateGlobeMercatorMatrix(tr) {
    const zScale = tr.pixelsPerMeter;
    const ws = zScale / mercatorZfromAltitude(1, tr.center.lat);
    const posMatrix = cjsExports.mat4.identity(new Float64Array(16));
    cjsExports.mat4.translate(posMatrix, posMatrix, [
        tr.point.x,
        tr.point.y,
        0
    ]);
    cjsExports.mat4.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 = cjsExports.mat4.identity(new Float64Array(16));
    const numTiles = 1 << z;
    const xOffsetAngle = (x / numTiles - 0.5) * Math.PI * 2;
    cjsExports.mat4.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 = 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();
    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) {
        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
        ];
        cjsExports.mat3.multiply(matrix, matrix, padMatrix);
    }
    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(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 = cjsExports.mat4.identity(new Float64Array(16));
    cjsExports.mat4.multiply(matrix, tr.pixelMatrix, tr.globeMatrix);
    cjsExports.vec3.transformMat4(pos, pos, matrix);
    return new Point(pos[0], pos[1]);
}
function cameraPositionInECEF(tr) {
    const centerToPivot = latLngToECEF(tr._center.lat, tr._center.lng);
    const south = cjsExports.vec3.fromValues(0, 1, 0);
    let axis = cjsExports.vec3.cross([], south, centerToPivot);
    const rotation = cjsExports.mat4.fromRotation([], -tr.angle, centerToPivot);
    axis = cjsExports.vec3.transformMat4(axis, axis, rotation);
    cjsExports.mat4.fromRotation(rotation, -tr._pitch, axis);
    const pivotToCamera = cjsExports.vec3.normalize([], centerToPivot);
    cjsExports.vec3.scale(pivotToCamera, pivotToCamera, globeMetersToEcef(tr.cameraToCenterDistance / tr.pixelsPerMeter));
    cjsExports.vec3.transformMat4(pivotToCamera, pivotToCamera, rotation);
    return cjsExports.vec3.add([], centerToPivot, pivotToCamera);
}
function globeTiltAtLngLat(tr, lngLat) {
    const centerToPoint = latLngToECEF(lngLat.lat, lngLat.lng);
    const centerToCamera = cameraPositionInECEF(tr);
    const pointToCamera = cjsExports.vec3.subtract([], centerToCamera, centerToPoint);
    return cjsExports.vec3.angle(pointToCamera, centerToPoint);
}
function isLngLatBehindGlobe(tr, lngLat) {
    return globeTiltAtLngLat(tr, lngLat) > Math.PI / 2 * 1.01;
}
function polesInViewport(tr) {
    const ecefToScreenMatrix = cjsExports.mat4.identity(new Float64Array(16));
    cjsExports.mat4.multiply(ecefToScreenMatrix, tr.pixelMatrix, tr.globeMatrix);
    const north = [
        0,
        GLOBE_MIN,
        0
    ];
    const south = [
        0,
        GLOBE_MAX,
        0
    ];
    cjsExports.vec3.transformMat4(north, north, ecefToScreenMatrix);
    cjsExports.vec3.transformMat4(south, south, ecefToScreenMatrix);
    const northInViewport = north[0] > 0 && north[0] <= tr.width && north[1] > 0 && north[1] <= tr.height && !isLngLatBehindGlobe(tr, new LngLat(tr.center.lat, 90));
    const southInViewport = south[0] > 0 && south[0] <= tr.width && south[1] > 0 && south[1] <= tr.height && !isLngLatBehindGlobe(tr, new LngLat(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);
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 );
        const prepareVertex = (x, y, isSkirt) => {
            let adjustedX = ((() => {
                if (x === xVertices - 1) {
                    return x - 2;
                } else if (x === 0) {
                    return x;
                } else {
                    return x - 1;
                }
            })());
            const skirtOffset = 24575;
            adjustedX += isSkirt ? skirtOffset : 0;
            return [
                adjustedX,
                y
            ];
        };
        {
            for (let x = 0; x < xVertices; ++x) {
                vertices.emplaceBack(...prepareVertex(x, 0, true));
            }
        }
        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));
            }
        }
        {
            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));
                }
            }
        }
        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);
                    }
                }
            }
            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]);
            }
            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);
            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]
        ];
    }
}

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 = cjsExports.mat4.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,
        '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, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$c(),
            paint: getPaintProperties$d()
        };
        super(layer, properties, scope, lut, options);
    }
    createBucket(parameters) {
        return new CircleBucket(parameters);
    }
    queryRadius(bucket) {
        const circleBucket = bucket;
        return getMaximumPaintValue('circle-radius', this, circleBucket) + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + translateDistance(this.paint.get('circle-translate'));
    }
    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, lut) {
        const definesValues = circleDefinesValues(this);
        return {
            config: new ProgramConfiguration(this, {
                zoom,
                lut
            }),
            defines: definesValues,
            overrideFog: false
        };
    }
}
function queryIntersectsCircle(queryGeometry, geometry, transform, pixelPosMatrix, elevationHelper, alignWithMap, scaleWithMap, translation, size) {
    if (alignWithMap && queryGeometry.queryGeometry.isAboveHorizon)
        return false;
    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;
            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 = cjsExports.vec4.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) {
                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 = cjsExports.vec4.transformMat4([], [
        x,
        y,
        z,
        1
    ], pixelPosMatrix);
    return new Point(point[0] / point[3], point[1] / point[3]);
}
const origin = cjsExports.vec3.fromValues(0, 0, 0);
const up = cjsExports.vec3.fromValues(0, 0, 1);
function intersectAtHeight(r, z) {
    const intersectionPt = cjsExports.vec3.create();
    origin[2] = z;
    r.intersectsPlane(origin, up, intersectionPt);
    return new Point(intersectionPt[0], intersectionPt[1]);
}

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

let layout$c;
const getLayoutProperties$b = () => layout$c || (layout$c = new Properties({ 'visibility': new DataConstantProperty(spec['layout_heatmap']['visibility']) }));
let paint$c;
const getPaintProperties$c = () => paint$c || (paint$c = 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']),
    'heatmap-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

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, null);
    image.width = width;
    image.height = height;
    image.data = newImage.data;
}
function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels, lut, overrideRGBWithWhite) {
    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;
    const overrideRGB = channels === 4 && overrideRGBWithWhite;
    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;
        if (overrideRGB) {
            for (let i = 0; i < size.width; i++) {
                const srcByteOffset = srcOffset + i * channels + 3;
                const dstPixelOffset = dstOffset + i * channels;
                dstData[dstPixelOffset + 0] = 255;
                dstData[dstPixelOffset + 1] = 255;
                dstData[dstPixelOffset + 2] = 255;
                dstData[dstPixelOffset + 3] = srcData[srcByteOffset];
            }
        } else if (lut) {
            for (let i = 0; i < size.width; i++) {
                const srcByteOffset = srcOffset + i * channels;
                const dstPixelOffset = dstOffset + i * channels;
                const alpha = srcData[srcByteOffset + 3];
                const color = new Color(srcData[srcByteOffset + 0] / 255 * alpha, srcData[srcByteOffset + 1] / 255 * alpha, srcData[srcByteOffset + 2] / 255 * alpha, alpha);
                const shifted = color.toRenderColor(lut).toArray();
                dstData[dstPixelOffset + 0] = shifted[0];
                dstData[dstPixelOffset + 1] = shifted[1];
                dstData[dstPixelOffset + 2] = shifted[2];
                dstData[dstPixelOffset + 3] = shifted[3];
            }
        } else {
            for (let i = 0; i < size.width * channels; i++) {
                const srcByte = srcOffset + i;
                dstData[dstOffset + i] = srcData[srcByte];
            }
        }
    }
    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, null);
    }
}
class RGBAImage {
    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, lut, overrideRGBWithWhite) {
        copyImage(srcImg, dstImg, srcPt, dstPt, size, 4, lut, overrideRGBWithWhite);
    }
}
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');

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;
        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) {
                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, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$b(),
            paint: getPaintProperties$c()
        };
        super(layer, properties, scope, lut, options);
        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;
        }
    }
    queryRadius(bucket) {
        return getMaximumPaintValue('heatmap-radius', this, bucket);
    }
    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(0, 0), size);
    }
    hasOffscreenPass() {
        return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none';
    }
    getProgramIds() {
        return [
            'heatmap',
            'heatmapTexture'
        ];
    }
    getDefaultProgramParams(name, zoom, lut) {
        if (name === 'heatmap') {
            return {
                config: new ProgramConfiguration(this, {
                    zoom,
                    lut
                }),
                overrideFog: false
            };
        }
        return {};
    }
}

let layout$b;
const getLayoutProperties$a = () => layout$b || (layout$b = new Properties({ 'visibility': new DataConstantProperty(spec['layout_hillshade']['visibility']) }));
let paint$b;
const getPaintProperties$b = () => paint$b || (paint$b = 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']),
    'hillshade-shadow-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'hillshade-highlight-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'hillshade-accent-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

class HillshadeStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$a(),
            paint: getPaintProperties$b()
        };
        super(layer, properties, scope, lut, options);
    }
    shouldRedrape() {
        return this.hasOffscreenPass() && this.paint.get('hillshade-illumination-anchor') === 'viewport';
    }
    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, lut) {
        return { overrideFog: false };
    }
}

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

function earcut(data, holeIndices, dim = 2) {
    const hasHoles = holeIndices && holeIndices.length;
    const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
    let outerNode = linkedList(data, 0, outerLen, dim, true);
    const triangles = [];
    if (!outerNode || outerNode.next === outerNode.prev)
        return triangles;
    let minX, minY, 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 = Infinity;
        minY = Infinity;
        let maxX = -Infinity;
        let maxY = -Infinity;
        for (let i = dim; i < outerLen; i += dim) {
            const x = data[i];
            const 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) {
    let last;
    if (clockwise === signedArea(data, start, end, dim) > 0) {
        for (let i = start; i < end; i += dim)
            last = insertNode(i / dim | 0, data[i], data[i + 1], last);
    } else {
        for (let i = end - dim; i >= start; i -= dim)
            last = insertNode(i / dim | 0, 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;
    let 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);
    let stop = ear;
    // iterate through ears, slicing them one by one
    while (ear.prev !== ear.next) {
        const prev = ear.prev;
        const next = ear.next;
        if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
            triangles.push(prev.i, ear.i, next.i);
            // cut off the triangle
            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);
                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) {
    const 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
    const 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
    const 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;
    let 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) {
    const a = ear.prev, b = ear, c = ear.next;
    if (area(a, b, c) >= 0)
        return false;
    // reflex, can't be an ear
    const 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
    const 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;
    const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize);
    let 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) {
    let p = start;
    do {
        const 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, p.i, b.i);
            // 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
    let a = start;
    do {
        let b = a.next.next;
        while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
                // split the polygon in two by the diagonal
                let 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) {
    const queue = [];
    for (let i = 0, len = holeIndices.length; i < len; i++) {
        const start = holeIndices[i] * dim;
        const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        const 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 (let 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) {
    const bridge = findHoleBridge(hole, outerNode);
    if (!bridge) {
        return outerNode;
    }
    const 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) {
    let p = outerNode;
    const hx = hole.x;
    const hy = hole.y;
    let qx = -Infinity;
    let 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) {
            const 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
    const stop = m;
    const mx = m.x;
    const my = m.y;
    let tanMin = Infinity;
    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)) {
            const 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) {
    let 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) {
    let numMerges;
    let inSize = 1;
    do {
        let p = list;
        let e;
        list = null;
        let tail = null;
        numMerges = 0;
        while (p) {
            numMerges++;
            let q = p;
            let pSize = 0;
            for (let i = 0; i < inSize; i++) {
                pSize++;
                q = q.nextZ;
                if (!q)
                    break;
            }
            let 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) {
    let 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) {
    const o1 = sign(area(p1, q1, p2));
    const o2 = sign(area(p1, q1, q2));
    const o3 = sign(area(p2, q2, p1));
    const 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) {
    let 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) {
    let p = a;
    let inside = false;
    const px = (a.x + b.x) / 2;
    const 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) {
    const a2 = createNode(a.i, a.x, a.y), b2 = createNode(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) {
    const p = createNode(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 createNode(i, x, y) {
    return {
        i,
        // vertex index in coordinates array
        x,
        y,
        // vertex coordinates
        prev: null,
        // previous and next vertex nodes in a polygon ring
        next: null,
        z: 0,
        // z-order curve value
        prevZ: null,
        // previous and next nodes in z-order
        nextZ: null,
        steiner: false    // indicates whether this is a steiner point
    };
}
function signedArea(data, start, end, dim) {
    let sum = 0;
    for (let i = start, j = end - dim; i < end; i += dim) {
        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
        j = i;
    }
    return sum;
}

function classifyRings(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 === void 0)
            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);
    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 addPattern(pattern, patterns, pixelRatio = 1) {
    if (!pattern) {
        return null;
    }
    const patternId = typeof pattern === 'string' ? pattern : pattern.getPrimary().id;
    if (!patterns[patternId]) {
        patterns[patternId] = [];
    }
    const patternPrimary = ResolvedImage.from(patternId).getPrimary().scaleSelf(pixelRatio);
    patterns[patternId].push(patternPrimary);
    return patternPrimary.serialize();
}
function hasPattern(type, layers, pixelRatio, options) {
    const patterns = options.patternDependencies;
    let hasPattern2 = false;
    for (const layer of layers) {
        const patternProperty = layer.paint.get(`${ type }-pattern`);
        if (!patternProperty.isConstant()) {
            hasPattern2 = true;
        }
        const constantPattern = patternProperty.constantOr(null);
        if (addPattern(constantPattern, patterns, pixelRatio)) {
            hasPattern2 = true;
        }
    }
    return hasPattern2;
}
function addPatternDependencies(type, layers, patternFeature, zoom, pixelRatio, 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;
            const patternSerialized = addPattern(pattern, patterns, pixelRatio);
            if (patternSerialized) {
                patternFeature.patterns[layer.id] = patternSerialized;
            }
        }
    }
    return patternFeature;
}

const EARCUT_MAX_RINGS$1 = 500;
class FillBucket {
    constructor(options) {
        this.zoom = options.zoom;
        this.pixelRatio = options.pixelRatio;
        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, {
            zoom: options.zoom,
            lut: options.lut
        });
        this.segments = new SegmentVector();
        this.segments2 = new SegmentVector();
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.projection = options.projection;
    }
    updateFootprints(_id, _footprints) {
    }
    populate(features, options, canonical, tileTransform) {
        this.hasPattern = hasPattern('fill', this.layers, this.pixelRatio, 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);
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const sortKey = fillSortKey ? fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : void 0;
            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) => {
                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, this.pixelRatio, options);
                this.patternFeatures.push(patternFeature);
            } else {
                this.addFeature(bucketFeature, geometry, index, canonical, {}, options.availableImages, options.brightness, options.elevationFeatures);
            }
            const feature = features[index].feature;
            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);
        }
    }
    update(states, vtLayer, availableImages, imagePositions, layers, isBrightnessChanged, brightness) {
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, brightness);
    }
    addFeatures(options, canonical, imagePositions, availableImages, _, brightness) {
        for (const feature of this.patternFeatures) {
            this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions, availableImages, brightness, options.elevationFeatures);
        }
    }
    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, elevationFeatures) {
        for (const polygon of classifyRings(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(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'
    ]
});

let layout$9;
const getLayoutProperties$9 = () => layout$9 || (layout$9 = new Properties({
    'fill-sort-key': new DataDrivenProperty(spec['layout_fill']['fill-sort-key']),
    'visibility': new DataConstantProperty(spec['layout_fill']['visibility']),
    'fill-elevation-reference': new DataConstantProperty(spec['layout_fill']['fill-elevation-reference'])
}));
let paint$a;
const getPaintProperties$a = () => paint$a || (paint$a = 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']),
    'fill-z-offset': new DataDrivenProperty(spec['paint_fill']['fill-z-offset']),
    'fill-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'fill-outline-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

class FillStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$9(),
            paint: getPaintProperties$a()
        };
        super(layer, properties, scope, lut, 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, lut) {
        return {
            config: new ProgramConfiguration(this, {
                zoom,
                lut
            }),
            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 === void 0) {
            this.paint._values['fill-outline-color'] = this.paint._values['fill-color'];
        }
    }
    createBucket(parameters) {
        return new FillBucket(parameters);
    }
    queryRadius() {
        return translateDistance(this.paint.get('fill-translate'));
    }
    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;
    }
    is3D() {
        return this.paint.get('fill-z-offset').constantOr(1) !== 0;
    }
}

class TriangleGridIndex {
    constructor(vertices, indices, cellCount, maxCellSize) {
        this.triangleCount = indices.length / 3;
        this.min = new Point(0, 0);
        this.max = new Point(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) {
            return;
        }
        const [min, max] = [
            vertices[0].clone(),
            vertices[0].clone()
        ];
        for (let i = 1; i < vertices.length; ++i) {
            const v = 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);
        }
        if (maxCellSize) {
            const optimalCellCount = Math.ceil(Math.max(max.x - min.x, max.y - min.y) / maxCellSize);
            cellCount = Math.max(cellCount, optimalCellCount);
        }
        if (cellCount === 0) {
            return;
        }
        this.min = min;
        this.max = max;
        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 (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);
            const c00 = new Point(0, 0);
            const c10 = new Point(0, 0);
            const c01 = new Point(0, 0);
            const c11 = new Point(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;
        }
        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
            };
            while (idx < associatedTriangles.length && associatedTriangles[idx].cellIdx === cellIdx) {
                ++cell.len;
                this.payload.push(associatedTriangles[idx++].triIdx);
            }
            this.cells[cellIdx] = cell;
        }
    }
    _lazyInitLookup() {
        if (!this.lookup) {
            this.lookup = new Uint8Array(Math.ceil(this.triangleCount / 8));
        }
        this.lookup.fill(0);
    }
    queryPoint(p, out) {
        if (this.triangleCount === 0 || this.cells.length === 0) {
            return;
        }
        if (p.x > this.max.x || this.min.x > p.x || p.y > this.max.y || this.min.y > p.y) {
            return;
        }
        const x = toCellIdx(p.x - this.min.x, this.xScale, this.cellsX);
        const y = toCellIdx(p.y - this.min.y, this.yScale, this.cellsY);
        const cell = this.cells[y * this.cellsX + x];
        if (!cell) {
            return;
        }
        this._lazyInitLookup();
        for (let i = 0; i < cell.len; i++) {
            const triIdx = this.payload[cell.start + i];
            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) {
                return;
            }
        }
    }
    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;
        }
        this._lazyInitLookup();
        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];
                    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) {
                        return;
                    }
                }
            }
        }
    }
}
function toCellIdx(p, scale, cells) {
    return Math.max(0, Math.min(cells - 1, Math.floor(p * scale)));
}
register(TriangleGridIndex, 'TriangleGridIndex');

class ClipBucket {
    constructor(options) {
        this.zoom = options.zoom;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.hasPattern = false;
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.footprints = [];
    }
    updateFootprints(id, footprints) {
        for (const footprint of this.footprints) {
            footprints.push({
                footprint,
                id
            });
        }
    }
    populate(features, options, canonical, tileTransform) {
        const bucketFeatures = [];
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const bucketFeature = {
                id,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),
                patterns: {}
            };
            bucketFeatures.push(bucketFeature);
        }
        for (const bucketFeature of bucketFeatures) {
            const {geometry, index, sourceLayerIndex} = bucketFeature;
            this.addFeature(bucketFeature, geometry, index, canonical, {}, options.availableImages, options.brightness);
            const feature = features[index].feature;
            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);
        }
    }
    isEmpty() {
        return this.footprints.length === 0;
    }
    uploadPending() {
        return false;
    }
    upload(_context) {
    }
    update(_states, _vtLayer, _availableImages, _imagePositions, layers, isBrightnessChanged, brightness) {
    }
    destroy() {
    }
    addFeature(feature, geometry, index, canonical, imagePositions, _availableImages = [], _brightness) {
        for (const polygon of classifyRings(geometry, 2)) {
            const points = [];
            const flattened = [];
            const holeIndices = [];
            const min = new Point(Infinity, Infinity);
            const max = new Point(-Infinity, -Infinity);
            for (const ring of polygon) {
                if (ring.length === 0) {
                    continue;
                }
                if (ring !== polygon[0]) {
                    holeIndices.push(flattened.length / 2);
                }
                for (let i = 0; i < ring.length; i++) {
                    flattened.push(ring[i].x);
                    flattened.push(ring[i].y);
                    points.push(ring[i]);
                    min.x = Math.min(min.x, ring[i].x);
                    min.y = Math.min(min.y, ring[i].y);
                    max.x = Math.max(max.x, ring[i].x);
                    max.y = Math.max(max.y, ring[i].y);
                }
            }
            const indices = earcut(flattened, holeIndices);
            const grid = new TriangleGridIndex(points, indices, 8, 256);
            this.footprints.push({
                vertices: points,
                indices,
                grid,
                min,
                max
            });
        }
    }
}
register(ClipBucket, 'ClipBucket', { omit: ['layers'] });

let layout$8;
const getLayoutProperties$8 = () => layout$8 || (layout$8 = new Properties({
    'clip-layer-types': new DataConstantProperty(spec['layout_clip']['clip-layer-types']),
    'clip-layer-scope': new DataConstantProperty(spec['layout_clip']['clip-layer-scope'])
}));
let paint$9;
const getPaintProperties$9 = () => paint$9 || (paint$9 = new Properties({}));

class ClipStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$8(),
            paint: getPaintProperties$9()
        };
        super(layer, properties, scope, lut, options);
    }
    recalculate(parameters, availableImages) {
        super.recalculate(parameters, availableImages);
    }
    createBucket(parameters) {
        return new ClipBucket(parameters);
    }
    isTileClipped() {
        return true;
    }
    is3D() {
        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 wallAttributes = createLayout([{
        name: 'a_join_normal_inside',
        components: 3,
        type: 'Int16'
    }]);
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 vectortilefeature;
var hasRequiredVectortilefeature;

function requireVectortilefeature () {
	if (hasRequiredVectortilefeature) return vectortilefeature;
	hasRequiredVectortilefeature = 1;
	var Point = requirePointGeometry();
	vectortilefeature = VectorTileFeature;
	function VectorTileFeature(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.types = [
	    'Unknown',
	    'Point',
	    'LineString',
	    'Polygon'
	];
	VectorTileFeature.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.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.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.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;
	}
	return vectortilefeature;
}

var vectortilelayer;
var hasRequiredVectortilelayer;

function requireVectortilelayer () {
	if (hasRequiredVectortilelayer) return vectortilelayer;
	hasRequiredVectortilelayer = 1;
	var VectorTileFeature = requireVectortilefeature();
	vectortilelayer = VectorTileLayer;
	function VectorTileLayer(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.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(this._pbf, end, this.extent, this._keys, this._values);
	};
	return vectortilelayer;
}

var vectortile;
var hasRequiredVectortile;

function requireVectortile () {
	if (hasRequiredVectortile) return vectortile;
	hasRequiredVectortile = 1;
	var VectorTileLayer = requireVectortilelayer();
	vectortile = VectorTile;
	function VectorTile(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;
	    }
	}
	return vectortile;
}

var hasRequiredVectorTile;

function requireVectorTile () {
	if (hasRequiredVectorTile) return vectorTile;
	hasRequiredVectorTile = 1;
	vectorTile.VectorTile = requireVectortile();
	vectorTile.VectorTileFeature = requireVectortilefeature();
	vectorTile.VectorTileLayer = requireVectortilelayer();
	return vectorTile;
}

var vectorTileExports = requireVectorTile();

class Point3D extends Point {
    constructor(x, y, z) {
        super(x, y);
        this.z = z;
    }
}
class Point4D extends Point3D {
    // used for line progress and interpolated on clipping
    constructor(x, y, z, w) {
        super(x, y, z);
        this.w = w;
    }
}
function clipPolygon(polygons, clipAxis1, clipAxis2, axis) {
    const intersectX = (ring, ax, ay, bx, by, x) => {
        ring.push(new Point(x, ay + (by - ay) * ((x - ax) / (bx - ax))));
    };
    const intersectY = (ring, ax, ay, bx, by, y) => {
        ring.push(new Point(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 a2 = axis === 0 ? ax : ay;
                const b = axis === 0 ? bx : by;
                if (a2 < clipAxis1) {
                    if (b > clipAxis1) {
                        intersect(clipped, ax, ay, bx, by, clipAxis1);
                    }
                } else if (a2 > clipAxis2) {
                    if (b < clipAxis2) {
                        intersect(clipped, ax, ay, bx, by, clipAxis2);
                    }
                } else {
                    clipped.push(ring[i]);
                }
                if (b < clipAxis1 && a2 >= clipAxis1) {
                    intersect(clipped, ax, ay, bx, by, clipAxis1);
                }
                if (b > clipAxis2 && a2 <= 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, bounds2) => {
        for (const polygon of clipped) {
            outPolygons.push({
                polygon,
                bounds: bounds2
            });
        }
    };
    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);
        splits.push(1);
    }
    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(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(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;
}
function clipFirst(a, b, axis, clip) {
    const axis1 = axis === 'x' ? 'y' : 'x';
    const ratio = (clip - a[axis]) / (b[axis] - a[axis]);
    a[axis1] = a[axis1] + (b[axis1] - a[axis1]) * ratio;
    a[axis] = clip;
    if (a.hasOwnProperty('z')) {
        a['z'] = number(a['z'], b['z'], ratio);
    }
    if (a.hasOwnProperty('w')) {
        a['w'] = number(a['w'], b['w'], ratio);
    }
}
function clipLine$1(p0, p1, boundsMin, boundsMax) {
    const clipAxis1 = boundsMin;
    const clipAxis2 = boundsMax;
    for (const axis of [
            'x',
            'y'
        ]) {
        let a = p0;
        let b = p1;
        if (a[axis] >= b[axis]) {
            a = p1;
            b = p0;
        }
        if (a[axis] < clipAxis1 && b[axis] > clipAxis1) {
            clipFirst(a, b, axis, clipAxis1);
        }
        if (a[axis] < clipAxis2 && b[axis] > clipAxis2) {
            clipFirst(b, a, axis, clipAxis2);
        }
    }
}

const ReplacementOrderLandmark = Number.MAX_SAFE_INTEGER;
function scopeSkipsClipping(scope, scopes) {
    return scopes.length !== 0 && scopes.find(el => {
        return el === scope;
    }) === void 0;
}
function skipClipping(region, layerIndex, mask, scope) {
    return region.order < layerIndex || region.order === ReplacementOrderLandmark || !(region.clipMask & mask) || scopeSkipsClipping(scope, region.clipScope);
}
class ReplacementSource {
    constructor() {
        this._updateTime = 0;
        this._sourceIds = [];
        this._activeRegions = [];
        this._prevRegions = [];
        this._globalClipBounds = {
            min: new Point(Infinity, Infinity),
            max: new Point(-Infinity, -Infinity)
        };
    }
    clear() {
        if (this._activeRegions.length > 0) {
            ++this._updateTime;
        }
        this._activeRegions = [];
        this._prevRegions = [];
    }
    get updateTime() {
        return this._updateTime;
    }
    getReplacementRegionsForTile(id, checkAgainstGlobalClipBounds = false) {
        const tileBounds = transformAabbToMerc(new Point(0, 0), new Point(EXTENT, EXTENT), id);
        const result = [];
        if (checkAgainstGlobalClipBounds) {
            if (!regionsOverlap(tileBounds, this._globalClipBounds))
                return 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,
                order: region.order,
                clipMask: region.clipMask,
                clipScope: region.clipScope
            });
        }
        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) {
                            bucket.updateFootprints(id.toUnwrapped(), footprints);
                        }
                    }
                    return footprints;
                },
                getOrder: () => {
                    return source.order;
                },
                getClipMask: () => {
                    return source.clipMask;
                },
                getClipScope: () => {
                    return source.clipScope;
                }
            };
        }));
    }
    _addSource(source) {
        const footprints = source.getFootprints();
        if (footprints.length === 0) {
            return;
        }
        const order = source.getOrder();
        const clipMask = source.getClipMask();
        const clipScope = source.getClipScope();
        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,
                order,
                clipMask,
                clipScope
            });
        }
        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) || a.order - b.order || a.clipMask - b.clipMask || compareClipScopes(a.clipScope, b.clipScope);
        });
        let regionsChanged = this._activeRegions.length !== this._prevRegions.length;
        if (!regionsChanged) {
            let idx = 0;
            while (!regionsChanged && idx !== this._activeRegions.length) {
                const curr = this._activeRegions[idx];
                const prev = this._prevRegions[idx];
                regionsChanged = curr.priority !== prev.priority || !boundsEquals(curr, prev) || curr.order !== prev.order || (curr.clipMask !== prev.clipMask || !deepEqual(curr.clipScope, prev.clipScope));
                ++idx;
            }
        }
        if (regionsChanged) {
            ++this._updateTime;
            for (const region of this._activeRegions) {
                if (region.order !== ReplacementOrderLandmark) {
                    this._globalClipBounds.min.x = Math.min(this._globalClipBounds.min.x, region.min.x);
                    this._globalClipBounds.min.y = Math.min(this._globalClipBounds.min.y, region.min.y);
                    this._globalClipBounds.max.x = Math.max(this._globalClipBounds.max.x, region.max.x);
                    this._globalClipBounds.max.y = Math.max(this._globalClipBounds.max.y, region.max.y);
                }
            }
            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) {
                let rangeBegin = 0;
                let rangeEnd = firstRegionOfNextPriority(rangeBegin);
                while (rangeBegin !== rangeEnd) {
                    let idx = rangeBegin;
                    const prevRangeEnd = rangeBegin;
                    while (idx !== rangeEnd) {
                        const active = this._activeRegions[idx];
                        active.hiddenByOverlap = false;
                        for (let prevIdx = 0; prevIdx < prevRangeEnd; prevIdx++) {
                            const prev = this._activeRegions[prevIdx];
                            if (prev.hiddenByOverlap) {
                                continue;
                            }
                            if (active.order !== ReplacementOrderLandmark) {
                                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) {
        [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 compareClipScopes(a, b) {
    const concat = (t, n) => {
        return t + n;
    };
    return a.length - b.length || a.reduce(concat, '').localeCompare(b.reduce(concat, ''));
}
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]) || a[i].order !== b[i].order || a[i].clipMask !== b[i].clipMask || !deepEqual(a[i].clipScope, b[i].clipScope)) {
            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(minx, miny),
        max: new Point(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(minx, miny),
        max: new Point(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(mnx, mny), new Point(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;
    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(x, y);
        });
    }
    return footprintTrianglesIntersect(b, queryVertices, a.indices, 0, a.indices.length, 0, 0);
}
function transformPointToTile(x, y, src, dst) {
    const zDiff = Math.pow(2, dst.z - src.z);
    const xf = (x + src.x * EXTENT) * zDiff - dst.x * EXTENT;
    const yf = (y + src.y * EXTENT) * zDiff - dst.y * EXTENT;
    return new Point(xf, yf);
}
function pointInFootprint(p, footprint) {
    const candidateTriangles = [];
    footprint.grid.queryPoint(p, candidateTriangles);
    const fpIndices = footprint.indices;
    const fpVertices = footprint.vertices;
    for (let j = 0; j < candidateTriangles.length; j++) {
        const triIdx = candidateTriangles[j];
        const triangle = [
            fpVertices[fpIndices[triIdx * 3 + 0]],
            fpVertices[fpIndices[triIdx * 3 + 1]],
            fpVertices[fpIndices[triIdx * 3 + 2]]
        ];
        if (polygonContainsPoint(triangle, p)) {
            return true;
        }
    }
    return false;
}

function isClockWise(vertices) {
    let signedArea = 0;
    const n = vertices.length;
    for (let i = 0; i < n; i++) {
        const x1 = vertices[i].x;
        const y1 = vertices[i].y;
        const x2 = vertices[(i + 1) % n].x;
        const y2 = vertices[(i + 1) % n].y;
        signedArea += (x2 - x1) * (y2 + y1);
    }
    return signedArea >= 0;
}
function createLineWallGeometry(vertices) {
    const isPolygon = vertices[0].x === vertices[vertices.length - 1].x && vertices[0].y === vertices[vertices.length - 1].y;
    const isCW = isClockWise(vertices);
    if (!isCW) {
        vertices = vertices.reverse();
    }
    const wallGeometry = {
        geometry: [],
        joinNormals: [],
        indices: []
    };
    const innerWall = [];
    const outerWall = [];
    const joinNormals = [];
    let len = vertices.length;
    while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {
        len--;
    }
    if (len < (isPolygon ? 3 : 2))
        return wallGeometry;
    let first = 0;
    while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {
        first++;
    }
    let currentVertex;
    let prevVertex = void 0;
    let nextVertex = void 0;
    let prevNormal = void 0;
    let nextNormal = void 0;
    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] : void 0 : // if it's a polygon, treat the last vertex like the first
        vertices[i + 1];
        if (nextVertex && vertices[i].equals(nextVertex))
            continue;
        if (nextNormal)
            prevNormal = nextNormal;
        if (currentVertex)
            prevVertex = currentVertex;
        currentVertex = vertices[i];
        nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;
        prevNormal = prevNormal || nextNormal;
        let joinNormal = prevNormal.add(nextNormal);
        if (joinNormal.x !== 0 || joinNormal.y !== 0) {
            joinNormal._unit();
        }
        const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
        const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;
        const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;
        let currentJoin = 'miter';
        const miterLimit = 2;
        if (currentJoin === 'miter' && miterLength > miterLimit) {
            currentJoin = 'bevel';
        }
        if (currentJoin === 'bevel') {
            if (miterLength > 100)
                currentJoin = 'flipbevel';
            if (miterLength < miterLimit)
                currentJoin = 'miter';
        }
        const addWallJoin = (vert, normal, outerOffset, innerOffset) => {
            const innerPoint = new Point(vert.x, vert.y);
            const outerPoint = new Point(vert.x, vert.y);
            innerPoint.x += normal.x * innerOffset;
            innerPoint.y += normal.y * innerOffset;
            outerPoint.x -= normal.x * Math.max(outerOffset, 1);
            outerPoint.y -= normal.y * Math.max(outerOffset, 1);
            joinNormals.push(normal);
            innerWall.push(innerPoint);
            outerWall.push(outerPoint);
        };
        if (currentJoin === 'miter') {
            joinNormal._mult(miterLength);
            addWallJoin(currentVertex, joinNormal, 0, 0);
        } else if (currentJoin === 'flipbevel') {
            joinNormal = nextNormal.mult(-1);
            addWallJoin(currentVertex, joinNormal, 0, 0);
            addWallJoin(currentVertex, joinNormal.mult(-1), 0, 0);
        } else {
            const offset = -Math.sqrt(miterLength * miterLength - 1);
            const offsetA = lineTurnsLeft ? offset : 0;
            const offsetB = lineTurnsLeft ? 0 : offset;
            if (prevVertex) {
                addWallJoin(currentVertex, prevNormal, offsetA, offsetB);
            }
            if (nextVertex) {
                addWallJoin(currentVertex, nextNormal, offsetA, offsetB);
            }
        }
    }
    wallGeometry.geometry = [
        ...innerWall,
        ...outerWall.reverse(),
        innerWall[0]
    ];
    wallGeometry.joinNormals = [
        ...joinNormals,
        ...joinNormals.reverse(),
        joinNormals[joinNormals.length - 1]
    ];
    const numPoints = wallGeometry.geometry.length - 1;
    for (let i = 0; i < numPoints / 2; i++) {
        if (i + 1 < numPoints / 2) {
            let indexA = i;
            let indexB = i + 1;
            let indexC = numPoints - 1 - i;
            let indexD = numPoints - 2 - i;
            indexA = indexA === 0 ? numPoints - 1 : indexA - 1;
            indexB = indexB === 0 ? numPoints - 1 : indexB - 1;
            indexC = indexC === 0 ? numPoints - 1 : indexC - 1;
            indexD = indexD === 0 ? numPoints - 1 : indexD - 1;
            wallGeometry.indices.push(indexC);
            wallGeometry.indices.push(indexB);
            wallGeometry.indices.push(indexA);
            wallGeometry.indices.push(indexC);
            wallGeometry.indices.push(indexD);
            wallGeometry.indices.push(indexB);
        }
    }
    return wallGeometry;
}
const tileCorners = [
    new Point(0, 0),
    new Point(EXTENT, 0),
    new Point(EXTENT, EXTENT),
    new Point(0, EXTENT)
];
function dropBufferConnectionLines(polygon, isPolygon) {
    const lineSegments = [];
    let lineSegment = [];
    if (!isPolygon || polygon.length < 2) {
        return [polygon];
    } else if (polygon.length === 2) {
        if (edgeIntersectsBox(polygon[0], polygon[1], tileCorners)) {
            return [polygon];
        }
        return [];
    } else {
        for (let i = 0; i < polygon.length + 2; i++) {
            const p0 = i === 0 ? polygon[polygon.length - 1] : polygon[(i - 1) % polygon.length];
            const p1 = polygon[i % polygon.length];
            const p2 = polygon[(i + 1) % polygon.length];
            const intersectsPrev = edgeIntersectsBox(p0, p1, tileCorners);
            const intersectsNext = edgeIntersectsBox(p1, p2, tileCorners);
            const addPoint = intersectsPrev || intersectsNext;
            if (addPoint) {
                lineSegment.push(p1);
            }
            if (!addPoint || !intersectsNext) {
                if (lineSegment.length > 0) {
                    if (lineSegment.length > 1) {
                        lineSegments.push(lineSegment);
                    }
                    lineSegment = [];
                }
            }
        }
    }
    if (lineSegment.length > 1) {
        lineSegments.push(lineSegment);
    }
    return lineSegments;
}

const vectorTileFeatureTypes$2 = vectorTileExports.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',
    'fill-extrusion-line-width',
    'fill-extrusion-emissive-strength'
];
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;
const TILE_REGIONS = 4;
const HIDDEN_CENTROID = new Point(0, 1);
const HIDDEN_BY_REPLACEMENT = 2147483648;
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 addWallVertex(vertexArray, joinNormal, inside) {
    vertexArray.emplaceBack(// a_join_normal_inside:
    joinNormal.x * EXTENT, joinNormal.y * EXTENT, inside ? 1 : 0);
}
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;
    }
}
class PartData {
    constructor() {
        this.centroidXY = new Point(0, 0);
        this.vertexArrayOffset = 0;
        this.vertexCount = 0;
        this.groundVertexArrayOffset = 0;
        this.groundVertexCount = 0;
        this.flags = 0;
        this.footprintSegIdx = -1;
        this.footprintSegLen = 0;
        this.polygonSegIdx = -1;
        this.polygonSegLen = 0;
        this.min = new Point(Number.MAX_VALUE, Number.MAX_VALUE);
        this.max = new Point(-Number.MAX_VALUE, -Number.MAX_VALUE);
        this.height = 0;
    }
    span() {
        return new Point(this.max.x - this.min.x, this.max.y - this.min.y);
    }
}
class BorderCentroidData {
    constructor() {
        this.acc = new Point(0, 0);
        this.accCount = 0;
        this.centroidDataIndex = 0;
    }
    startRing(data, p) {
        if (data.min.x === Number.MAX_VALUE) {
            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)) {
            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;
            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(0, 0);
        }
        return new Point(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
];
function getTileRegions(pa, pb, na, maxRadius) {
    const regions = [4];
    if (maxRadius === 0)
        return regions;
    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, {
            zoom: options.zoom,
            lut: options.lut
        }, 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$1(pa, bounds) && pointOutsideBounds$1(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;
                const regions = getTileRegions(pa, pb, na, maxRadius);
                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();
        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;
            });
        }
        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);
            let regionTriCountOffset = 0;
            for (let k = 0; k <= TILE_REGIONS; k++) {
                const triCount = regionTriCounts[k];
                if (triCount !== 0) {
                    let segmentVector = this.regionSegments[k];
                    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);
            }
        }
        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, isBrightnessChanged, brightness) {
        if (!this.hasData())
            return;
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, 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) {
            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 {
    constructor(options) {
        this.zoom = options.zoom;
        this.canonical = options.canonical;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.pixelRatio = options.pixelRatio;
        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.wallVertexArray = new FillExtrusionWallArray();
        this.indexArray = new StructArrayLayout3ui6();
        const filtered = property => {
            return fillExtrusionDefaultDataDrivenProperties.includes(property);
        };
        this.programConfigurations = new ProgramConfigurationSet(options.layers, {
            zoom: options.zoom,
            lut: options.lut
        }, 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 = {};
        this.triangleSubSegments = [];
        this.polygonSegments = [];
    }
    updateFootprints(_id, _footprints) {
    }
    populate(features, options, canonical, tileTransform) {
        this.features = [];
        this.hasPattern = hasPattern('fill-extrusion', this.layers, this.pixelRatio, options);
        this.featuresOnBorder = [];
        this.borderFeatureIndices = [
            [],
            [],
            [],
            []
        ];
        this.borderDoneWithNeighborZ = [
            -1,
            -1,
            -1,
            -1
        ];
        this.selfDEMTileTimestamp = Number.MAX_VALUE;
        this.borderDEMTileTimestamp = [
            Number.MAX_VALUE,
            Number.MAX_VALUE,
            Number.MAX_VALUE,
            Number.MAX_VALUE
        ];
        this.tileToMeter = tileToMeter(canonical);
        this.edgeRadius = this.layers[0].layout.get('fill-extrusion-edge-radius') / this.tileToMeter;
        this.wallMode = this.layers[0].paint.get('fill-extrusion-line-width').constantOr(1) !== 0;
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            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;
            const featureIsPolygon = vectorTileFeatureTypes$2[bucketFeature.type] === 'Polygon';
            if (this.hasPattern) {
                this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, this.pixelRatio, options));
            } else {
                if (this.wallMode) {
                    for (const polygon of bucketFeature.geometry) {
                        for (const line of dropBufferConnectionLines(polygon, featureIsPolygon)) {
                            this.addFeature(bucketFeature, [line], index, canonical, {}, options.availableImages, tileTransform, options.brightness);
                        }
                    }
                } 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();
        if (this.projection.name === 'mercator') {
            this.splitToSubtiles();
        }
        this.groundEffect.prepareBorderSegments();
        this.polygonSegments.length = 0;
    }
    addFeatures(options, canonical, imagePositions, availableImages, tileTransform, brightness) {
        for (const feature of this.features) {
            const featureIsPolygon = vectorTileFeatureTypes$2[feature.type] === 'Polygon';
            const {geometry} = feature;
            if (this.wallMode) {
                for (const polygon of geometry) {
                    for (const line of dropBufferConnectionLines(polygon, featureIsPolygon)) {
                        this.addFeature(feature, [line], feature.index, canonical, imagePositions, availableImages, tileTransform, brightness);
                    }
                }
            } else {
                this.addFeature(feature, geometry, feature.index, canonical, imagePositions, availableImages, tileTransform, brightness);
            }
        }
        this.sortBorders();
        if (this.projection.name === 'mercator') {
            this.splitToSubtiles();
        }
    }
    update(states, vtLayer, availableImages, imagePositions, layers, isBrightnessChanged, brightness) {
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, brightness);
        this.groundEffect.update(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, 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);
            this.wallVertexBuffer = context.createVertexBuffer(this.wallVertexArray, wallAttributes.members);
            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) {
            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(0, 0),
            new Point(EXTENT, EXTENT)
        ];
        const projection = tileTransform.projection;
        const isGlobe = projection.name === 'globe';
        const isPolygon = this.wallMode || vectorTileFeatureTypes$2[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();
        }
        let wallGeometry;
        if (this.wallMode) {
            if (isGlobe) {
                warnOnce('Non zero fill-extrusion-line-width is not yet supported on globe.');
                return;
            }
            if (geometry.length !== 1) {
                return;
            }
            wallGeometry = createLineWallGeometry(geometry[0]);
            geometry = [wallGeometry.geometry];
        }
        const isPointOnInnerWall = (index2, polygon) => {
            return index2 < (polygon.length - 1) / 2 || index2 === polygon.length - 1;
        };
        const polygons = this.wallMode ? [geometry] : classifyRings(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) {
            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) {
            let topIndex = 0;
            let numVertices = 0;
            for (const ring of polygon) {
                if (isPolygon && !ring[0].equals(ring[ring.length - 1]))
                    ring.push(ring[0]);
                numVertices += isPolygon ? ring.length - 1 : ring.length;
            }
            const segment = this.segments.prepareSegment((isPolygon ? 5 : 4) * numVertices, this.layoutVertexArray, this.indexArray);
            if (centroid.footprintSegIdx < 0) {
                centroid.footprintSegIdx = this.footprintSegments.length;
            }
            if (centroid.polygonSegIdx < 0) {
                centroid.polygonSegIdx = this.polygonSegments.length;
            }
            const polygonSeg = {
                triangleArrayOffset: this.indexArray.length,
                triangleCount: 0,
                triangleSegIdx: this.segments.segments.length - 1
            };
            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;
                for (let r = 0; r < polygon.length; r++) {
                    const ring = polygon[r];
                    if (ring.length && r !== 0) {
                        holeIndices.push(flattened.length / 2);
                    }
                    const groundPolyline = [];
                    let na, nb;
                    {
                        const p0 = ring[0];
                        const p1 = ring[1];
                        na = p1.sub(p0)._perp()._unit();
                    }
                    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);
                        if (this.wallMode) {
                            const isInside = isPointOnInnerWall(i, ring);
                            const joinNormal = wallGeometry.joinNormals[i];
                            addWallVertex(this.wallVertexArray, joinNormal, !isInside);
                        }
                        segment.vertexLength++;
                        this.footprintVertices.emplaceBack(p1.x, p1.y);
                        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 = this.wallMode ? wallGeometry.indices : earcut(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]);
                    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;
                const groundPolyline = [];
                let kFirst;
                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();
                    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;
                    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);
                    if (this.wallMode) {
                        const isInside = isPointOnInnerWall(i - 1, ring);
                        const joinNormal = wallGeometry.joinNormals[i - 1];
                        addWallVertex(this.wallVertexArray, joinNormal, isInside);
                        addWallVertex(this.wallVertexArray, joinNormal, isInside);
                    }
                    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);
                    if (this.wallMode) {
                        const isInside = isPointOnInnerWall(i, ring);
                        const joinNormal = wallGeometry.joinNormals[i];
                        addWallVertex(this.wallVertexArray, joinNormal, isInside);
                        addWallVertex(this.wallVertexArray, joinNormal, isInside);
                    }
                    segment.vertexLength += 4;
                    this.indexArray.emplaceBack(k + 0, k + 1, k + 2);
                    this.indexArray.emplaceBack(k + 1, k + 3, k + 2);
                    segment.primitiveLength += 2;
                    if (edgeRadius) {
                        const t0 = topIndex + (i === 1 ? ring.length - 2 : i - 2);
                        const t1 = i === 1 ? topIndex : t0 + 1;
                        this.indexArray.emplaceBack(k + 1, t0, k + 3);
                        this.indexArray.emplaceBack(t0, t1, k + 3);
                        segment.primitiveLength += 2;
                        if (kFirst === void 0) {
                            kFirst = k;
                        }
                        if (!isEdgeOutsideBounds(p2, ring[i], bounds)) {
                            const l = i === ring.length - 1 ? kFirst : segment.vertexLength;
                            this.indexArray.emplaceBack(k + 2, k + 3, l);
                            this.indexArray.emplaceBack(k + 3, l + 1, l);
                            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);
            polygonSeg.triangleCount = this.indexArray.length - polygonSeg.triangleArrayOffset;
            this.polygonSegments.push(polygonSeg);
            ++centroid.footprintSegLen;
            ++centroid.polygonSegLen;
        }
        centroid.vertexCount = this.layoutVertexArray.length - centroid.vertexArrayOffset;
        centroid.groundVertexCount = this.groundEffect.vertexArray.length - centroid.groundVertexArrayOffset;
        if (centroid.vertexCount === 0) {
            return;
        }
        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);
        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]);
        }
    }
    splitToSubtiles() {
        const segmentedFeatures = [];
        for (let centroidIdx = 0; centroidIdx < this.centroidData.length; centroidIdx++) {
            const part = this.centroidData[centroidIdx];
            const right = +(part.min.x + part.max.x > EXTENT);
            const bottom = +(part.min.y + part.max.y > EXTENT);
            const subtile = bottom * 2 + (right ^ bottom);
            for (let i = 0; i < part.polygonSegLen; i++) {
                const polySegIdx = part.polygonSegIdx + i;
                segmentedFeatures.push({
                    centroidIdx,
                    subtile,
                    polygonSegmentIdx: polySegIdx,
                    triangleSegmentIdx: this.polygonSegments[polySegIdx].triangleSegIdx
                });
            }
        }
        const sortedTriangles = new StructArrayLayout3ui6();
        segmentedFeatures.sort((a, b) => a.triangleSegmentIdx === b.triangleSegmentIdx ? a.subtile - b.subtile : a.triangleSegmentIdx - b.triangleSegmentIdx);
        let segmentIdx = 0;
        let segmentBeginIndex = 0;
        let segmentEndIndex = 0;
        for (const segmentedFeature of segmentedFeatures) {
            if (segmentedFeature.triangleSegmentIdx !== segmentIdx) {
                break;
            }
            segmentEndIndex++;
        }
        const segmentedFeaturesEndIndex = segmentedFeatures.length;
        while (segmentBeginIndex !== segmentedFeatures.length) {
            segmentIdx = segmentedFeatures[segmentBeginIndex].triangleSegmentIdx;
            let subTileIdx = 0;
            let featuresBeginIndex = segmentBeginIndex;
            let featuresEndIndex = segmentBeginIndex;
            for (let seg = featuresBeginIndex; seg < segmentEndIndex; seg++) {
                if (segmentedFeatures[seg].subtile !== subTileIdx) {
                    break;
                }
                featuresEndIndex++;
            }
            while (featuresBeginIndex !== segmentEndIndex) {
                const featuresBegin = segmentedFeatures[featuresBeginIndex];
                subTileIdx = featuresBegin.subtile;
                const subtileMin = this.centroidData[featuresBegin.centroidIdx].min.clone();
                const subtileMax = this.centroidData[featuresBegin.centroidIdx].max.clone();
                const segment = {
                    vertexOffset: this.segments.segments[segmentIdx].vertexOffset,
                    primitiveOffset: sortedTriangles.length,
                    vertexLength: this.segments.segments[segmentIdx].vertexLength,
                    primitiveLength: 0,
                    sortKey: void 0,
                    vaos: {}
                };
                for (let featureIdx = featuresBeginIndex; featureIdx < featuresEndIndex; featureIdx++) {
                    const feature = segmentedFeatures[featureIdx];
                    const data = this.polygonSegments[feature.polygonSegmentIdx];
                    const centroidMin = this.centroidData[feature.centroidIdx].min;
                    const centroidMax = this.centroidData[feature.centroidIdx].max;
                    const iArray = this.indexArray.uint16;
                    for (let i = data.triangleArrayOffset; i < data.triangleArrayOffset + data.triangleCount; i++) {
                        sortedTriangles.emplaceBack(iArray[i * 3], iArray[i * 3 + 1], iArray[i * 3 + 2]);
                    }
                    segment.primitiveLength += data.triangleCount;
                    subtileMin.x = Math.min(subtileMin.x, centroidMin.x);
                    subtileMin.y = Math.min(subtileMin.y, centroidMin.y);
                    subtileMax.x = Math.max(subtileMax.x, centroidMax.x);
                    subtileMax.y = Math.max(subtileMax.y, centroidMax.y);
                }
                if (segment.primitiveLength > 0) {
                    this.triangleSubSegments.push({
                        segment,
                        min: subtileMin,
                        max: subtileMax
                    });
                }
                featuresBeginIndex = featuresEndIndex;
                for (let seg = featuresBeginIndex; seg < segmentEndIndex; seg++) {
                    if (segmentedFeatures[seg].subtile !== segmentedFeatures[featuresBeginIndex].subtile) {
                        break;
                    }
                    featuresEndIndex++;
                }
            }
            segmentBeginIndex = segmentEndIndex;
            for (let seg = segmentBeginIndex; seg < segmentedFeaturesEndIndex; seg++) {
                if (segmentedFeatures[seg].triangleSegmentIdx !== segmentedFeatures[segmentBeginIndex].triangleSegmentIdx) {
                    break;
                }
                segmentEndIndex++;
            }
        }
        sortedTriangles._trim();
        this.indexArray = sortedTriangles;
    }
    getVisibleSegments(renderId, elevation, frustum) {
        const outSegments = new SegmentVector();
        if (this.wallMode) {
            for (const subSegment of this.triangleSubSegments) {
                outSegments.segments.push(subSegment.segment);
            }
            return outSegments;
        }
        let minZ = 0;
        let maxZ = 0;
        const tiles = 1 << renderId.canonical.z;
        if (elevation) {
            const minmax = elevation.getMinMaxForTile(renderId);
            if (minmax) {
                minZ = minmax.min;
                maxZ = minmax.max;
            }
        }
        maxZ += this.maxHeight;
        const id = renderId.toUnwrapped();
        let activeSegment;
        const tileMin = [
            id.canonical.x / tiles + id.wrap,
            id.canonical.y / tiles
        ];
        const tileMax = [
            (id.canonical.x + 1) / tiles + id.wrap,
            (id.canonical.y + 1) / tiles
        ];
        const mix = (a, b, c) => {
            return [
                a[0] * (1 - c[0]) + b[0] * c[0],
                a[1] * (1 - c[1]) + b[1] * c[1]
            ];
        };
        const fracMin = [];
        const fracMax = [];
        for (const subSegment of this.triangleSubSegments) {
            fracMin[0] = subSegment.min.x / EXTENT;
            fracMin[1] = subSegment.min.y / EXTENT;
            fracMax[0] = subSegment.max.x / EXTENT;
            fracMax[1] = subSegment.max.y / EXTENT;
            const aabbMin = mix(tileMin, tileMax, fracMin);
            const aabbMax = mix(tileMin, tileMax, fracMax);
            const aabb = new Aabb([
                aabbMin[0],
                aabbMin[1],
                minZ
            ], [
                aabbMax[0],
                aabbMax[1],
                maxZ
            ]);
            if (aabb.intersectsPrecise(frustum) === 0) {
                if (activeSegment) {
                    outSegments.segments.push(activeSegment);
                    activeSegment = void 0;
                }
                continue;
            }
            const renderSegment = subSegment.segment;
            if (activeSegment && activeSegment.vertexOffset !== renderSegment.vertexOffset) {
                outSegments.segments.push(activeSegment);
                activeSegment = void 0;
            }
            if (!activeSegment) {
                activeSegment = {
                    vertexOffset: renderSegment.vertexOffset,
                    primitiveLength: renderSegment.primitiveLength,
                    vertexLength: renderSegment.vertexLength,
                    primitiveOffset: renderSegment.primitiveOffset,
                    sortKey: void 0,
                    vaos: {}
                };
            } else {
                activeSegment.vertexLength += renderSegment.vertexLength;
                activeSegment.primitiveLength += renderSegment.primitiveLength;
            }
        }
        if (activeSegment) {
            outSegments.segments.push(activeSegment);
        }
        return outSegments;
    }
    // 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(clamp(c.x, 1, EXTENT - 1) << 3 | spanX, clamp(c.y, 1, EXTENT - 1) << 3 | spanY);
    }
    // Border centroid data is unreliable for elevating parts split on tile borders.
    // It is used only for synchronous lowering of splits as the centroid (not the size information in split parts) is consistent.
    encodeBorderCentroid(borderCentroidData) {
        if (!borderCentroidData.borders)
            return new Point(0, 0);
        const b = borderCentroidData.borders;
        const notOnBorder = Number.MAX_VALUE;
        const span = 6;
        if (b[0][0] !== notOnBorder || b[1][0] !== notOnBorder) {
            const x = (b[0][0] !== notOnBorder ? 0 : 8191 << 3) | span;
            const index = b[0][0] !== notOnBorder ? 0 : 1;
            return new Point(x, ((b[index][0] + b[index][1]) / 2 | 0) << 3 | span);
        } else {
            const y = (b[2][0] !== notOnBorder ? 0 : 8191 << 3) | span;
            const index = b[2][0] !== notOnBorder ? 2 : 3;
            return new Point(((b[index][0] + b[index][1]) / 2 | 0) << 3 | span, y);
        }
    }
    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;
        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, layerIndex) {
        if (source.updateTime === this.replacementUpdateTime) {
            return;
        }
        this.replacementUpdateTime = source.updateTime;
        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 = [];
        for (const region of this.activeReplacements) {
            if (region.order < layerIndex)
                continue;
            const padding = Math.max(1, Math.pow(2, region.footprintTileId.canonical.z - coord.canonical.z));
            for (const centroid of this.centroidData) {
                if (centroid.flags & HIDDEN_BY_REPLACEMENT) {
                    continue;
                }
                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];
                    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)
            } : void 0;
        }
        for (const centroid of this.centroidData) {
            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) {
            this.partLookup[lookupKey] = void 0;
            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');
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$1(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) {
    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;
    }
    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;
    return cosAB > -0.866 && dotProductWithNormal < 0;
}
function encodeAOToEdgeDistance(edgeDistance, isConcaveCorner, edgeStart) {
    const encodedEdgeDistance = isConcaveCorner ? edgeDistance | 2 : edgeDistance & ~2;
    return edgeStart ? encodedEdgeDistance | 1 : encodedEdgeDistance & ~1;
}
function fillExtrusionHeightLift() {
    const angle = Math.PI / 32;
    const tanAngle = Math.tan(angle);
    const r = earthRadius;
    return r * Math.sqrt(1 + 2 * tanAngle * tanAngle) - r;
}
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(x, y));
    }
}

let layout$7;
const getLayoutProperties$7 = () => layout$7 || (layout$7 = new Properties({
    'visibility': new DataConstantProperty(spec['layout_fill-extrusion']['visibility']),
    'fill-extrusion-edge-radius': new DataConstantProperty(spec['layout_fill-extrusion']['fill-extrusion-edge-radius'])
}));
let paint$8;
const getPaintProperties$8 = () => paint$8 || (paint$8 = 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-height-alignment': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-height-alignment']),
    'fill-extrusion-base-alignment': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-base-alignment']),
    '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']),
    'fill-extrusion-emissive-strength': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-emissive-strength']),
    'fill-extrusion-line-width': new DataDrivenProperty(spec['paint_fill-extrusion']['fill-extrusion-line-width']),
    'fill-extrusion-cast-shadows': new DataConstantProperty(spec['paint_fill-extrusion']['fill-extrusion-cast-shadows']),
    'fill-extrusion-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'fill-extrusion-flood-light-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

class FillExtrusionStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$7(),
            paint: getPaintProperties$8()
        };
        super(layer, properties, scope, lut, options);
        this._stats = {
            numRenderedVerticesInShadowPass: 0,
            numRenderedVerticesInTransparentPass: 0
        };
    }
    createBucket(parameters) {
        return new FillExtrusionBucket(parameters);
    }
    queryRadius() {
        return translateDistance(this.paint.get('fill-extrusion-translate'));
    }
    is3D() {
        return true;
    }
    hasShadowPass() {
        return this.paint.get('fill-extrusion-cast-shadows');
    }
    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'];
    }
    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;
            const centroidOffset = layoutVertexArrayOffset + 1;
            if (centroidOffset < centroidVertexArray.length) {
                centroid[0] = centroidVertexArray.geta_centroid_pos0(centroidOffset);
                centroid[1] = centroidVertexArray.geta_centroid_pos1(centroidOffset);
            }
        }
        const isHidden = centroid[0] === 0 && centroid[1] === 1;
        if (isHidden)
            return false;
        if (transform.projection.name === 'globe') {
            const bounds = [
                new Point(0, 0),
                new Point(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) {
        let i = 0;
        const a = projectedFace[i++];
        let b;
        while (!b || a.equals(b)) {
            b = projectedFace[i++];
            if (!b)
                return Infinity;
        }
        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;
            const distance = a.z * u + b.z * v + c.z * w;
            if (isFinite(distance))
                return distance;
        }
        return Infinity;
    } else {
        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;
    };
    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;
            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);
            cjsExports.vec3.transformMat4(basePoint, basePoint, m);
            cjsExports.vec3.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
    ];
}
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
    ];
}
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;
            cjsExports.vec4.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;
            cjsExports.vec4.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
    };
}
function elevationFromUint16(n) {
    return n / ELEVATION_SCALE - ELEVATION_OFFSET;
}
function flatElevation(demSampler, centroid, lat) {
    const posX = Math.floor(centroid[0] / 8);
    const posY = Math.floor(centroid[1] / 8);
    const spanX = 10 * (centroid[0] - posX * 8);
    const spanY = 10 * (centroid[1] - posY * 8);
    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)
    ];
}

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 lineZOffsetAttributes = createLayout([{
        name: 'a_z_offset_width',
        components: 3,
        type: 'Float32'
    }], 4);
const {members: members$2, size: size$2, alignment: alignment$2} = lineLayoutAttributes;

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

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

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) {
        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) {
        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);
            }
        }
        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;
        }
        if (dasharray.length === 0) {
            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 vectorTileFeatureTypes$1 = vectorTileExports.VectorTileFeature.types;
const EXTRUDE_SCALE = 63;
const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));
const COS_STRAIGHT_CORNER = Math.cos(5 * (Math.PI / 180));
const DEG_PER_TRIANGLE = 20;
class LineBucket {
    constructor(options) {
        this.evaluationGlobals = {
            'zoom': 0,
            'lineProgress': void 0
        };
        this.zoom = options.zoom;
        this.evaluationGlobals.zoom = this.zoom;
        this.overscaling = options.overscaling;
        this.pixelRatio = options.pixelRatio;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.index = options.index;
        this.projection = options.projection;
        this.hasPattern = false;
        this.hasZOffset = false;
        this.hasCrossSlope = false;
        this.patternFeatures = [];
        this.lineClipsArray = [];
        this.gradients = {};
        this.layers.forEach(layer => {
            this.gradients[layer.id] = {};
        });
        this.layoutVertexArray = new StructArrayLayout2i4ub1f12();
        this.layoutVertexArray2 = new StructArrayLayout3f12();
        this.patternVertexArray = new StructArrayLayout3f12();
        this.indexArray = new StructArrayLayout3ui6();
        this.programConfigurations = new ProgramConfigurationSet(options.layers, {
            zoom: options.zoom,
            lut: options.lut
        });
        this.segments = new SegmentVector();
        this.maxLineLength = 0;
        this.zOffsetVertexArray = new StructArrayLayout3f12();
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.tessellationStep = options.tessellationStep ? options.tessellationStep : EXTENT / 64;
    }
    updateFootprints(_id, _footprints) {
    }
    populate(features, options, canonical, tileTransform) {
        this.hasPattern = hasPattern('line', this.layers, this.pixelRatio, options);
        const lineSortKey = this.layers[0].layout.get('line-sort-key');
        this.tileToMeter = tileToMeter(canonical);
        const zOffset = this.layers[0].layout.get('line-z-offset');
        const zOffsetZero = zOffset.isConstant() && !zOffset.constantOr(0);
        const elevationReference = this.layers[0].layout.get('line-elevation-reference');
        const seaOrGroundReference = elevationReference === 'sea' || elevationReference === 'ground';
        this.hasZOffset = seaOrGroundReference || !zOffsetZero && elevationReference === 'none';
        if (this.hasZOffset && elevationReference === 'none') {
            warnOnce(`line-elevation-reference: ground is used for the layer ${ this.layerIds[0] } because non-zero line-z-offset value was found.`);
        }
        const crossSlope = this.layers[0].layout.get('line-cross-slope');
        this.hasCrossSlope = this.hasZOffset && crossSlope !== void 0;
        const bucketFeatures = [];
        for (const {feature, id, index, sourceLayerIndex} of features) {
            const needGeometry = this.layers[0]._featureFilter.needGeometry;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const sortKey = lineSortKey ? lineSortKey.evaluate(evaluationFeature, {}, canonical) : void 0;
            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) => {
                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, this.pixelRatio, options);
                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);
            feature.patterns[layer.id] = lineAtlas.getKey(dashArray, cap);
        }
    }
    update(states, vtLayer, availableImages, imagePositions, layers, isBrightnessChanged, brightness) {
        this.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, 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);
            }
            if (this.patternVertexArray.length !== 0) {
                this.patternVertexBuffer = context.createVertexBuffer(this.patternVertexArray, members);
            }
            if (!this.zOffsetVertexBuffer && this.zOffsetVertexArray.length > 0) {
                this.zOffsetVertexBuffer = context.createVertexBuffer(this.zOffsetVertexArray, lineZOffsetAttributes.members, true);
            }
            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;
        if (this.zOffsetVertexBuffer) {
            this.zOffsetVertexBuffer.destroy();
        }
        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);
        this.lineFeature = feature;
        this.zOffsetValue = layout.get('line-z-offset').value;
        const paint = this.layers[0].paint;
        const lineWidth = paint.get('line-width').value;
        if (lineWidth.kind !== 'constant' && lineWidth.isLineProgressConstant === false) {
            this.variableWidthValue = lineWidth;
        }
        for (const line of geometry) {
            this.addLine(line, feature, canonical, join, cap, miterLimit, roundLimit);
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical, brightness);
    }
    addLine(vertices, feature, canonical, join, cap, miterLimit, roundLimit) {
        this.distance = 0;
        this.prevDistance = 0;
        this.scaledDistance = 0;
        this.totalDistance = 0;
        this.totalFeatureLength = 0;
        this.lineSoFar = 0;
        this.currentVertex = void 0;
        const joinNone = join === 'none';
        this.patternJoinNone = this.hasPattern && joinNone;
        this.segmentStart = 0;
        this.segmentStartf32 = 0;
        this.segmentPoints = [];
        if (this.lineClips) {
            this.lineClipsArray.push(this.lineClips);
            for (let i = 0; i < vertices.length - 1; i++) {
                this.totalDistance += vertices[i].dist(vertices[i + 1]);
            }
            const featureShare = this.lineClips.end - this.lineClips.start;
            this.totalFeatureLength = this.totalDistance / featureShare;
            this.updateScaledDistance();
            this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);
        }
        const isPolygon = vectorTileFeatureTypes$1[feature.type] === 'Polygon';
        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++;
        }
        if (len < (isPolygon ? 3 : 2))
            return;
        if (join === 'bevel')
            miterLimit = 1.05;
        const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);
        let currentVertex;
        let prevVertex = void 0;
        let nextVertex = void 0;
        let prevNormal = void 0;
        let nextNormal = void 0;
        this.e1 = this.e2 = -1;
        if (isPolygon) {
            currentVertex = vertices[len - 2];
            nextNormal = vertices[first].sub(currentVertex)._unit()._perp();
        }
        let lineProgressFeatures;
        for (let i = first; i < len; i++) {
            nextVertex = i === len - 1 ? isPolygon ? vertices[first + 1] : void 0 : // if it's a polygon, treat the last vertex like the first
            vertices[i + 1];
            if (nextVertex && vertices[i].equals(nextVertex))
                continue;
            if (nextNormal)
                prevNormal = nextNormal;
            if (currentVertex)
                prevVertex = currentVertex;
            currentVertex = vertices[i];
            lineProgressFeatures = this.evaluateLineProgressFeatures(prevVertex ? prevVertex.dist(currentVertex) : 0);
            nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;
            prevNormal = prevNormal || nextNormal;
            const middleVertex = prevVertex && nextVertex;
            let currentJoin = middleVertex ? join : isPolygon || joinNone ? 'butt' : cap;
            const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;
            if (joinNone) {
                const endLineSegment = function (bucket) {
                    if (bucket.patternJoinNone) {
                        const pointCount = bucket.segmentPoints.length / 2;
                        const segmentLength = bucket.lineSoFar - bucket.segmentStart;
                        for (let idx = 0; idx < pointCount; ++idx) {
                            const pos = bucket.segmentPoints[idx * 2];
                            const offsetSign = bucket.segmentPoints[idx * 2 + 1];
                            const posAndOffset = Math.round(pos) + 0.5 + offsetSign * 0.25;
                            bucket.patternVertexArray.emplaceBack(posAndOffset, segmentLength, bucket.segmentStart);
                            bucket.patternVertexArray.emplaceBack(posAndOffset, segmentLength, bucket.segmentStart);
                        }
                        bucket.segmentPoints.length = 0;
                    }
                    bucket.e1 = bucket.e2 = -1;
                };
                if (middleVertex && cosAngle < COS_STRAIGHT_CORNER) {
                    this.updateDistance(prevVertex, currentVertex);
                    this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, lineProgressFeatures);
                    endLineSegment(this);
                    this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, lineProgressFeatures);
                    continue;
                } else if (prevVertex) {
                    if (!nextVertex) {
                        this.updateDistance(prevVertex, currentVertex);
                        this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, lineProgressFeatures);
                        endLineSegment(this);
                        continue;
                    } else {
                        currentJoin = 'miter';
                    }
                }
            }
            let joinNormal = prevNormal.add(nextNormal);
            if (joinNormal.x !== 0 || joinNormal.y !== 0) {
                joinNormal._unit();
            }
            const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
            const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;
            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;
            const SHARP_CORNER_OFFSET = 15;
            const sharpCornerOffset = this.overscaling <= 16 ? SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) : 0;
            if (middleVertex && currentJoin === 'round') {
                if (miterLength < roundLimit) {
                    currentJoin = 'miter';
                } else if (miterLength <= 2) {
                    const boundsMin = -10;
                    const boundsMax = EXTENT + 10;
                    const outside = pointOutsideBounds(currentVertex, boundsMin, boundsMax);
                    currentJoin = this.hasZOffset && (outside || this.hasCrossSlope) ? 'miter' : 'fakeround';
                }
            }
            if (currentJoin === 'miter' && miterLength > miterLimit) {
                currentJoin = 'bevel';
            }
            if (currentJoin === 'bevel') {
                if (miterLength > 2)
                    currentJoin = 'flipbevel';
                if (miterLength < miterLimit)
                    currentJoin = 'miter';
            }
            const sharpMiter = currentJoin === 'miter' && isSharpCorner;
            if (prevVertex && !sharpMiter)
                this.updateDistance(prevVertex, currentVertex);
            if (currentJoin === 'miter') {
                if (isSharpCorner) {
                    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, lineProgressFeatures);
                        prevVertex = newPrevVertex;
                    }
                    this.updateDistance(prevVertex, currentVertex);
                    joinNormal._mult(miterLength);
                    this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, lineProgressFeatures);
                    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, lineProgressFeatures);
                        currentVertex = newCurrentVertex;
                    }
                } else {
                    joinNormal._mult(miterLength);
                    this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, lineProgressFeatures);
                }
            } else if (currentJoin === 'flipbevel') {
                if (miterLength > 100) {
                    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, lineProgressFeatures);
                this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment, lineProgressFeatures);
            } else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {
                if (lineProgressFeatures != null && prevVertex) {
                    this.addCurrentVertex(currentVertex, prevNormal, -1, -1, segment, lineProgressFeatures);
                }
                const dist = currentVertex.dist(prevVertex);
                const skipStraightEdges = dist <= 2 * sharpCornerOffset && currentJoin !== 'bevel';
                const join2 = joinNormal.mult(lineTurnsLeft ? 1 : -1);
                join2._mult(miterLength);
                const next = nextNormal.mult(lineTurnsLeft ? -1 : 1);
                const prev = prevNormal.mult(lineTurnsLeft ? -1 : 1);
                const lpf = this.evaluateLineProgressFeatures(this.distance);
                if (lineProgressFeatures == null) {
                    this.addHalfVertex(currentVertex, join2.x, join2.y, false, !lineTurnsLeft, 0, segment, lpf);
                    if (!skipStraightEdges) {
                        this.addHalfVertex(currentVertex, join2.x + prev.x * 2, join2.y + prev.y * 2, false, lineTurnsLeft, 0, segment, lpf);
                    }
                }
                if (currentJoin === 'fakeround') {
                    const n = Math.round(approxAngle * 180 / Math.PI / DEG_PER_TRIANGLE);
                    this.addHalfVertex(currentVertex, prev.x, prev.y, false, lineTurnsLeft, 0, segment, lpf);
                    for (let m = 0; m < n; m++) {
                        let t = m / n;
                        if (t !== 0.5) {
                            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 = next.sub(prev)._mult(t)._add(prev)._unit();
                        this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment, lpf);
                    }
                    this.addHalfVertex(currentVertex, next.x, next.y, false, lineTurnsLeft, 0, segment, lpf);
                }
                if (!skipStraightEdges && lineProgressFeatures == null) {
                    this.addHalfVertex(currentVertex, join2.x + next.x * 2, join2.y + next.y * 2, false, lineTurnsLeft, 0, segment, lpf);
                }
                if (lineProgressFeatures != null && nextVertex) {
                    this.addCurrentVertex(currentVertex, nextNormal, 1, 1, segment, lineProgressFeatures);
                }
            } else if (currentJoin === 'butt') {
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, lineProgressFeatures);
            } else if (currentJoin === 'square') {
                if (!prevVertex) {
                    this.addCurrentVertex(currentVertex, joinNormal, -1, -1, segment, lineProgressFeatures);
                }
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, lineProgressFeatures);
                if (prevVertex) {
                    this.addCurrentVertex(currentVertex, joinNormal, 1, 1, segment, lineProgressFeatures);
                }
            } else if (currentJoin === 'round') {
                if (prevVertex) {
                    this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment, lineProgressFeatures);
                    this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, lineProgressFeatures, true);
                }
                if (nextVertex) {
                    this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, lineProgressFeatures, true);
                    this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment, lineProgressFeatures);
                }
            }
        }
    }
    addVerticesTo(from, to, leftX, leftY, rightX, rightY, endLeft, endRight, segment, round) {
        const STEP = this.tessellationStep;
        const steps = (to.w - from.w) / STEP | 0;
        let stepsDistance = 0;
        const scaledDistance = this.scaledDistance;
        if (steps > 1) {
            this.lineSoFar = from.w;
            const stepX = (to.x - from.x) / steps;
            const stepY = (to.y - from.y) / steps;
            const stepZ = (to.z - from.z) / steps;
            const stepW = (to.w - from.w) / steps;
            for (let i = 1; i < steps; ++i) {
                from.x += stepX;
                from.y += stepY;
                from.z += stepZ;
                this.lineSoFar += stepW;
                stepsDistance += stepW;
                const lpf2 = this.evaluateLineProgressFeatures(this.prevDistance + stepsDistance);
                this.scaledDistance = (this.prevDistance + stepsDistance) / this.totalDistance;
                this.addHalfVertex(from, leftX, leftY, round, false, endLeft, segment, lpf2);
                this.addHalfVertex(from, rightX, rightY, round, true, -endRight, segment, lpf2);
            }
        }
        this.lineSoFar = to.w;
        this.scaledDistance = scaledDistance;
        const lpf = this.evaluateLineProgressFeatures(this.distance);
        this.addHalfVertex(to, leftX, leftY, round, false, endLeft, segment, lpf);
        this.addHalfVertex(to, rightX, rightY, round, true, -endRight, segment, lpf);
    }
    evaluateLineProgressFeatures(distance) {
        if (!this.variableWidthValue && !this.hasZOffset) {
            return null;
        }
        this.evaluationGlobals.lineProgress = 0;
        if (this.lineClips) {
            this.evaluationGlobals.lineProgress = Math.min(1, (this.totalFeatureLength * this.lineClips.start + distance) / this.totalFeatureLength);
        } else {
            warnOnce(`line-progress evaluation for ${ this.layerIds[0] } requires enabling 'lineMetrics' for the source.`);
        }
        let variableWidth = 0;
        if (this.variableWidthValue && this.variableWidthValue.kind !== 'constant') {
            variableWidth = this.variableWidthValue.evaluate(this.evaluationGlobals, this.lineFeature) || 0;
        }
        if (!this.hasZOffset) {
            return {
                zOffset: 0,
                variableWidth
            };
        }
        if (this.zOffsetValue.kind === 'constant') {
            return {
                zOffset: this.zOffsetValue.value,
                variableWidth
            };
        }
        const zOffset = this.zOffsetValue.evaluate(this.evaluationGlobals, this.lineFeature) || 0;
        return {
            zOffset,
            variableWidth
        };
    }
    /**
   * 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, lineProgressFeatures, round = false) {
        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;
        if (lineProgressFeatures != null) {
            const dropOutOfBounds = this.hasZOffset;
            const boundsMin = -10;
            const boundsMax = EXTENT + 10;
            const zOffset = lineProgressFeatures.zOffset;
            const vertex = new Point4D(p.x, p.y, zOffset, this.lineSoFar);
            const outside = dropOutOfBounds ? pointOutsideBounds(p, boundsMin, boundsMax) : false;
            const lineSoFar = this.lineSoFar;
            const distance = this.distance;
            if (!this.currentVertex) {
                if (!outside) {
                    this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment, lineProgressFeatures);
                    this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment, lineProgressFeatures);
                }
            } else if (outside) {
                const prevOutside = this.currentVertexIsOutside;
                const prev = this.currentVertex;
                const next = new Point4D(p.x, p.y, zOffset, this.lineSoFar);
                clipLine$1(prev, next, boundsMin, boundsMax);
                if (!pointOutsideBounds(next, boundsMin, boundsMax)) {
                    if (prevOutside) {
                        this.e1 = this.e2 = -1;
                        this.distance -= prev.dist(vertex);
                        this.lineSoFar = prev.w;
                        const lpf = this.evaluateLineProgressFeatures(prev.w - this.totalFeatureLength * (this.lineClips ? this.lineClips.start : 0));
                        this.addHalfVertex(prev, leftX, leftY, round, false, endLeft, segment, lpf);
                        this.addHalfVertex(prev, rightX, rightY, round, true, -endRight, segment, lpf);
                        this.prevDistance = this.distance;
                    }
                    this.distance = this.prevDistance + prev.dist(next);
                    this.scaledDistance = this.distance / this.totalDistance;
                    this.addVerticesTo(prev, next, leftX, leftY, rightX, rightY, endLeft, endRight, segment, round);
                    this.distance = distance;
                    this.scaledDistance = this.distance / this.totalDistance;
                }
            } else {
                const prevOutside = this.currentVertexIsOutside;
                const prev = this.currentVertex;
                if (prevOutside) {
                    clipLine$1(prev, vertex, boundsMin, boundsMax);
                    this.e1 = this.e2 = -1;
                    this.distance -= prev.dist(vertex);
                    this.scaledDistance = this.distance / this.totalDistance;
                    this.lineSoFar = prev.w;
                    const lpf = this.evaluateLineProgressFeatures(prev.w - this.totalFeatureLength * (this.lineClips ? this.lineClips.start : 0));
                    this.addHalfVertex(prev, leftX, leftY, round, false, endLeft, segment, lpf);
                    this.addHalfVertex(prev, rightX, rightY, round, true, -endRight, segment, lpf);
                    this.prevDistance = this.distance;
                    this.distance = distance;
                    this.scaledDistance = this.distance / this.totalDistance;
                }
                this.addVerticesTo(prev, vertex, leftX, leftY, rightX, rightY, endLeft, endRight, segment, round);
            }
            this.currentVertex = vertex;
            this.currentVertexIsOutside = outside;
            this.lineSoFar = lineSoFar;
        } else {
            this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment, lineProgressFeatures);
            this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment, lineProgressFeatures);
        }
    }
    addHalfVertex({x, y}, extrudeX, extrudeY, round, up, dir, segment, lineProgressFeatures) {
        if (this.patternJoinNone) {
            if (this.segmentPoints.length === 0) {
                this.segmentStart = this.lineSoFar;
                this.segmentStartf32 = Math.fround(this.lineSoFar);
            }
            if (!up) {
                this.segmentPoints.push(this.lineSoFar - this.segmentStart, dir);
            }
        }
        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 - this.segmentStartf32);
        if (this.lineClips) {
            const lineProgress = number(this.lineClips.start, this.lineClips.end, this.scaledDistance);
            this.layoutVertexArray2.emplaceBack(this.scaledDistance, this.lineClipsArray.length, lineProgress);
        }
        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;
        }
        if (lineProgressFeatures != null) {
            this.zOffsetVertexArray.emplaceBack(lineProgressFeatures.zOffset, lineProgressFeatures.variableWidth, lineProgressFeatures.variableWidth);
        }
    }
    updateScaledDistance() {
        if (this.lineClips) {
            this.scaledDistance = this.distance / this.totalDistance;
            this.lineSoFar = this.totalFeatureLength * this.lineClips.start + this.distance;
        } else {
            this.lineSoFar = this.distance;
        }
    }
    updateDistance(prev, next) {
        this.prevDistance = this.distance;
        this.distance += prev.dist(next);
        this.updateScaledDistance();
    }
}
function pointOutsideBounds(p, min, max) {
    return p.x < min || p.x > max || p.y < min || p.y > max;
}
register(LineBucket, 'LineBucket', {
    omit: [
        'layers',
        'patternFeatures',
        'currentVertex',
        'currentVertexIsOutside'
    ]
});

let layout$6;
const getLayoutProperties$6 = () => layout$6 || (layout$6 = 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']),
    'line-z-offset': new DataDrivenProperty(spec['layout_line']['line-z-offset']),
    'line-elevation-reference': new DataConstantProperty(spec['layout_line']['line-elevation-reference']),
    'line-cross-slope': new DataConstantProperty(spec['layout_line']['line-cross-slope']),
    'visibility': new DataConstantProperty(spec['layout_line']['visibility']),
    'line-width-unit': new DataConstantProperty(spec['layout_line']['line-width-unit'])
}));
let paint$7;
const getPaintProperties$7 = () => paint$7 || (paint$7 = 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-trim-fade-range': new DataConstantProperty(spec['paint_line']['line-trim-fade-range']),
    'line-trim-color': new DataConstantProperty(spec['paint_line']['line-trim-color']),
    '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']),
    'line-occlusion-opacity': new DataConstantProperty(spec['paint_line']['line-occlusion-opacity']),
    'line-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'line-gradient-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'line-trim-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'line-border-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

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 cjsExports.mat2.scale(new Float32Array(4), transform.inverseAdjustmentMatrix, [
        s,
        s
    ]);
}

const lineUniforms = context => ({
    'u_matrix': new UniformMatrix4f(context),
    'u_pixels_to_tile_units': new UniformMatrix2f(context),
    'u_device_pixel_ratio': new Uniform1f(context),
    'u_width_scale': new Uniform1f(context),
    'u_floor_width_scale': 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_trim_fade_range': new Uniform2f(context),
    'u_trim_color': new Uniform4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_zbias_factor': new Uniform1f(context),
    'u_tile_to_meter': 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_width_scale': new Uniform1f(context),
    'u_floor_width_scale': 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),
    'u_trim_offset': new Uniform2f(context),
    'u_trim_fade_range': new Uniform2f(context),
    'u_trim_color': new Uniform4f(context),
    'u_emissive_strength': new Uniform1f(context),
    'u_zbias_factor': new Uniform1f(context),
    'u_tile_to_meter': new Uniform1f(context)
});
const lerp = (a, b, t) => {
    return (1 - t) * a + t * b;
};
const lineUniformValues = (painter, tile, layer, matrix, imageHeight, pixelRatio, widthScale, floorWidthScale, trimOffset) => {
    const transform = painter.transform;
    const pixelsToTileUnits2 = transform.calculatePixelsToTileUnitsMatrix(tile);
    const ignoreLut = layer.paint.get('line-trim-color-use-theme').constantOr('default') === 'none';
    const zbiasFactor = transform.pitch < 15 ? lerp(0.07, 0.7, clamp((14 - transform.zoom) / (14 - 9), 0, 1)) : 0.07;
    return {
        'u_matrix': calculateMatrix(painter, tile, layer, matrix),
        'u_pixels_to_tile_units': pixelsToTileUnits2,
        'u_device_pixel_ratio': pixelRatio,
        'u_width_scale': widthScale,
        'u_floor_width_scale': floorWidthScale,
        '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 ? tile.lineAtlasTexture.size : [
            0,
            0
        ],
        'u_tile_units_to_pixels': calculateTileRatio(tile, painter.transform),
        'u_alpha_discard_threshold': 0,
        'u_trim_offset': trimOffset,
        'u_trim_fade_range': layer.paint.get('line-trim-fade-range'),
        'u_trim_color': layer.paint.get('line-trim-color').toRenderColor(ignoreLut ? null : layer.lut).toArray01(),
        'u_emissive_strength': layer.paint.get('line-emissive-strength'),
        'u_zbias_factor': zbiasFactor,
        'u_tile_to_meter': tileToMeter(tile.tileID.canonical, 0)
    };
};
const linePatternUniformValues = (painter, tile, layer, matrix, pixelRatio, widthScale, floorWidthScale, trimOffset) => {
    const transform = painter.transform;
    const zbiasFactor = transform.pitch < 15 ? lerp(0.07, 0.7, clamp((14 - transform.zoom) / (14 - 9), 0, 1)) : 0.07;
    const ignoreLut = layer.paint.get('line-trim-color-use-theme').constantOr('default') === 'none';
    return {
        'u_matrix': calculateMatrix(painter, tile, layer, matrix),
        'u_texsize': tile.imageAtlasTexture ? tile.imageAtlasTexture.size : [
            0,
            0
        ],
        // camera zoom ratio
        'u_pixels_to_tile_units': transform.calculatePixelsToTileUnitsMatrix(tile),
        'u_device_pixel_ratio': pixelRatio,
        'u_width_scale': widthScale,
        'u_floor_width_scale': floorWidthScale,
        '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,
        'u_trim_offset': trimOffset,
        'u_trim_fade_range': layer.paint.get('line-trim-fade-range'),
        'u_trim_color': layer.paint.get('line-trim-color').toRenderColor(ignoreLut ? null : layer.lut).toArray01(),
        'u_emissive_strength': layer.paint.get('line-emissive-strength'),
        'u_zbias_factor': zbiasFactor,
        'u_tile_to_meter': tileToMeter(tile.tileID.canonical, 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');
    const hasJoinNone = layer.layout.get('line-join').constantOr('miter') === 'none';
    const hasPattern = !!layer.paint.get('line-pattern').constantOr(1);
    if (hasJoinNone && hasPattern) {
        values.push('LINE_JOIN_NONE');
    }
    return values;
};
function hasDash(layer) {
    const dashPropertyValue = layer.paint.get('line-dasharray').value;
    return dashPropertyValue.value || dashPropertyValue.kind !== 'constant';
}

let properties$1;
const getProperties$1 = () => {
    if (properties$1) {
        return properties$1;
    }
    properties$1 = {
        layout: getLayoutProperties$6(),
        paint: getPaintProperties$7()
    };
    return properties$1;
};
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);
    }
}
let lineFloorwidthProperty;
const getLineFloorwidthProperty = () => {
    if (lineFloorwidthProperty) {
        return lineFloorwidthProperty;
    }
    const properties2 = getProperties$1();
    lineFloorwidthProperty = new LineFloorwidthProperty(properties2.paint.properties['line-width'].specification);
    lineFloorwidthProperty.useIntegerZoom = true;
    return lineFloorwidthProperty;
};
class LineStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties2 = getProperties$1();
        super(layer, properties2, scope, lut, options);
        if (properties2.layout) {
            this.layout = new PossiblyEvaluated(properties2.layout);
        }
        this.gradientVersion = 0;
        this.hasElevatedBuckets = false;
        this.hasNonElevatedBuckets = false;
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'line-gradient') {
            const expression = this._transitionablePaint._values['line-gradient'].value.expression;
            this.stepInterpolant = expression._styleExpression && expression._styleExpression.expression instanceof Step;
            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'] = getLineFloorwidthProperty().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, lut) {
        const definesValues = lineDefinesValues(this);
        return {
            config: new ProgramConfiguration(this, {
                zoom,
                lut
            }),
            defines: definesValues,
            overrideFog: false
        };
    }
    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'));
    }
    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;
    }
    isDraped(_) {
        return !this.hasElevatedBuckets;
    }
}
function getLineWidth(lineWidth, lineGapWidth) {
    if (lineGapWidth > 0) {
        return lineGapWidth + 2 * lineWidth;
    } else {
        return lineWidth;
    }
}
function offsetLine(rings, offset) {
    const newRings = [];
    const zero = new Point(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;
}

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_auto_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'
    },
    {
        name: 'a_elevation_from_sea',
        components: 2,
        type: 'Float32'
    }
]);
const collisionVertexAttributesExt = createLayout([
    {
        name: 'a_size_scale',
        components: 1,
        type: 'Float32'
    },
    {
        name: 'a_padding',
        components: 2,
        type: 'Float32'
    },
    {
        name: 'a_auto_z_offset',
        components: 1,
        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'
    }
]);

var ONE_EM = 24;

const SIZE_PACK_FACTOR = 128;
function getRasterizedIconSize(sizeData, unevaluatedIconSize, canonical, zoom, feature) {
    if (sizeData.kind === 'camera') {
        return sizeData.maxSize;
    }
    if (sizeData.kind === 'composite') {
        const maxZoomSize = unevaluatedIconSize.possiblyEvaluate(new EvaluationParameters(sizeData.maxZoom), canonical).evaluate(feature, {}, canonical);
        const minZoomSize = unevaluatedIconSize.possiblyEvaluate(new EvaluationParameters(sizeData.minZoom), canonical).evaluate(feature, {}, canonical);
        return Math.max(maxZoomSize, minZoomSize);
    }
    return unevaluatedIconSize.possiblyEvaluate(new EvaluationParameters(zoom)).evaluate(feature, {}, canonical);
}
function getSizeData(tileZoom, value) {
    const {expression} = value;
    if (expression.kind === 'constant') {
        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;
        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];
        if (expression.kind === 'composite') {
            return {
                kind: 'composite',
                minZoom,
                maxZoom,
                interpolationType
            };
        }
        const minSize = expression.evaluate(new EvaluationParameters(minZoom));
        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, scaleFactor = 1) {
    let uSizeT = 0;
    let uSize = 0;
    if (sizeData.kind === 'constant') {
        uSize = sizeData.layoutSize * scaleFactor;
    } else if (sizeData.kind !== 'source') {
        const {interpolationType, minZoom, maxZoom} = sizeData;
        const t = !interpolationType ? 0 : clamp(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);
        if (sizeData.kind === 'camera') {
            uSize = number(sizeData.minSize, sizeData.maxSize, t) * scaleFactor;
        } else {
            uSizeT = t * scaleFactor;
        }
    }
    return {
        uSizeT,
        uSize
    };
}

var symbolSize = /*#__PURE__*/Object.freeze({
__proto__: null,
SIZE_PACK_FACTOR: SIZE_PACK_FACTOR,
evaluateSizeForFeature: evaluateSizeForFeature,
evaluateSizeForZoom: evaluateSizeForZoom,
getRasterizedIconSize: getRasterizedIconSize,
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]) {
            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) {
            mergeFromRight(leftKey, rightKey, geom);
        } else if (rightKey in leftIndex) {
            mergeFromLeft(leftKey, rightKey, geom);
        } else {
            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';
}

var ieee754 = {};

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

var hasRequiredIeee754;

function requireIeee754 () {
	if (hasRequiredIeee754) return ieee754;
	hasRequiredIeee754 = 1;
	ieee754.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.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;
	};
	return ieee754;
}

var pbf;
var hasRequiredPbf;

function requirePbf () {
	if (hasRequiredPbf) return pbf;
	hasRequiredPbf = 1;
	pbf = Pbf;
	var ieee754 = requireIeee754();
	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;
	}
	return pbf;
}

var pbfExports = requirePbf();
var Pbf$1 = /*@__PURE__*/getDefaultExportFromCjs(pbfExports);

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 Pbf$1(data).readFields(readFontstacks, {});
}
const GLYPH_PBF_BORDER = border$1;

const WritingMode = {
    horizontal: 1,
    vertical: 2,
    horizontalOnly: 3
};
const SHAPING_DEFAULT_OFFSET = -17;
function isEmpty(positionedLines) {
    for (const line of positionedLines) {
        if (line.positionedGlyphs.length !== 0) {
            return false;
        }
    }
    return true;
}
const PUAbegin = 57344;
const PUAend = 63743;
class SectionOptions {
    constructor() {
        this.scale = 1;
        this.fontStack = '';
        this.image = null;
    }
    static forText(scale, fontStack) {
        const textOptions = new SectionOptions();
        textOptions.scale = scale || 1;
        textOptions.fontStack = fontStack;
        return textOptions;
    }
    static forImage(image) {
        const imageOptions = new SectionOptions();
        imageOptions.image = image;
        return imageOptions;
    }
}
class TaggedString {
    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 image = section.image && section.image.namePrimary ? section.image.getPrimary() : null;
        if (!image) {
            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(image));
        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) {
        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) {
        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;
}
const whitespace = {
    [9]: true,
    // tab
    [10]: true,
    // newline
    [11]: true,
    // vertical tab
    [12]: true,
    // form feed
    [13]: true,
    // carriage return
    [32]: true    // space
};
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.image) {
        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.image.serialize()];
        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) {
        if (lineWidth < targetWidth) {
            return raggedness / 2;
        } else {
            return raggedness * 2;
        }
    }
    return raggedness + Math.abs(penalty) * penalty;
}
function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) {
    let penalty = 0;
    if (codePoint === 10) {
        penalty -= 10000;
    }
    if (penalizableIdeographicBreak) {
        penalty += 150;
    }
    if (codePoint === 40 || codePoint === 65288) {
        penalty += 50;
    }
    if (nextCodePoint === 41 || nextCodePoint === 65289) {
        penalty += 50;
    }
    return penalty;
}
function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) {
    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);
        if (i < logicalInput.length() - 1) {
            const ideographicBreak = charAllowsIdeographicBreaking(codePoint);
            if (breakable[codePoint] || ideographicBreak || section.image) {
                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.image)
                continue;
            const glyphData = glyphMap[section.fontStack];
            if (!glyphData)
                continue;
            hasBaseline = glyphData.ascender !== void 0 && glyphData.descender !== void 0;
            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;
            ++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 || // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled.
            !allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint) || // If vertical placement is enabled, don't verticalize glyphs that
            // are from complex text layout script, or whitespaces.
            allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)));
            if (!section.image) {
                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;
                if (hasBaseline) {
                    const ascender = glyphData.ascender !== void 0 ? Math.abs(glyphData.ascender) : 0;
                    const descender = glyphData.descender !== void 0 ? Math.abs(glyphData.descender) : 0;
                    const value = (ascender + descender) * sectionScale;
                    if (biggestHeight < value) {
                        biggestHeight = value;
                        baselineOffset = (ascender - descender) / 2 * sectionScale;
                    }
                    glyphOffset = -ascender * sectionScale;
                } else {
                    glyphOffset = SHAPING_DEFAULT_OFFSET + (lineMaxScale - sectionScale) * ONE_EM;
                }
            } else {
                const imagePosition = imagePositions[section.image.serialize()];
                if (!imagePosition)
                    continue;
                imageName = section.image.id;
                shaping.iconsInText = shaping.iconsInText || true;
                rect = imagePosition.paddedRect;
                const size = imagePosition.displaySize;
                sectionScale = sectionScale * ONE_EM / layoutTextSizeThisZoom;
                metrics = {
                    width: size[0],
                    height: size[1],
                    left: 0,
                    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 {
                    const imageAscender = metrics.height;
                    glyphOffset = -imageAscender * sectionScale;
                }
                verticalAdvance = metrics.advance;
                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;
            }
        }
        if (positionedGlyphs.length !== 0) {
            const lineLength = x - spacing;
            maxLineLength = Math.max(lineLength, maxLineLength);
            if (hasBaseline) {
                justifyLine(positionedGlyphs, justify, lineOffset, baselineOffset, lineHeight * lineMaxScale / 2);
            } else {
                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);
    shaping.top += -verticalAlign * height;
    shaping.bottom = shaping.top + height;
    shaping.left += -horizontalAlign * maxLineLength;
    shaping.right = shaping.left + maxLineLength;
    shaping.hasBaseline = hasBaseline;
}
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
        ];
    }
    const textLeft = shapedText.left * fontScale;
    const textRight = shapedText.right * fontScale;
    let top, right, bottom, left;
    if (textFit === 'width' || textFit === 'both') {
        left = iconOffset[0] + textLeft - padding[3];
        right = iconOffset[0] + textRight + padding[1];
    } else {
        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') {
        top = iconOffset[1] + textTop - padding[0];
        bottom = iconOffset[1] + textBottom + padding[2];
    } else {
        top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2;
        bottom = top + image.displaySize[1];
    }
    return {
        imagePrimary: image,
        imageSecondary: void 0,
        top,
        right,
        bottom,
        left,
        collisionPadding
    };
}

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

function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) {
    if (anchor.segment === void 0)
        return true;
    let p = anchor;
    let index = anchor.segment + 1;
    let anchorDistance = 0;
    while (anchorDistance > -labelLength / 2) {
        index--;
        if (index < 0)
            return false;
        anchorDistance -= line[index].dist(p);
        p = line[index];
    }
    anchorDistance += line[index].dist(line[index + 1]);
    index++;
    const recentCorners = [];
    let recentAngleDelta = 0;
    while (anchorDistance < labelLength / 2) {
        const prev = line[index - 1];
        const current = line[index];
        const next = line[index + 1];
        if (!next)
            return false;
        let angleDelta = prev.angleTo(current) - current.angleTo(next);
        angleDelta = Math.abs((angleDelta + 3 * Math.PI) % (Math.PI * 2) - Math.PI);
        recentCorners.push({
            distance: anchorDistance,
            angleDelta
        });
        recentAngleDelta += angleDelta;
        while (anchorDistance - recentCorners[0].distance > windowSize) {
            recentAngleDelta -= recentCorners.shift().angleDelta;
        }
        if (recentAngleDelta > maxAngle)
            return false;
        index++;
        anchorDistance += current.dist(next);
    }
    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) {
            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) {
    const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);
    const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon);
    const labelLength = shapedLabelLength * boxScale;
    const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent;
    if (spacing - labelLength < spacing / 4) {
        spacing = labelLength + spacing / 4;
    }
    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);
            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) {
        anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent);
    }
    return anchors;
}

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(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();
            } else if (p1.x < x1) {
                p1 = new Point(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(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();
            } else if (p1.y < y1) {
                p1 = new Point(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(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();
            } else if (p1.x >= x2) {
                p1 = new Point(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(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();
            } else if (p1.y >= y2) {
                p1 = new Point(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 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 ICON_PADDING = 1;
const PATTERN_PADDING = 2;
class ImagePosition {
    static getImagePositionScale(imageIdWithOptions, usvg, pixelRatio) {
        if (usvg && imageIdWithOptions && imageIdWithOptions.options && imageIdWithOptions.options.transform) {
            return {
                x: imageIdWithOptions.options.transform.a,
                y: imageIdWithOptions.options.transform.d
            };
        } else {
            return {
                x: pixelRatio,
                y: pixelRatio
            };
        }
    }
    constructor(paddedRect, {pixelRatio, version, stretchX, stretchY, content, sdf, usvg}, padding, imageIdWithOptions) {
        this.paddedRect = paddedRect;
        this.pixelRatio = pixelRatio;
        this.stretchX = stretchX;
        this.stretchY = stretchY;
        this.content = content;
        this.version = version;
        this.padding = padding;
        this.sdf = sdf;
        this.scale = ImagePosition.getImagePositionScale(imageIdWithOptions, usvg, pixelRatio);
    }
    get tl() {
        return [
            this.paddedRect.x + this.padding,
            this.paddedRect.y + this.padding
        ];
    }
    get br() {
        return [
            this.paddedRect.x + this.paddedRect.w - this.padding,
            this.paddedRect.y + this.paddedRect.h - this.padding
        ];
    }
    get displaySize() {
        return [
            (this.paddedRect.w - this.padding * 2) / this.scale.x,
            (this.paddedRect.h - this.padding * 2) / this.scale.y
        ];
    }
}
class ImageAtlas {
    constructor(icons, patterns, lut) {
        const iconPositions = {}, patternPositions = {};
        this.haveRenderCallbacks = [];
        const bins = [];
        this.addImages(icons, iconPositions, ICON_PADDING, bins);
        this.addImages(patterns, patternPositions, PATTERN_PADDING, 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;
            const overrideRGB = src.sdf;
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x: bin.x + ICON_PADDING,
                y: bin.y + ICON_PADDING
            }, src.data, lut, overrideRGB);
        }
        for (const id in patterns) {
            const src = patterns[id];
            const bin = patternPositions[id].paddedRect;
            let padding = patternPositions[id].padding;
            const x = bin.x + padding, y = bin.y + padding, w2 = src.data.width, h2 = src.data.height;
            padding = padding > 1 ? padding - 1 : padding;
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x,
                y
            }, src.data, lut);
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: h2 - padding
            }, {
                x,
                y: y - padding
            }, {
                width: w2,
                height: padding
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x,
                y: y + h2
            }, {
                width: w2,
                height: padding
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: w2 - padding,
                y: 0
            }, {
                x: x - padding,
                y
            }, {
                width: padding,
                height: h2
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x: x + w2,
                y
            }, {
                width: padding,
                height: h2
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: w2 - padding,
                y: h2 - padding
            }, {
                x: x - padding,
                y: y - padding
            }, {
                width: padding,
                height: padding
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: h2 - padding
            }, {
                x: x + w2,
                y: y - padding
            }, {
                width: padding,
                height: padding
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
            }, {
                x: x + w2,
                y: y + h2
            }, {
                width: padding,
                height: padding
            }, lut);
            RGBAImage.copy(src.data, image, {
                x: w2 - padding,
                y: 0
            }, {
                x: x - padding,
                y: y + h2
            }, {
                width: padding,
                height: padding
            }, lut);
        }
        this.lut = lut;
        this.image = image;
        this.iconPositions = iconPositions;
        this.patternPositions = patternPositions;
    }
    addImages(images, positions, padding, bins) {
        for (const id in images) {
            const src = images[id];
            const bin = {
                x: 0,
                y: 0,
                w: src.data.width + 2 * padding,
                h: src.data.height + 2 * padding
            };
            bins.push(bin);
            const imageIdWithOptions = ImageIdWithOptions.deserializeFromString(id);
            positions[id] = new ImagePosition(bin, src, padding, imageIdWithOptions);
            if (src.hasRenderCallback) {
                this.haveRenderCallbacks.push(imageIdWithOptions.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)) {
            for (const id of Object.keys(this.iconPositions)) {
                if (ImageIdWithOptions.deserializeId(id) === name) {
                    this.patchUpdatedImage(this.iconPositions[id], imageManager.getImage(name, scope), texture);
                }
            }
            for (const id of Object.keys(this.patternPositions)) {
                if (ImageIdWithOptions.deserializeId(id) === name) {
                    this.patchUpdatedImage(this.patternPositions[id], 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;
        const overrideRGBWithWhite = position.sdf;
        if (this.lut || overrideRGBWithWhite) {
            const size = {
                width: image.data.width,
                height: image.data.height
            };
            const imageToUpload = new RGBAImage(size);
            RGBAImage.copy(image.data, imageToUpload, {
                x: 0,
                y: 0
            }, {
                x: 0,
                y: 0
            }, size, this.lut, overrideRGBWithWhite);
            texture.update(imageToUpload, {
                position: {
                    x,
                    y
                }
            });
        } else {
            texture.update(image.data, {
                position: {
                    x,
                    y
                }
            });
        }
    }
}
register(ImagePosition, 'ImagePosition');
register(ImageAtlas, 'ImageAtlas');

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;
    }
}

const SDF_SCALE = 2;
const LocalGlyphMode = {
    none: 0,
    ideographs: 1,
    all: 2
};
class GlyphManager {
    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
            // @ts-expect-error - TS2739 - Type '{}' is missing the following properties from type '{ glyphs: { [id: number]: StyleGlyph; }; ascender: number; descender: number; }': glyphs, ascender, descender
            '200': {},
            // @ts-expect-error - TS2739 - Type '{}' is missing the following properties from type '{ glyphs: { [id: number]: StyleGlyph; }; ascender: number; descender: number; }': glyphs, ascender, descender
            '400': {},
            // @ts-expect-error - TS2739 - Type '{}' is missing the following properties from type '{ glyphs: { [id: number]: StyleGlyph; }; ascender: number; descender: number; }': glyphs, ascender, descender
            '500': {},
            // @ts-expect-error - TS2739 - Type '{}' is missing the following properties from type '{ glyphs: { [id: number]: StyleGlyph; }; ascender: number; descender: number; }': glyphs, ascender, descender
            '900': {}
        };
    }
    setURL(url, scope) {
        this.urls[scope] = url;
    }
    getGlyphs(glyphs, scope, callback) {
        const all = [];
        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: void 0,
                    descender: void 0
                };
            }
            let glyph = entry.glyphs[id];
            if (glyph !== void 0) {
                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) {
                warnOnce('glyphs > 65535 not supported');
                fnCallback(null, {
                    stack,
                    id,
                    glyph
                });
                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 id2 in response.glyphs) {
                            if (!this._doesCharSupportLocalGlyph(+id2)) {
                                entry.glyphs[+id2] = response.glyphs[+id2];
                            }
                        }
                        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, glyphs2) => {
            if (err) {
                callback(err);
            } else if (glyphs2) {
                const result = {};
                for (const {stack, id, glyph} of glyphs2) {
                    if (result[stack] === void 0)
                        result[stack] = {};
                    if (result[stack].glyphs === void 0)
                        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 {
            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
            unicodeBlockLookup['Osage'](id));
        }
    }
    _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);
        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;

const border = ICON_PADDING;
function reduceRanges(sum, range) {
    return sum + range[1] - range[0];
}
function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit, iconScale = 1) {
    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) * iconScale;
    const iconHeight = (shapedIcon.bottom - shapedIcon.top) * iconScale;
    const stretchX = image.stretchX || [[
            0,
            imageWidth
        ]];
    const stretchY = image.stretchY || [[
            0,
            imageHeight
        ]];
    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 * iconScale);
        const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth);
        const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top * iconScale);
        const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight);
        const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left * iconScale);
        const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth);
        const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top * iconScale);
        const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight);
        const tl = new Point(leftEm, topEm);
        const tr = new Point(rightEm, topEm);
        const br = new Point(rightEm, bottomEm);
        const bl = new Point(leftEm, bottomEm);
        const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio);
        const pixelOffsetBR = new Point(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
        } : void 0;
        const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth;
        const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight;
        return {
            tl,
            tr,
            bl,
            br,
            texPrimary: subRect,
            texSecondary: subRectB,
            writingMode: void 0,
            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;
}
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 || {};
            const glyphPadding = 1;
            let rectBuffer = GLYPH_PBF_BORDER + glyphPadding;
            let isSDF = true;
            let pixelRatio = 1;
            let lineOffset = 0;
            if (positionedGlyph.imageName) {
                const image = imageMap[ResolvedImage.build(positionedGlyph.imageName).getSerializedPrimary()];
                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 = ICON_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;
            if (allowVerticalPlacement && shaping.verticalizable) {
                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) {
                    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(x1, y1);
                tr = new Point(x2, y1);
                bl = new Point(x1, y2);
                br = new Point(x2, y2);
            } else {
                const yShift = positionedGlyph.y - currentOffset;
                const center = new Point(-halfAdvance, halfAdvance - yShift);
                const verticalRotation = -Math.PI / 2;
                const verticalOffsetCorrection = new Point(...verticalizedLabelOffset);
                tl = new Point(-halfAdvance + builtInOffset[0], builtInOffset[1]);
                tl._rotateAround(verticalRotation, center)._add(verticalOffsetCorrection);
                tl.x += -yShift + halfAdvance;
                tl.y -= (metrics.left - rectBuffer) * positionedGlyph.scale;
                const verticalAdvance = positionedGlyph.imageName ? metrics.advance * positionedGlyph.scale : ONE_EM * positionedGlyph.scale;
                const chr = String.fromCodePoint(positionedGlyph.glyph);
                if (isVerticalClosePunctuation(chr)) {
                    tl.x += (-rectBuffer + 1) * positionedGlyph.scale;
                } else if (isVerticalOpenPunctuation(chr)) {
                    const xOffset = verticalAdvance - metrics.height * positionedGlyph.scale;
                    tl.x += xOffset + (-rectBuffer - 1) * positionedGlyph.scale;
                } else if (!positionedGlyph.imageName && (metrics.width + rectBuffer * 2 !== rect.w || metrics.height + rectBuffer * 2 !== rect.h)) {
                    const perfectPaddedHeight = (metrics.height + rectBuffer * 2) * positionedGlyph.scale;
                    const delta = verticalAdvance - perfectPaddedHeight;
                    tl.x += delta / 2;
                } else {
                    const delta = verticalAdvance - paddedHeight;
                    tl.x += delta / 2;
                }
                tr = new Point(tl.x, tl.y - paddedWidth);
                bl = new Point(tl.x + paddedHeight, tl.y);
                br = new Point(tl.x + paddedHeight, tl.y - paddedWidth);
            }
            if (textRotate) {
                let center;
                if (!alongLine) {
                    if (useRotateOffset) {
                        center = new Point(rotateOffset[0], rotateOffset[1]);
                    } else {
                        center = new Point(textOffset[0], textOffset[1]);
                    }
                } else {
                    center = new Point(0, 0);
                }
                tl._rotateAround(textRotate, center);
                tr._rotateAround(textRotate, center);
                bl._rotateAround(textRotate, center);
                br._rotateAround(textRotate, center);
            }
            const pixelOffsetTL = new Point(0, 0);
            const pixelOffsetBR = new Point(0, 0);
            const minFontScaleX = 0;
            const minFontScaleY = 0;
            quads.push({
                tl,
                tr,
                bl,
                br,
                texPrimary: textureRect,
                texSecondary: void 0,
                writingMode: shaping.writingMode,
                glyphOffset,
                sectionIndex: positionedGlyph.sectionIndex,
                isSDF,
                pixelOffsetTL,
                pixelOffsetBR,
                minFontScaleX,
                minFontScaleY
            });
        }
    }
    return quads;
}

function findPoleOfInaccessibility (polygonRings, precision = 1, debug = false) {
    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;
    const cellQueue = new TinyQueue([], compareMax);
    if (cellSize === 0)
        return new Point(minX, minY);
    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));
        }
    }
    let bestCell = getCentroidCell(polygonRings);
    let numProbes = cellQueue.length;
    while (cellQueue.length) {
        const cell = cellQueue.pop();
        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);
        }
        if (cell.max - bestCell.d <= precision)
            continue;
        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(x, y);
        this.h = h;
        this.d = pointToPolygonDist(this.p, polygon);
        this.max = this.d + this.h * Math.SQRT2;
    }
}
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);
}
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);
}

const baselineOffset = 7;
const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY;
const sqrt2 = Math.sqrt(2);
const SymbolBucketConstants = {
    // 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
    MAX_GLYPHS: 65535
};
function evaluateVariableOffset(anchor, [offsetX, offsetY]) {
    let x = 0, y = 0;
    if (offsetY === INVALID_TEXT_OFFSET) {
        if (offsetX < 0)
            offsetX = 0;
        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 {
        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, scaleFactor = 1, pixelRatio, 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 = {};
    sizes.scaleFactor = scaleFactor;
    sizes.textSizeScaleRange = layout.get('text-size-scale-range');
    sizes.iconSizeScaleRange = layout.get('icon-size-scale-range');
    const [textSizeScaleRangeMin, textSizeScaleRangeMax] = sizes.textSizeScaleRange;
    const [iconSizeScaleRangeMin, iconSizeScaleRangeMax] = sizes.iconSizeScaleRange;
    sizes.textScaleFactor = clamp(sizes.scaleFactor, textSizeScaleRangeMin, textSizeScaleRangeMax);
    sizes.iconScaleFactor = clamp(sizes.scaleFactor, iconSizeScaleRangeMin, iconSizeScaleRangeMax);
    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) * sizes.textScaleFactor;
        const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, canonical) * sizes.textScaleFactor;
        const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, canonical) * sizes.iconScaleFactor;
        const shapedTextOrientations = {
            horizontal: {},
            vertical: void 0
        };
        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);
                if (radialOffset) {
                    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 = textJustify2 => {
                if (bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) {
                    shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, // @ts-expect-error - TS2345 - Argument of type 'number' is not assignable to parameter of type '2 | 1'.
                    textJustify2, spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom);
                }
            };
            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) {
                        shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0];
                    } else {
                        const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, 'center', // @ts-expect-error - TS2345 - Argument of type 'number' is not assignable to parameter of type '2 | 1'.
                        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);
                }
                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, // @ts-expect-error - TS2345 - Argument of type 'number' is not assignable to parameter of type '2 | 1'.
                    textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);
                    if (shaping)
                        shapedTextOrientations.horizontal[textJustify] = shaping;
                }
                addVerticalShapingIfNeeded(isPointPlacement ? 'left' : textJustify);
            }
        }
        let shapedIcon;
        let isSDFIcon = false;
        if (feature.icon && feature.icon.namePrimary) {
            const iconSizeFactor = getRasterizedIconSize(bucket.iconSizeData, unevaluatedLayoutValues['icon-size'], canonical, bucket.zoom, feature);
            const scaleFactor2 = iconSizeFactor * sizes.iconScaleFactor * pixelRatio;
            const primaryImageSerialized = feature.icon.getPrimary().scaleSelf(scaleFactor2).serialize();
            const image = imageMap[primaryImageSerialized];
            if (image) {
                shapedIcon = shapeIcon(imagePositions[primaryImageSerialized], feature.icon.nameSecondary ? imagePositions[feature.icon.getSecondary().scaleSelf(scaleFactor2).serialize()] : void 0, layout.get('icon-offset').evaluate(feature, {}, canonical), layout.get('icon-anchor').evaluate(feature, {}, canonical));
                isSDFIcon = image.sdf;
                if (bucket.sdfIcons === void 0) {
                    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, sizes.textScaleFactor);
    }
}
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';
}
function tilePixelRatioForSymbolSpacing(overscaleFactor, overscaledZ) {
    if (overscaledZ > 18 && overscaleFactor > 2) {
        overscaleFactor >>= 1;
    }
    const tilePixelRatio = EXTENT / (512 * overscaleFactor);
    return Math.max(tilePixelRatio, 1);
}
function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, availableImages, canonical, projection, brightness, hasAnySecondaryIcon) {
    let textMaxSize = sizes.textMaxSize.evaluate(feature, {}, canonical);
    if (textMaxSize === void 0) {
        textMaxSize = layoutTextSize * sizes.textScaleFactor;
    } else {
        textMaxSize *= sizes.textScaleFactor;
    }
    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 * sizes.textScaleFactor / 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;
    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) {
            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, void 0),
                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') {
        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(feature.geometry, 0)) {
            const poi = findPoleOfInaccessibility(polygon, 16);
            addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0, 0, void 0), canonical);
        }
    } else if (feature.type === 'LineString') {
        for (const line of feature.geometry) {
            addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0, 0, void 0), 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, void 0), 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) * sizes.textScaleFactor];
        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) * sizes.textScaleFactor,
            SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) * sizes.textScaleFactor
        ];
        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);
    for (const placementType of placementTypes) {
        placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1;
    }
    return glyphQuads.length * 4;
}
function getDefaultHorizontalShaping(horizontalShaping) {
    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) {
        const tl = new Point(x1, y1);
        const tr = new Point(x2, y1);
        const bl = new Point(x1, y2);
        const br = new Point(x2, y2);
        const rotateRadians = degToRad(rotate);
        let rotateCenter = new Point(0, 0);
        if (textOffset) {
            rotateCenter = new Point(textOffset[0], textOffset[1]);
        }
        tl._rotateAround(rotateRadians, rotateCenter);
        tr._rotateAround(rotateRadians, rotateCenter);
        bl._rotateAround(rotateRadians, rotateCenter);
        br._rotateAround(rotateRadians, rotateCenter);
        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) {
        shaped.top -= shaped.collisionPadding[1];
        shaped.bottom += shaped.collisionPadding[3];
    }
    const height = shaped.bottom - shaped.top;
    return height > 0 ? Math.max(10, height) : null;
}
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('');
    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') === void 0) {
        [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);
            }
        }
    }
    if (shapedIcon) {
        const sizeData = bucket.iconSizeData;
        const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}, canonical);
        const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit, sizes.iconScaleFactor);
        const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit, sizes.iconScaleFactor) : void 0;
        iconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconPadding, iconRotate, null);
        numIconVertices = iconQuads.length * 4;
        let iconSizeData = null;
        if (sizeData.kind === 'source') {
            iconSizeData = [SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}, canonical) * sizes.iconScaleFactor];
            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) * sizes.iconScaleFactor,
                SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) * sizes.iconScaleFactor
            ];
            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(shaping.text);
            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);
    }
    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 >= SymbolBucketConstants.MAX_GLYPHS)
        warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907');
    if (feature.sortKey !== void 0) {
        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 !== void 0 ? textBoxIndex : bucket.collisionBoxArray.length, textBoxIndex !== void 0 ? textBoxIndex + 1 : bucket.collisionBoxArray.length, verticalTextBoxIndex !== void 0 ? verticalTextBoxIndex : bucket.collisionBoxArray.length, verticalTextBoxIndex !== void 0 ? verticalTextBoxIndex + 1 : bucket.collisionBoxArray.length, iconBoxIndex !== void 0 ? iconBoxIndex : bucket.collisionBoxArray.length, iconBoxIndex !== void 0 ? 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) {
                return true;
            }
        }
    }
    compareText[text].push(anchor);
    return false;
}

function farthestPixelDistanceOnPlane(tr, pixelsPerMeter) {
    const fovAboveCenter = tr.fovAboveCenter;
    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));
    let furthestDistance = Math.sin(tr._pitch) * topHalfSurfaceDistance + cameraToSeaLevelDistance;
    const horizonDistance = cameraToSeaLevelDistance * (1 / tr._horizonShift);
    if (!tr.elevation || tr.elevation.exaggeration() === 0) {
        let factor = Math.max(tr.zoom - 17, 0);
        if (tr.isOrthographic) {
            factor /= 10;
        }
        furthestDistance *= 1 + factor;
    }
    return Math.min(furthestDistance * 1.01, horizonDistance);
}
function farthestPixelDistanceOnSphere(tr, pixelsPerMeter) {
    const cameraDistance = tr.cameraToCenterDistance;
    const centerPixelAltitude = tr._centerAltitude * pixelsPerMeter;
    const camera = tr._camera;
    const forward = tr._camera.forward();
    const cameraPosition = cjsExports.vec3.add([], cjsExports.vec3.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 = cjsExports.vec3.scale([], camera.up(), tanFovAboveCenter);
    const right = cjsExports.vec3.scale([], camera.right(), tanFovAboveCenter * aspectRatio);
    const dir = cjsExports.vec3.normalize([], cjsExports.vec3.add([], cjsExports.vec3.add([], forward, up), right));
    const pointOnGlobe = [];
    const ray = new Ray(cameraPosition, dir);
    let pixelDistance;
    if (ray.closestPointOnSphere(globeCenter, globeRadius, pointOnGlobe)) {
        const p0 = cjsExports.vec3.add([], pointOnGlobe, globeCenter);
        const p1 = cjsExports.vec3.sub([], p0, cameraPosition);
        pixelDistance = Math.cos(tr.fovAboveCenter) * cjsExports.vec3.length(p1);
    } else {
        const globeCenterToCamera = cjsExports.vec3.sub([], cameraPosition, globeCenter);
        const cameraToGlobe = cjsExports.vec3.sub([], globeCenter, cameraPosition);
        cjsExports.vec3.normalize(cameraToGlobe, cameraToGlobe);
        const cameraHeight = cjsExports.vec3.length(globeCenterToCamera) - globeRadius;
        pixelDistance = Math.sqrt(cameraHeight * (cameraHeight + 2 * globeRadius));
        const angle = Math.acos(pixelDistance / (globeRadius + cameraHeight)) - Math.acos(cjsExports.vec3.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);
    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);
    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(tileTransform2, {x, y}, wrap = 0) {
    return new Point(((x - wrap) * tileTransform2.scale - tileTransform2.x) * EXTENT, (y * tileTransform2.scale - tileTransform2.y) * EXTENT);
}
function getTileVec3(tileTransform2, coord, wrap = 0) {
    const x = ((coord.x - wrap) * tileTransform2.scale - tileTransform2.x) * EXTENT;
    const y = (coord.y * tileTransform2.scale - tileTransform2.y) * EXTENT;
    return cjsExports.vec3.fromValues(x, y, altitudeFromMercatorZ(coord.z, coord.y));
}

const identity = cjsExports.mat4.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) {
        return {
            x: 0,
            y: 0,
            z: 0
        };
    }
    unproject(x, y) {
        return new LngLat(0, 0);
    }
    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) {
        return 1;
    }
    farthestPixelDistance(tr) {
        return farthestPixelDistanceOnPlane(tr, tr.pixelsPerMeter);
    }
    pointCoordinate(tr, x, y, z) {
        const horizonOffset = tr.horizonLineFromTop(false);
        const clamped = new Point(x, Math.max(horizonOffset, y));
        return tr.rayIntersectionCoordinate(tr.pointRayIntersection(clamped, z));
    }
    pointCoordinate3D(tr, x, y) {
        const p = new Point(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 && tr.elevation.visibleDemTiles.length) {
            const raycastOnTerrain = this.pointCoordinate3D(tr, p.x, p.y);
            return !raycastOnTerrain;
        }
        const horizon = tr.horizonLineFromTop();
        return p.y < horizon;
    }
    createInversionMatrix(tr, id) {
        return identity;
    }
    createTileMatrix(tr, worldSize, id) {
        let scale, scaledX, scaledY;
        const canonical = id.canonical;
        const posMatrix = cjsExports.mat4.identity(new Float64Array(16));
        if (this.isReprojectedInTileSpace) {
            const cs = tileTransform(canonical, this);
            scale = 1;
            scaledX = cs.x + id.wrap * cs.scale;
            scaledY = cs.y;
            cjsExports.mat4.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;
        }
        cjsExports.mat4.translate(posMatrix, posMatrix, [
            scaledX,
            scaledY,
            0
        ]);
        cjsExports.mat4.scale(posMatrix, posMatrix, [
            scale / EXTENT,
            scale / EXTENT,
            1
        ]);
        return posMatrix;
    }
    upVector(id, x, y) {
        return [
            0,
            0,
            1
        ];
    }
    upVectorScale(id, latitude, worldSize) {
        return { metersToTile: 1 };
    }
}

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(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) {
        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) {
        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(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(lng, lat);
    }
}

const halfPi = Math.PI / 2;
function tany(y) {
    return Math.tan((halfPi + y) / 2);
}
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);
        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(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(lng, lat);
    }
}

const maxPhi$1 = degToRad(MAX_MERCATOR_LATITUDE);
class NaturalEarth extends Projection {
    project(lng, lat) {
        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) {
        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(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) {
        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(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])));
        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(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);
        cjsExports.vec3.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 = cjsExports.vec3.normalize([], pos);
        const elevation = tr.elevation ? tr.elevation.getAtPointOrZero(tr.locationCoordinate(lngLat), tr._centerAltitude) : tr._centerAltitude;
        const upScale = mercatorZfromAltitude(1, 0) * EXTENT * elevation;
        cjsExports.vec3.scaleAndAdd(pos, pos, up, upScale);
        const matrix = cjsExports.mat4.identity(new Float64Array(16));
        cjsExports.mat4.multiply(matrix, tr.pixelMatrix, tr.globeMatrix);
        cjsExports.vec3.transformMat4(pos, pos, matrix);
        return new Point(pos[0], pos[1]);
    }
    pixelsPerMeter(lat, worldSize) {
        return mercatorZfromAltitude(1, 0) * worldSize;
    }
    pixelSpaceConversion(lat, worldSize, interpolationT) {
        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 cjsExports.mat4.multiply(new Float64Array(16), tr.globeMatrix, decode);
    }
    createInversionMatrix(tr, id) {
        const {center} = tr;
        const matrix = globeNormalizeECEF(globeTileBounds(id));
        cjsExports.mat4.rotateY(matrix, matrix, degToRad(center.lng));
        cjsExports.mat4.rotateX(matrix, matrix, degToRad(center.lat));
        cjsExports.mat4.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);
        }
        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));
            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 }`);
}

const vectorTileFeatureTypes = vectorTileExports.VectorTileFeature.types;
const shaderOpacityAttributes = [{
        name: 'a_fade_opacity',
        components: 1,
        type: 'Uint8',
        offset: 0
    }];
function addVertex(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) {
    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.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 StructArrayLayout2ub4f20();
        this.collisionVertexArrayExt = new StructArrayLayout4f16();
    }
    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');
class SymbolBucket {
    constructor(options) {
        this.collisionBoxArray = options.collisionBoxArray;
        this.zoom = options.zoom;
        this.lut = options.lut;
        this.overscaling = options.overscaling;
        this.layers = options.layers;
        this.layerIds = this.layers.map(layer2 => layer2.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 = cjsExports.mat4.identity([]);
        this.placementViewportMatrix = cjsExports.mat4.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) !== void 0;
        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');
        this.activeReplacements = [];
        this.replacementUpdateTime = 0;
    }
    createArrays() {
        this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, {
            zoom: this.zoom,
            lut: this.lut
        }, property => {
            return property.startsWith('text') || property.startsWith('symbol');
        }));
        this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, {
            zoom: this.zoom,
            lut: this.lut
        }, property => {
            return property.startsWith('icon') || property.startsWith('symbol');
        }));
        this.glyphOffsetArray = new GlyphOffsetArray();
        this.lineVertexArray = new SymbolLineVertexArray();
        this.symbolInstances = new SymbolInstanceArray();
    }
    calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) {
        for (const char of text) {
            const codePoint = char.codePointAt(0);
            if (codePoint === void 0)
                break;
            stack[codePoint] = true;
            if (allowVerticalPlacement && doesAllowVerticalWritingMode && codePoint <= 65535) {
                const verticalChar = verticalizedCharacterMap[char];
                if (verticalChar) {
                    stack[verticalChar.charCodeAt(0)] = true;
                }
            }
        }
    }
    updateFootprints(_id, _footprints) {
    }
    updateReplacement(coord, source) {
        if (source.updateTime === this.replacementUpdateTime) {
            return false;
        }
        this.replacementUpdateTime = source.updateTime;
        const newReplacements = source.getReplacementRegionsForTile(coord.toUnwrapped(), true);
        if (regionsEquals(this.activeReplacements, newReplacements)) {
            return false;
        }
        this.activeReplacements = newReplacements;
        return 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 [iconSizeScaleRangeMin, iconSizeScaleRangeMax] = layout.get('icon-size-scale-range');
        const iconScaleFactor = clamp(options.scaleFactor || 1, iconSizeScaleRangeMin, iconSizeScaleRangeMax);
        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);
        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);
            if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {
                continue;
            }
            if (!needGeometry)
                evaluationFeature.geometry = loadGeometry(feature, canonical, tileTransform);
            if (isGlobe && feature.type !== 1 && canonical.z <= 5) {
                const geom = evaluationFeature.geometry;
                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 cjsExports.vec3.dot(v0, v1) < cosAngleThreshold;
                };
                for (let i = 0; i < geom.length; i++) {
                    geom[i] = resamplePred(geom[i], predicate);
                }
            }
            let text;
            if (hasText) {
                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' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping
                    this.hasRTLText && plugin.isParsed()) {
                    text = transformText$1(formattedText, layer, evaluationFeature);
                }
            }
            let icon;
            if (hasIcon) {
                const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages);
                if (resolvedTokens instanceof ResolvedImage) {
                    icon = resolvedTokens;
                } else {
                    icon = ResolvedImage.build(resolvedTokens);
                }
            }
            if (!text && !icon) {
                continue;
            }
            const sortKey = this.sortFeaturesByKey ? symbolSortKey.evaluate(evaluationFeature, {}, canonical) : void 0;
            const symbolFeature = {
                id,
                text,
                icon,
                index,
                sourceLayerIndex,
                geometry: evaluationFeature.geometry,
                properties: feature.properties,
                type: vectorTileFeatureTypes[feature.type],
                sortKey
            };
            this.features.push(symbolFeature);
            if (icon) {
                const layer2 = this.layers[0];
                const unevaluatedLayoutValues = layer2._unevaluatedLayout._values;
                const iconSizeFactor = getRasterizedIconSize(this.iconSizeData, unevaluatedLayoutValues['icon-size'], canonical, this.zoom, symbolFeature);
                const scaleFactor = iconSizeFactor * iconScaleFactor * this.pixelRatio;
                const iconPrimary = icon.getPrimary().scaleSelf(scaleFactor);
                icons[iconPrimary.id] = icons[iconPrimary.id] || [];
                icons[iconPrimary.id].push(iconPrimary);
                if (icon.nameSecondary) {
                    const iconSecondary = icon.getSecondary().scaleSelf(scaleFactor);
                    icons[iconSecondary.id] = icons[iconSecondary.id] || [];
                    icons[iconSecondary.id].push(iconSecondary);
                }
            }
            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 {
                        const imagePrimary = section.image.getPrimary().scaleSelf(this.pixelRatio);
                        icons[imagePrimary.id] = icons[imagePrimary.id] || [];
                        icons[imagePrimary.id].push(imagePrimary);
                    }
                }
            }
        }
        if (layout.get('symbol-placement') === 'line') {
            this.features = mergeLines(this.features);
        }
        if (this.sortFeaturesByKey) {
            this.features.sort((a, b) => {
                return a.sortKey - b.sortKey;
            });
        }
    }
    update(states, vtLayer, availableImages, imagePositions, layers, isBrightnessChanged, brightness) {
        this.text.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, brightness);
        this.icon.programConfigurations.updatePaintArrays(states, vtLayer, layers, availableImages, imagePositions, isBrightnessChanged, brightness);
    }
    updateZOffset() {
        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() {
        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 !== void 0) {
            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 : void 0);
        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(layoutVertexArray, tileAnchor.x, tileAnchor.y, tl.x, y + tl.y, texPrimary.x, texPrimary.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
            addVertex(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(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(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: y2,
                    z
                } = globe.anchor;
                const [ux, uy, uz] = globe.up;
                addGlobeVertex(globeExtVertexArray, x, y2, z, ux, uy, uz);
                addGlobeVertex(globeExtVertexArray, x, y2, z, ux, uy, uz);
                addGlobeVertex(globeExtVertexArray, x, y2, z, ux, uy, uz);
                addGlobeVertex(globeExtVertexArray, x, y2, z, ux, uy, uz);
                addDynamicAttributes(arrays.dynamicLayoutVertexArray, x, y2, z, angle);
            } else {
                addDynamicAttributes(arrays.dynamicLayoutVertexArray, tileAnchor.x, tileAnchor.y, tileAnchor.z, angle);
            }
            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, 0, 0);
        }
        this._commitDebugCollisionVertexUpdate(arrays.collisionVertexArrayExt, scale, box.padding, symbolInstance.zOffset);
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x1, box.y1));
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x2, box.y1));
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x2, box.y2));
        this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(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, textScaleFactor) {
        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, textScaleFactor);
        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, zOffset) {
        array.emplaceBack(scale, -padding, -padding, zOffset);
        array.emplaceBack(scale, padding, -padding, zOffset);
        array.emplaceBack(scale, padding, padding, zOffset);
        array.emplaceBack(scale, -padding, padding, zOffset);
    }
    _updateTextDebugCollisionBoxes(size, zoom, collisionBoxArray, startIndex, endIndex, instance, scaleFactor) {
        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, instance.zOffset);
        }
    }
    _updateIconDebugCollisionBoxes(size, zoom, collisionBoxArray, startIndex, endIndex, instance, iconScaleFactor) {
        for (let b = startIndex; b < endIndex; b++) {
            const box = collisionBoxArray.get(b);
            const scale = this.getSymbolInstanceIconSize(size, zoom, instance.placedIconSymbolIndex);
            const array = this.iconCollisionBox.collisionVertexArrayExt;
            this._commitDebugCollisionVertexUpdate(array, scale, box.padding, instance.zOffset);
        }
    }
    updateCollisionDebugBuffers(zoom, collisionBoxArray, textScaleFactor, iconScaleFactor) {
        if (!this.hasDebugData()) {
            return;
        }
        if (this.hasTextCollisionBoxData())
            this.textCollisionBox.collisionVertexArrayExt.clear();
        if (this.hasIconCollisionBoxData())
            this.iconCollisionBox.collisionVertexArrayExt.clear();
        const iconSize = evaluateSizeForZoom(this.iconSizeData, zoom, iconScaleFactor);
        const textSize = evaluateSizeForZoom(this.textSizeData, zoom, textScaleFactor);
        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, textScaleFactor);
            this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, textScaleFactor);
            this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, iconScaleFactor);
            this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, iconScaleFactor);
        }
        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) {
        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 !== void 0) {
            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;
        if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1)
            return;
        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;
            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'
    ]
});
SymbolBucket.addDynamicAttributes = addDynamicAttributes;

function resolveTokens(properties, text) {
    return text.replace(/{([^{}]+)}/g, (match, key) => {
        return key in properties ? String(properties[key]) : '';
    });
}

let layout$5;
const getLayoutProperties$5 = () => layout$5 || (layout$5 = 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']),
    'symbol-elevation-reference': new DataConstantProperty(spec['layout_symbol']['symbol-elevation-reference']),
    '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-size-scale-range': new DataConstantProperty(spec['layout_symbol']['icon-size-scale-range']),
    '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-size-scale-range': new DataConstantProperty(spec['layout_symbol']['text-size-scale-range']),
    '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'])
}));
let paint$6;
const getPaintProperties$6 = () => paint$6 || (paint$6 = new Properties({
    'icon-opacity': new DataDrivenProperty(spec['paint_symbol']['icon-opacity']),
    'icon-occlusion-opacity': new DataDrivenProperty(spec['paint_symbol']['icon-occlusion-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-occlusion-opacity': new DataDrivenProperty(spec['paint_symbol']['text-occlusion-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']),
    'icon-color-saturation': new DataConstantProperty(spec['paint_symbol']['icon-color-saturation']),
    'icon-color-contrast': new DataConstantProperty(spec['paint_symbol']['icon-color-contrast']),
    'icon-color-brightness-min': new DataConstantProperty(spec['paint_symbol']['icon-color-brightness-min']),
    'icon-color-brightness-max': new DataConstantProperty(spec['paint_symbol']['icon-color-brightness-max']),
    'symbol-z-offset': new DataDrivenProperty(spec['paint_symbol']['symbol-z-offset']),
    'icon-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'icon-halo-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'text-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'text-halo-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

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);
        }
        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'] });

let properties;
const getProperties = () => {
    if (properties) {
        return properties;
    }
    properties = {
        layout: getLayoutProperties$5(),
        paint: getPaintProperties$6()
    };
    return properties;
};
class SymbolStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        super(layer, getProperties(), scope, lut, options);
        this._colorAdjustmentMatrix = cjsExports.mat4.identity([]);
        this.hasInitialOcclusionOpacityProperties = layer.paint !== void 0 && ('icon-occlusion-opacity' in layer.paint || 'text-occlusion-opacity' in layer.paint);
    }
    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 (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) {
            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') {
            this.layout._values['text-writing-mode'] = ['horizontal'];
        } else {
            this.layout._values['text-writing-mode'] = [
                'horizontal',
                'vertical'
            ];
        }
        this._setPaintOverrides();
    }
    getColorAdjustmentMatrix(saturation, contrast, brightnessMin, brightnessMax) {
        if (this._saturation !== saturation || this._contrast !== contrast || this._brightnessMin !== brightnessMin || this._brightnessMax !== brightnessMax) {
            this._colorAdjustmentMatrix = computeColorAdjustmentMatrix(saturation, contrast, brightnessMin, brightnessMax);
            this._saturation = saturation;
            this._contrast = contrast;
            this._brightnessMin = brightnessMin;
            this._brightnessMax = brightnessMax;
        }
        return this._colorAdjustmentMatrix;
    }
    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(parameters);
    }
    queryRadius() {
        return 0;
    }
    queryIntersectsFeature() {
        return false;
    }
    _setPaintOverrides() {
        for (const overridable of getProperties().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, this.scope, this.options);
            let expression = null;
            if (overriden.value.kind === 'constant' || overriden.value.kind === 'source') {
                expression = new ZoomConstantExpression('source', styleExpression);
            } else {
                expression = new ZoomDependentExpression('composite', styleExpression, // @ts-expect-error - TS2339 - Property 'value' does not exist on type 'unknown'.
                overriden.value.zoomStops, // @ts-expect-error - TS2339 - Property 'value' does not exist on type 'unknown'.
                overriden.value._interpolationType);
            }
            this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property, expression, // @ts-expect-error - TS2339 - Property 'parameters' does not exist on type 'unknown'.
            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 = getProperties().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 && 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() {
        return ['symbol'];
    }
    getDefaultProgramParams(name, zoom, lut) {
        return {
            config: new ProgramConfiguration(this, {
                zoom,
                lut
            }),
            overrideFog: false
        };
    }
}

let layout$4;
const getLayoutProperties$4 = () => layout$4 || (layout$4 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_background']['visibility']) }));
let paint$5;
const getPaintProperties$5 = () => paint$5 || (paint$5 = new Properties({
    'background-pitch-alignment': new DataConstantProperty(spec['paint_background']['background-pitch-alignment']),
    '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']),
    'background-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

class BackgroundStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$4(),
            paint: getPaintProperties$5()
        };
        super(layer, properties, scope, lut, options);
    }
    getProgramIds() {
        const image = this.paint.get('background-pattern');
        return [image ? 'backgroundPattern' : 'background'];
    }
    getDefaultProgramParams(name, zoom, lut) {
        return { overrideFog: false };
    }
    is3D() {
        return this.paint.get('background-pitch-alignment') === 'viewport';
    }
}

let layout$3;
const getLayoutProperties$3 = () => layout$3 || (layout$3 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_raster']['visibility']) }));
let paint$4;
const getPaintProperties$4 = () => paint$4 || (paint$4 = 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']),
    'raster-emissive-strength': new DataConstantProperty(spec['paint_raster']['raster-emissive-strength']),
    'raster-array-band': new DataConstantProperty(spec['paint_raster']['raster-array-band']),
    'raster-elevation': new DataConstantProperty(spec['paint_raster']['raster-elevation']),
    'raster-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

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

function _getLegacyFormat(format) {
    switch (format) {
    case WebGL2RenderingContext['RGBA8']:
        return WebGL2RenderingContext['RGBA'];
    case WebGL2RenderingContext['DEPTH_COMPONENT16']:
        return WebGL2RenderingContext['DEPTH_COMPONENT'];
    case WebGL2RenderingContext['DEPTH24_STENCIL8']:
        return WebGL2RenderingContext['DEPTH_STENCIL'];
    case WebGL2RenderingContext['R8']:
        return WebGL2RenderingContext['RED'];
    case WebGL2RenderingContext['R32F']:
        return WebGL2RenderingContext['RED'];
    }
}
function _getType(format) {
    switch (format) {
    case WebGL2RenderingContext['RGBA8']:
        return WebGL2RenderingContext['UNSIGNED_BYTE'];
    case WebGL2RenderingContext['DEPTH_COMPONENT16']:
        return WebGL2RenderingContext['UNSIGNED_SHORT'];
    case WebGL2RenderingContext['DEPTH24_STENCIL8']:
        return WebGL2RenderingContext['UNSIGNED_INT_24_8'];
    case WebGL2RenderingContext['R8']:
        return WebGL2RenderingContext['UNSIGNED_BYTE'];
    case WebGL2RenderingContext['R32F']:
        return WebGL2RenderingContext['FLOAT'];
    }
}
class Texture {
    constructor(context, image, format, options) {
        this.context = context;
        this.format = format;
        this.useMipmap = options && options.useMipmap;
        this.texture = context.gl.createTexture();
        this.update(image, { premultiply: options && options.premultiply });
    }
    update(image, options) {
        const srcWidth = image && image instanceof HTMLVideoElement && image.width === 0 ? image.videoWidth : image.width;
        const srcHeight = image && image instanceof HTMLVideoElement && image.height === 0 ? image.videoHeight : image.height;
        const {context} = this;
        const {gl} = context;
        const {x, y} = options && options.position ? options.position : {
            x: 0,
            y: 0
        };
        const width = x + srcWidth;
        const height = y + srcHeight;
        if (this.size && (this.size[0] !== width || this.size[1] !== height)) {
            gl.bindTexture(gl.TEXTURE_2D, null);
            gl.deleteTexture(this.texture);
            this.texture = gl.createTexture();
            this.size = null;
        }
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        context.pixelStoreUnpackFlipY.set(false);
        context.pixelStoreUnpack.set(1);
        context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA8 && (!options || options.premultiply !== false));
        const externalImage = image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || ImageBitmap && image instanceof ImageBitmap;
        if (!this.size && width > 0 && height > 0) {
            const numLevels = this.useMipmap ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1;
            gl.texStorage2D(gl.TEXTURE_2D, numLevels, this.format, width, height);
            this.size = [
                width,
                height
            ];
        }
        if (this.size) {
            if (externalImage) {
                gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, _getLegacyFormat(this.format), _getType(this.format), image);
            } else {
                const pixels = image.data;
                if (pixels) {
                    gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, srcWidth, srcHeight, _getLegacyFormat(this.format), _getType(this.format), pixels);
                }
            }
        }
        if (this.useMipmap) {
            gl.generateMipmap(gl.TEXTURE_2D);
        }
    }
    bind(filter, wrap, ignoreMipMap = false) {
        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 && !ignoreMipMap ? filter === gl.NEAREST ? gl.NEAREST_MIPMAP_NEAREST : gl.LINEAR_MIPMAP_LINEAR : 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_LINEAR : 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 Texture3D {
    constructor(context, image, size, format) {
        this.context = context;
        this.format = format;
        this.size = size;
        this.texture = context.gl.createTexture();
        const [width, height, depth] = this.size;
        const {gl} = context;
        gl.bindTexture(gl.TEXTURE_3D, this.texture);
        context.pixelStoreUnpackFlipY.set(false);
        context.pixelStoreUnpack.set(1);
        context.pixelStoreUnpackPremultiplyAlpha.set(false);
        gl.texImage3D(gl.TEXTURE_3D, 0, this.format, width, height, depth, 0, _getLegacyFormat(this.format), _getType(this.format), image.data);
    }
    bind(filter, wrap) {
        const {context} = this;
        const {gl} = context;
        gl.bindTexture(gl.TEXTURE_3D, this.texture);
        if (filter !== this.minFilter) {
            gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, filter);
            gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, filter);
            this.minFilter = filter;
        }
        if (wrap !== this.wrapS) {
            gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, wrap);
            gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, wrap);
            this.wrapS = wrap;
        }
    }
    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;
        }
    }
}

function basisToPoints(x1, y1, x2, y2, x3, y3, x4, y4) {
    const m = [
        x1,
        y1,
        1,
        x2,
        y2,
        1,
        x3,
        y3,
        1
    ];
    const s = [
        x4,
        y4,
        1
    ];
    const ma = cjsExports.mat3.adjoint([], m);
    const [sx, sy, sz] = cjsExports.vec3.transformMat3(s, s, ma);
    return cjsExports.mat3.multiply(m, m, [
        sx,
        0,
        0,
        0,
        sy,
        0,
        0,
        0,
        sz
    ]);
}
function getTileToTextureTransformMatrix(x1, y1, x2, y2, x3, y3, x4, y4) {
    const a = basisToPoints(0, 0, 1, 0, 1, 1, 0, 1);
    const b = basisToPoints(x1, y1, x2, y2, x3, y3, x4, y4);
    const adjB = cjsExports.mat3.adjoint([], b);
    return cjsExports.mat3.multiply(a, a, adjB);
}
function getTextureToTileTransformMatrix(x1, y1, x2, y2, x3, y3, x4, y4) {
    const a = basisToPoints(0, 0, 1, 0, 1, 1, 0, 1);
    const b = basisToPoints(x1, y1, x2, y2, x3, y3, x4, y4);
    const adjA = cjsExports.mat3.adjoint([], a);
    return cjsExports.mat3.multiply(b, b, adjA);
}
function getPerspectiveTransform(x1, y1, x2, y2, x3, y3, x4, y4) {
    const m = getTextureToTileTransformMatrix(x1, y1, x2, y2, x3, y3, x4, y4);
    return [
        m[2] / m[8] / EXTENT,
        m[5] / m[8] / EXTENT
    ];
}
function isConvex(coords) {
    const dx1 = coords[1].x - coords[0].x;
    const dy1 = coords[1].y - coords[0].y;
    const dx2 = coords[2].x - coords[1].x;
    const dy2 = coords[2].y - coords[1].y;
    const dx3 = coords[3].x - coords[2].x;
    const dy3 = coords[3].y - coords[2].y;
    const dx4 = coords[0].x - coords[3].x;
    const dy4 = coords[0].y - coords[3].y;
    const crossProduct1 = dx1 * dy2 - dx2 * dy1;
    const crossProduct2 = dx2 * dy3 - dx3 * dy2;
    const crossProduct3 = dx3 * dy4 - dx4 * dy3;
    const crossProduct4 = dx4 * dy1 - dx1 * dy4;
    return crossProduct1 > 0 && crossProduct2 > 0 && crossProduct3 > 0 && crossProduct4 > 0 || crossProduct1 < 0 && crossProduct2 < 0 && crossProduct3 < 0 && crossProduct4 < 0;
}
function constrainCoordinates(coords) {
    return [
        coords[0],
        Math.min(Math.max(coords[1], -MAX_MERCATOR_LATITUDE), MAX_MERCATOR_LATITUDE)
    ];
}
function constrain(coords) {
    return [
        constrainCoordinates(coords[0]),
        constrainCoordinates(coords[1]),
        constrainCoordinates(coords[2]),
        constrainCoordinates(coords[3])
    ];
}
function calculateMinAndSize(coords) {
    let minX = coords[0][0];
    let maxX = minX;
    let minY = coords[0][1];
    let maxY = minY;
    for (let i = 1; i < coords.length; i++) {
        if (coords[i][0] < minX) {
            minX = coords[i][0];
        } else if (coords[i][0] > maxX) {
            maxX = coords[i][0];
        }
        if (coords[i][1] < minY) {
            minY = coords[i][1];
        } else if (coords[i][1] > maxY) {
            maxY = coords[i][1];
        }
    }
    return [
        minX,
        minY,
        maxX - minX,
        maxY - minY
    ];
}
function calculateMinAndSizeForPoints(coords) {
    let minX = coords[0].x;
    let maxX = minX;
    let minY = coords[0].y;
    let maxY = minY;
    for (let i = 1; i < coords.length; i++) {
        if (coords[i].x < minX) {
            minX = coords[i].x;
        } else if (coords[i].x > maxX) {
            maxX = coords[i].x;
        }
        if (coords[i].y < minY) {
            minY = coords[i].y;
        } else if (coords[i].y > maxY) {
            maxY = coords[i].y;
        }
    }
    return [
        minX,
        minY,
        maxX - minX,
        maxY - minY
    ];
}
function sortTriangles(centerLatitudes, indices) {
    const triangleCount = centerLatitudes.length;
    const triangleIndexes = Array.from({ length: triangleCount }, (v, i) => i);
    triangleIndexes.sort((idx1, idx2) => {
        return centerLatitudes[idx1] - centerLatitudes[idx2];
    });
    const sortedCenterLatitudes = [];
    const sortedIndices = new StructArrayLayout3ui6();
    for (let i = 0; i < triangleIndexes.length; i++) {
        const idx = triangleIndexes[i];
        sortedCenterLatitudes.push(centerLatitudes[idx]);
        const i0 = idx * 3;
        const i1 = i0 + 1;
        const i2 = i1 + 1;
        sortedIndices.emplaceBack(indices.uint16[i0], indices.uint16[i1], indices.uint16[i2]);
    }
    return [
        sortedCenterLatitudes,
        sortedIndices
    ];
}
class ImageSource extends Evented {
    /**
   * @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) {
                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 (!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'
            }));
        }
    }
    onAdd(map) {
        this.map = map;
        this.load();
    }
    onRemove(_) {
        if (this._imageRequest) {
            this._imageRequest.cancel();
            this._imageRequest = null;
        }
        if (this.texture && !(this.texture instanceof UserManagedTexture))
            this.texture.destroy();
        if (this.boundsBuffer) {
            this.boundsBuffer.destroy();
            if (this.elevatedGlobeVertexBuffer) {
                this.elevatedGlobeVertexBuffer.destroy();
            }
            if (this.elevatedGlobeIndexBuffer) {
                this.elevatedGlobeIndexBuffer.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 = void 0;
        this._unsupportedCoords = false;
        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) {
            const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat);
            this.tileID = getCoordinatesCenterTileID(cornerCoords);
            this.minzoom = this.maxzoom = this.tileID.z;
        }
        this.fire(new Event('data', {
            dataType: 'source',
            sourceDataType: 'content'
        }));
        return this;
    }
    _clear() {
        this._boundsArray = void 0;
        this._unsupportedCoords = false;
    }
    _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 || this.onNorthPole || this.onSouthPole || this._unsupportedCoords)
            return;
        const globalTileTr = tileTransform(new CanonicalTileID(0, 0, 0), this.map.transform.projection);
        const globalTileCoords = [
            globalTileTr.projection.project(this.coordinates[0][0], this.coordinates[0][1]),
            globalTileTr.projection.project(this.coordinates[1][0], this.coordinates[1][1]),
            globalTileTr.projection.project(this.coordinates[2][0], this.coordinates[2][1]),
            globalTileTr.projection.project(this.coordinates[3][0], this.coordinates[3][1])
        ];
        if (!isConvex(globalTileCoords)) {
            console.warn('Image source coordinates are defining non-convex area in the Mercator projection');
            this._unsupportedCoords = true;
            return;
        }
        const tileTr = tileTransform(this.tileID, this.map.transform.projection);
        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(tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.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();
            if (this.elevatedGlobeVertexBuffer) {
                this.elevatedGlobeVertexBuffer.destroy();
            }
            if (this.elevatedGlobeIndexBuffer) {
                this.elevatedGlobeIndexBuffer.destroy();
            }
        }
        this.boundsBuffer = context.createVertexBuffer(boundsArray, boundsAttributes.members);
        this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
        const cellCount = GLOBE_VERTEX_GRID_SIZE;
        const lineSize = cellCount + 1;
        const linesCount = cellCount + 1;
        const vertexCount = lineSize * linesCount;
        const triangleCount = cellCount * cellCount * 2;
        const verticesLongitudes = [];
        const constrainedCoordinates = constrain(this.coordinates);
        const [minLng, minLat, lngDiff, latDiff] = calculateMinAndSize(constrainedCoordinates);
        {
            const elevatedGlobeVertexArray = new StructArrayLayout4i8();
            const [minX, minY, dx, dy] = calculateMinAndSizeForPoints(globalTileCoords);
            const transformToImagePoint = coord => {
                return [
                    (coord.x - minX) / dx,
                    (coord.y - minY) / dy
                ];
            };
            const [p0, p1, p2, p3] = globalTileCoords.map(transformToImagePoint);
            const toUV = getTileToTextureTransformMatrix(p0[0], p0[1], p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
            this.elevatedGlobePerspectiveTransform = getPerspectiveTransform(p0[0], p0[1], p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
            const addVertex = (point, tilePoint) => {
                verticesLongitudes.push(point.lng);
                const x = Math.round((point.lng - minLng) / lngDiff * EXTENT);
                const y = Math.round((point.lat - minLat) / latDiff * EXTENT);
                const imagePoint = transformToImagePoint(tilePoint);
                const uv = cjsExports.vec3.transformMat3([], [
                    imagePoint[0],
                    imagePoint[1],
                    1
                ], toUV);
                const u = Math.round(uv[0] / uv[2] * EXTENT);
                const v = Math.round(uv[1] / uv[2] * EXTENT);
                elevatedGlobeVertexArray.emplaceBack(x, y, u, v);
            };
            const leftDx = globalTileCoords[3].x - globalTileCoords[0].x;
            const leftDy = globalTileCoords[3].y - globalTileCoords[0].y;
            const rightDx = globalTileCoords[2].x - globalTileCoords[1].x;
            const rightDy = globalTileCoords[2].y - globalTileCoords[1].y;
            for (let i = 0; i < linesCount; i++) {
                const linesPart = i / cellCount;
                const startLinePoint = [
                    globalTileCoords[0].x + linesPart * leftDx,
                    globalTileCoords[0].y + linesPart * leftDy
                ];
                const endLinePoint = [
                    globalTileCoords[1].x + linesPart * rightDx,
                    globalTileCoords[1].y + linesPart * rightDy
                ];
                const lineDx = endLinePoint[0] - startLinePoint[0];
                const lineDy = endLinePoint[1] - startLinePoint[1];
                for (let j = 0; j < lineSize; j++) {
                    const linePart = j / cellCount;
                    const point = {
                        x: startLinePoint[0] + lineDx * linePart,
                        y: startLinePoint[1] + lineDy * linePart,
                        z: 0
                    };
                    addVertex(globalTileTr.projection.unproject(point.x, point.y), point);
                }
            }
            this.elevatedGlobeVertexBuffer = context.createVertexBuffer(elevatedGlobeVertexArray, boundsAttributes.members);
        }
        {
            this.maxLongitudeTriangleSize = 0;
            let elevatedGlobeTrianglesCenterLongitudes = [];
            let indices = new StructArrayLayout3ui6();
            const processTriangle = (i0, i1, i2) => {
                indices.emplaceBack(i0, i1, i2);
                const l0 = verticesLongitudes[i0];
                const l1 = verticesLongitudes[i1];
                const l2 = verticesLongitudes[i2];
                const minLongitude = Math.min(Math.min(l0, l1), l2);
                const maxLongitude = Math.max(Math.max(l0, l1), l2);
                const diff = maxLongitude - minLongitude;
                if (diff > this.maxLongitudeTriangleSize) {
                    this.maxLongitudeTriangleSize = diff;
                }
                elevatedGlobeTrianglesCenterLongitudes.push(minLongitude + diff / 2);
            };
            for (let i = 0; i < cellCount; i++) {
                for (let j = 0; j < cellCount; j++) {
                    const i0 = i * lineSize + j;
                    const i1 = i0 + 1;
                    const i2 = i0 + lineSize;
                    const i3 = i2 + 1;
                    processTriangle(i0, i2, i1);
                    processTriangle(i1, i2, i3);
                }
            }
            [elevatedGlobeTrianglesCenterLongitudes, indices] = sortTriangles(elevatedGlobeTrianglesCenterLongitudes, indices);
            this.elevatedGlobeTrianglesCenterLongitudes = elevatedGlobeTrianglesCenterLongitudes;
            this.elevatedGlobeIndexBuffer = context.createIndexBuffer(indices);
        }
        this.elevatedGlobeSegments = SegmentVector.simpleSegment(0, 0, vertexCount, triangleCount);
        this.elevatedGlobeGridMatrix = new Float32Array([
            0,
            lngDiff / EXTENT,
            0,
            latDiff / EXTENT,
            0,
            0,
            minLat,
            minLng,
            0
        ]);
    }
    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.RGBA8);
                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) {
        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;
    }
    getSegmentsForLongitude(longitude) {
        const segments = this.elevatedGlobeSegments;
        if (!this.elevatedGlobeTrianglesCenterLongitudes || !segments) {
            return null;
        }
        const longitudes = this.elevatedGlobeTrianglesCenterLongitudes;
        const normalizeLongitudeTo = (longitude2, desiredLongitude) => {
            const diff = Math.round((desiredLongitude - longitude2) / 360);
            return longitude2 + diff * 360;
        };
        let gapLongitude = normalizeLongitudeTo(longitude + 180, longitudes[0]);
        const ret = new SegmentVector();
        const addTriangleRange = (triangleOffset, triangleCount) => {
            ret.segments.push({
                vertexOffset: 0,
                primitiveOffset: triangleOffset,
                vertexLength: segments.segments[0].vertexLength,
                primitiveLength: triangleCount,
                sortKey: void 0,
                vaos: {}
            });
        };
        const distanceToDrop = 0.51 * this.maxLongitudeTriangleSize;
        if (Math.abs(longitudes[0] - gapLongitude) <= distanceToDrop) {
            const minIdx2 = upperBound(longitudes, 0, longitudes.length, gapLongitude + distanceToDrop);
            if (minIdx2 === longitudes.length) {
                return ret;
            }
            const maxIdx2 = lowerBound(longitudes, minIdx2 + 1, longitudes.length, gapLongitude + 360 - distanceToDrop);
            const count = maxIdx2 - minIdx2;
            addTriangleRange(minIdx2, count);
            return ret;
        }
        if (gapLongitude < longitudes[0]) {
            gapLongitude += 360;
        }
        const minIdx = lowerBound(longitudes, 0, longitudes.length, gapLongitude - distanceToDrop);
        if (minIdx === longitudes.length) {
            addTriangleRange(0, longitudes.length);
            return ret;
        }
        addTriangleRange(0, minIdx - 0);
        const maxIdx = upperBound(longitudes, minIdx + 1, longitudes.length, gapLongitude + distanceToDrop);
        if (maxIdx !== longitudes.length) {
            addTriangleRange(maxIdx, longitudes.length - maxIdx);
        }
        return ret;
    }
}
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);
    let x = Math.floor((minX + maxX) / 2 * tilesAtZoom);
    if (x > 1) {
        x -= 1;
    }
    return new CanonicalTileID(zoom, x, Math.floor((minY + maxY) / 2 * tilesAtZoom));
}

const COLOR_RAMP_RES$1 = 256;
const COLOR_MIX_FACTOR = (Math.pow(COLOR_RAMP_RES$1, 2) - 1) / (255 * COLOR_RAMP_RES$1 * (COLOR_RAMP_RES$1 + 3));
class RasterStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$3(),
            paint: getPaintProperties$4()
        };
        super(layer, properties, scope, lut, options);
        this.updateColorRamp();
        this._curRampRange = [
            NaN,
            NaN
        ];
    }
    getProgramIds() {
        return ['raster'];
    }
    hasColorMap() {
        const expr = this._transitionablePaint._values['raster-color'].value;
        return !!expr.value;
    }
    tileCoverLift() {
        return this.paint.get('raster-elevation');
    }
    isDraped(sourceCache) {
        if (sourceCache && sourceCache._source instanceof ImageSource) {
            if (sourceCache._source.onNorthPole || sourceCache._source.onSouthPole) {
                return false;
            }
        }
        return this.paint.get('raster-elevation') === 0;
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'raster-color' || name === 'raster-color-range') {
            this._curRampRange = [
                NaN,
                NaN
            ];
            this.updateColorRamp();
        }
    }
    updateColorRamp(overrideRange) {
        if (!this.hasColorMap())
            return;
        if (!this._curRampRange)
            return;
        const expression = this._transitionablePaint._values['raster-color'].value.expression;
        const [start, end] = overrideRange || this._transitionablePaint._values['raster-color-range'].value.expression.evaluate({ zoom: 0 }) || [
            NaN,
            NaN
        ];
        if (isNaN(start) && isNaN(end))
            return;
        if (start === this._curRampRange[0] && end === this._curRampRange[1])
            return;
        this.colorRamp = renderColorRamp({
            expression,
            evaluationKey: 'rasterValue',
            image: this.colorRamp,
            clips: [{
                    start,
                    end
                }],
            resolution: COLOR_RAMP_RES$1
        });
        this.colorRampTexture = null;
        this._curRampRange = [
            start,
            end
        ];
    }
}

let layout$2;
const getLayoutProperties$2 = () => layout$2 || (layout$2 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_raster-particle']['visibility']) }));
let paint$3;
const getPaintProperties$3 = () => paint$3 || (paint$3 = new Properties({
    'raster-particle-array-band': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-array-band']),
    'raster-particle-count': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-count']),
    'raster-particle-color': new ColorRampProperty(spec['paint_raster-particle']['raster-particle-color']),
    'raster-particle-max-speed': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-max-speed']),
    'raster-particle-speed-factor': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-speed-factor']),
    'raster-particle-fade-opacity-factor': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-fade-opacity-factor']),
    'raster-particle-reset-rate-factor': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-reset-rate-factor']),
    'raster-particle-elevation': new DataConstantProperty(spec['paint_raster-particle']['raster-particle-elevation']),
    'raster-particle-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

const COLOR_RAMP_RES = 256;
class RasterParticleStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$2(),
            paint: getPaintProperties$3()
        };
        super(layer, properties, scope, lut, options);
        this._updateColorRamp();
        this.lastInvalidatedAt = exported$1.now();
    }
    onRemove(_) {
        if (this.colorRampTexture) {
            this.colorRampTexture.destroy();
        }
        if (this.tileFramebuffer) {
            this.tileFramebuffer.destroy();
        }
        if (this.particleFramebuffer) {
            this.particleFramebuffer.destroy();
        }
    }
    hasColorMap() {
        const expr = this._transitionablePaint._values['raster-particle-color'].value;
        return !!expr.value;
    }
    getProgramIds() {
        return ['rasterParticle'];
    }
    hasOffscreenPass() {
        return this.visibility !== 'none';
    }
    isDraped(_) {
        return false;
    }
    _handleSpecialPaintPropertyUpdate(name) {
        if (name === 'raster-particle-color' || name === 'raster-particle-max-speed') {
            this._updateColorRamp();
            this._invalidateAnimationState();
        }
        if (name === 'raster-particle-count') {
            this._invalidateAnimationState();
        }
    }
    _updateColorRamp() {
        if (!this.hasColorMap())
            return;
        const expression = this._transitionablePaint._values['raster-particle-color'].value.expression;
        const end = this._transitionablePaint._values['raster-particle-max-speed'].value.expression.evaluate({ zoom: 0 });
        this.colorRamp = renderColorRamp({
            expression,
            evaluationKey: 'rasterParticleSpeed',
            image: this.colorRamp,
            clips: [{
                    start: 0,
                    end
                }],
            resolution: COLOR_RAMP_RES
        });
        this.colorRampTexture = null;
    }
    _invalidateAnimationState() {
        this.lastInvalidatedAt = exported$1.now();
    }
    tileCoverLift() {
        return this.paint.get('raster-particle-elevation');
    }
}

function validateCustomStyleLayer(layerObject) {
    const errors = [];
    const id = layerObject.id;
    if (id === void 0) {
        errors.push({ message: `layers.${ id }: missing required property "id"` });
    }
    if (layerObject.render === void 0) {
        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, scope) {
        super(implementation, {}, scope, null);
        this.implementation = implementation;
        if (implementation.slot)
            this.slot = implementation.slot;
    }
    is3D() {
        return this.implementation.renderingMode === '3d';
    }
    hasOffscreenPass() {
        return this.implementation.prerender !== void 0;
    }
    isDraped(_) {
        return this.implementation.renderToTile !== void 0;
    }
    shouldRedrape() {
        return !!this.implementation.shouldRerenderTiles && this.implementation.shouldRerenderTiles();
    }
    recalculate() {
    }
    updateTransitions() {
    }
    hasTransition() {
        return false;
    }
    serialize() {
    }
    onAdd(map) {
        if (this.implementation.onAdd) {
            this.implementation.onAdd(map, map.painter.context.gl);
        }
    }
    onRemove(map) {
        if (this.implementation.onRemove) {
            this.implementation.onRemove(map, map.painter.context.gl);
        }
    }
}

let layout$1;
const getLayoutProperties$1 = () => layout$1 || (layout$1 = new Properties({ 'visibility': new DataConstantProperty(spec['layout_sky']['visibility']) }));
let paint$2;
const getPaintProperties$2 = () => paint$2 || (paint$2 = 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']),
    'sky-gradient-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'sky-atmosphere-halo-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    }),
    'sky-atmosphere-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

function getCelestialDirection(azimuth, altitude, leftHanded) {
    const up = [
        0,
        0,
        1
    ];
    const rotation = cjsExports.quat.identity([]);
    cjsExports.quat.rotateY(rotation, rotation, leftHanded ? -degToRad(azimuth) + Math.PI : degToRad(azimuth));
    cjsExports.quat.rotateX(rotation, rotation, -degToRad(altitude));
    cjsExports.vec3.transformQuat(up, up, rotation);
    return cjsExports.vec3.normalize(up, up);
}
class SkyLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties$1(),
            paint: getPaintProperties$2()
        };
        super(layer, properties, scope, lut, 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;
    }
}

let paint$1;
const getPaintProperties$1 = () => paint$1 || (paint$1 = new Properties({}));

class SlotStyleLayer extends StyleLayer {
    constructor(layer, scope, _lut, _) {
        const properties = { paint: getPaintProperties$1() };
        super(layer, properties, scope, null);
    }
}

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);
    cjsExports.mat4.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.convert(projection.center));
    const scaleAdjustment = Math.pow(2, zoomAdjustment * interpT + (1 - interpT) * zoomAdjustmentOrigin);
    return scaleAdjustment;
}
function getProjectionAdjustmentInverted(transform) {
    const m = getProjectionAdjustments(transform, true);
    return cjsExports.mat2.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));
    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;
}
const offset = 1 / 40000;
function getZoomAdjustment(projection, loc) {
    const lat = clamp(loc.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);
    const loc1 = new LngLat(loc.lng - 180 * offset, lat);
    const loc2 = new LngLat(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) {
    const locw = new LngLat(loc.lng - 180 * offset, loc.lat);
    const loce = new LngLat(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;
    const angleAdjust = -Math.atan2(pdy, pdx);
    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);
    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 = cjsExports.mat4.identity([]);
    cjsExports.mat4.rotateZ(unrotate, unrotate, -angleAdjust * (1 - (withoutRotation ? 0 : interpT)));
    const shear = cjsExports.mat4.identity([]);
    cjsExports.mat4.scale(shear, shear, [
        1,
        1 - (1 - scale) * interpT,
        1
    ]);
    shear[4] = -delta4.x / delta4.y * interpT;
    cjsExports.mat4.rotateZ(shear, shear, angleAdjust);
    cjsExports.mat4.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
    };
}

function rotationScaleYZFlipMatrix(out, rotation, scale) {
    cjsExports.mat4.identity(out);
    cjsExports.mat4.rotateZ(out, out, degToRad(rotation[2]));
    cjsExports.mat4.rotateX(out, out, degToRad(rotation[0]));
    cjsExports.mat4.rotateY(out, out, degToRad(rotation[1]));
    cjsExports.mat4.scale(out, out, scale);
    const coordSpaceTransform = [
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1
    ];
    cjsExports.mat4.multiply(out, out, coordSpaceTransform);
}
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 = cjsExports.vec3.cross(a, a, b);
        cjsExports.vec3.normalize(normal, normal);
        face.dotProductWithUp = cjsExports.vec3.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 (cjsExports.vec3.length(p0p1) < 1e-12 || cjsExports.vec3.length(p0p2) < 1e-12) {
        return cjsExports.quat.identity(out);
    }
    const from = cjsExports.vec3.cross([], p0p1, p0p2);
    cjsExports.vec3.normalize(from, from);
    cjsExports.vec3.subtract(p0p2, p2, p0);
    p0p1[2] = (h1 - h0) * meterToMercator;
    p0p2[2] = (h2 - h0) * meterToMercator;
    const to = p0p1;
    cjsExports.vec3.cross(to, p0p1, p0p2);
    cjsExports.vec3.normalize(to, to);
    return cjsExports.quat.rotationTo(out, from, to);
}
function coordinateFrameAtEcef(ecef) {
    const zAxis = [
        ecef[0],
        ecef[1],
        ecef[2]
    ];
    let yAxis = [
        0,
        1,
        0
    ];
    const xAxis = cjsExports.vec3.cross([], yAxis, zAxis);
    cjsExports.vec3.cross(yAxis, zAxis, xAxis);
    if (cjsExports.vec3.squaredLength(yAxis) === 0) {
        yAxis = [
            0,
            1,
            0
        ];
        cjsExports.vec3.cross(xAxis, zAxis, yAxis);
    }
    cjsExports.vec3.normalize(xAxis, xAxis);
    cjsExports.vec3.normalize(yAxis, yAxis);
    cjsExports.vec3.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) {
    const worldSize = transform.worldSize;
    const position = [
        matrix[12],
        matrix[13],
        matrix[14]
    ];
    const lat = latFromMercatorY(position[1] / worldSize);
    const lng = lngFromMercatorX(position[0] / worldSize);
    const mercToEcef = cjsExports.mat4.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) {
        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;
    }
    const ecefCoord = latLngToECEF(lat, lng);
    cjsExports.vec3.add(ecefCoord, ecefCoord, cjsExports.vec3.scale([], cjsExports.vec3.normalize([], ecefCoord), sourcePixelsPerMeter * scale * position[2]));
    const ecefFrame = coordinateFrameAtEcef(ecefCoord);
    cjsExports.mat4.scale(mercToEcef, mercToEcef, [
        scale,
        scale,
        scale * sourcePixelsPerMeter
    ]);
    cjsExports.mat4.translate(mercToEcef, mercToEcef, [
        -position[0],
        -position[1],
        -position[2]
    ]);
    const result = cjsExports.mat4.multiply([], transform.globeMatrix, ecefFrame);
    cjsExports.mat4.multiply(result, result, mercToEcef);
    cjsExports.mat4.multiply(result, result, matrix);
    return result;
}
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 = cjsExports.mat4.identity([]);
    cjsExports.mat4.rotateY(m, m, degToRad(transform.center.lng));
    cjsExports.mat4.rotateX(m, m, degToRad(transform.center.lat));
    cjsExports.mat4.translate(m, m, [
        0,
        0,
        GLOBE_RADIUS
    ]);
    cjsExports.mat4.scale(m, m, [
        pixelsToEcef,
        pixelsToEcef,
        pixelsToEcef * pixelsPerMeter
    ]);
    cjsExports.mat4.translate(m, m, [
        transform.point.x - 0.5 * worldSize,
        transform.point.y - 0.5 * worldSize,
        0
    ]);
    cjsExports.mat4.multiply(m, m, matrix);
    return cjsExports.mat4.multiply(m, transform.globeMatrix, m);
}
function affineMatrixLerp(a, b, t) {
    const lerpAxis = (ax, bx, t2) => {
        const axLen = cjsExports.vec3.length(ax);
        const bxLen = cjsExports.vec3.length(bx);
        const c = interpolateVec3(ax, bx, t2);
        return cjsExports.vec3.scale(c, c, 1 / cjsExports.vec3.length(c) * number(axLen, bxLen, t2));
    };
    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;
}
function queryGeometryIntersectsProjectedAabb(queryGeometry, transform, worldViewProjection, aabb) {
    const corners = Aabb.projectAabbCorners(aabb, worldViewProjection);
    let minDepth = Number.MAX_VALUE;
    let closestCornerIndex = -1;
    for (let c = 0; c < corners.length; ++c) {
        const corner = corners[c];
        corner[0] = (0.5 * corner[0] + 0.5) * transform.width;
        corner[1] = (0.5 - 0.5 * corner[1]) * transform.height;
        if (corner[2] < minDepth) {
            closestCornerIndex = c;
            minDepth = corner[2];
        }
    }
    const p = i => new Point(corners[i][0], corners[i][1]);
    let convexPolygon;
    switch (closestCornerIndex) {
    case 0:
    case 6:
        convexPolygon = [
            p(1),
            p(5),
            p(4),
            p(7),
            p(3),
            p(2),
            p(1)
        ];
        break;
    case 1:
    case 7:
        convexPolygon = [
            p(0),
            p(4),
            p(5),
            p(6),
            p(2),
            p(3),
            p(0)
        ];
        break;
    case 3:
    case 5:
        convexPolygon = [
            p(1),
            p(0),
            p(4),
            p(7),
            p(6),
            p(2),
            p(1)
        ];
        break;
    default:
        convexPolygon = [
            p(1),
            p(5),
            p(6),
            p(7),
            p(3),
            p(0),
            p(1)
        ];
        break;
    }
    if (polygonIntersectsPolygon(queryGeometry, convexPolygon)) {
        return minDepth;
    }
}

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'
    }
]);

const LayerTypeMask = {
    None: 0,
    Model: 1,
    Symbol: 2,
    FillExtrusion: 4,
    All: 7
};

class ValidationError {
    constructor(key, value, message, identifier) {
        this.message = (key ? `${ key }: ` : '') + message;
        if (identifier)
            this.identifier = identifier;
        if (value !== null && value !== void 0 && value.__line__) {
            this.line = value.__line__;
        }
    }
}
class ValidationWarning extends ValidationError {
}

function isValidUrl(str, allowRelativeUrls) {
    const isRelative = str.indexOf('://') === -1;
    try {
        new URL(str, isRelative && allowRelativeUrls ? 'http://example.com' : void 0);
        return true;
    } catch (_) {
        return false;
    }
}
function validateModel(options) {
    const url = options.value;
    let errors = [];
    if (!url) {
        return errors;
    }
    const type = getType(url);
    if (type !== 'string') {
        errors = errors.concat([new ValidationError(options.key, url, `string expected, "${ type }" found`)]);
        return errors;
    }
    if (!isValidUrl(url, true)) {
        errors = errors.concat([new ValidationError(options.key, url, `invalid url "${ url }"`)]);
    }
    return errors;
}

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 {
    // via this.features, enable lookup instancedDataArray based on feature ID.
    constructor() {
        this.instancedDataArray = new StructArrayLayout16f64();
        this.instancesEvaluatedElevation = [];
        this.features = [];
        this.idToFeaturesIndex = {};
    }
}
class ModelBucket {
    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;
        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
        };
        this.modelUris = [];
        this.modelsRequested = false;
        this.activeReplacements = [];
        this.replacementUpdateTime = 0;
    }
    updateFootprints(_id, _footprints) {
    }
    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 featureId = id != null ? id : feature.properties && feature.properties.hasOwnProperty('id') ? feature.properties['id'] : void 0;
            const evaluationFeature = toEvaluationFeature(feature, needGeometry);
            if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical))
                continue;
            const bucketFeature = {
                id: featureId,
                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, EXTENT / 32);
            }
        }
        this.lookup = null;
    }
    // eslint-disable-next-line no-unused-vars
    update(states, vtLayer, availableImages, imagePositions) {
        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.uploaded = false;
                }
            }
        }
        this.maxHeight = 0;
    }
    updateZoomBasedPaintProperties() {
        if (!this.hasZoomDependentProperties) {
            return false;
        }
        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);
                if (!cjsExports.vec3.exactEquals(feature.rotation, rotation) || !cjsExports.vec3.exactEquals(feature.scale, scale) || !cjsExports.vec3.exactEquals(feature.translation, translation)) {
                    this.evaluate(feature, feature.featureStates, instances, true);
                    reuploadNeeded = true;
                }
            }
        }
        return reuploadNeeded;
    }
    updateReplacement(coord, source, layerIndex, scope) {
        if (source.updateTime === this.replacementUpdateTime) {
            return false;
        }
        this.replacementUpdateTime = source.updateTime;
        const newReplacements = source.getReplacementRegionsForTile(coord.toUnwrapped(), true);
        if (regionsEquals(this.activeReplacements, newReplacements)) {
            return false;
        }
        this.activeReplacements = newReplacements;
        let reuploadNeeded = false;
        for (const modelId in this.instancesPerModel) {
            const perModelVertexArray = this.instancesPerModel[modelId];
            const va = perModelVertexArray.instancedDataArray;
            for (const feature of perModelVertexArray.features) {
                const offset = feature.instancedDataOffset;
                const count = feature.instancedDataCount;
                for (let i = 0; i < count; i++) {
                    const i16 = (i + offset) * 16;
                    let x_ = va.float32[i16 + 0];
                    const wasHidden = x_ > EXTENT;
                    x_ = wasHidden ? x_ - EXTENT : x_;
                    const x = Math.floor(x_);
                    const y = va.float32[i16 + 1];
                    let hidden = false;
                    for (const region of this.activeReplacements) {
                        if (skipClipping(region, layerIndex, LayerTypeMask.Model, scope))
                            continue;
                        if (region.min.x > x || x > region.max.x || region.min.y > y || y > region.max.y) {
                            continue;
                        }
                        const p = transformPointToTile(x, y, coord.canonical, region.footprintTileId.canonical);
                        hidden = pointInFootprint(p, region.footprint);
                        if (hidden)
                            break;
                    }
                    va.float32[i16] = hidden ? x_ + EXTENT : x_;
                    reuploadNeeded = reuploadNeeded || hidden !== wasHidden;
                }
            }
        }
        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) {
        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, void 0, 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();
            }
        }
        const modelManager = this.layers[0].modelManager;
        if (modelManager && this.modelUris) {
            for (const modelUri of this.modelUris) {
                modelManager.removeModel(modelUri, '');
            }
        }
    }
    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 (isValidUrl(modelId, false)) {
            if (!this.modelUris.includes(modelId)) {
                this.modelUris.push(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;
                }
                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;
    }
    getModelUris() {
        return this.modelUris;
    }
    evaluate(feature, featureState, perModelVertexArray, update) {
        const layer = this.layers[0];
        const evaluationFeature = feature.feature;
        const canonical = this.canonical;
        const rotation = feature.rotation = layer.paint.get('model-rotation').evaluate(evaluationFeature, featureState, canonical);
        const scale = feature.scale = layer.paint.get('model-scale').evaluate(evaluationFeature, featureState, canonical);
        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);
        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];
            }
            const pointY = va[offset + 1] | 0;
            va[offset] = (va[offset] | 0) + color.r / 1.05;
            va[offset + 1] = pointY + color.g / 1.05;
            va[offset + 2] = vaOffset2;
            va[offset + 3] = 1 / (canonical.z > constantTileToMeterAcrossTile ? this.tileToMeter : tileToMeter(canonical, pointY));
            va[offset + 4] = translation[0];
            va[offset + 5] = translation[1];
            va[offset + 6] = translation[2] + terrainElevationContribution;
            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');

let layout;
const getLayoutProperties = () => layout || (layout = new Properties({
    'visibility': new DataConstantProperty(spec['layout_model']['visibility']),
    'model-id': new DataDrivenProperty(spec['layout_model']['model-id'])
}));
let paint;
const getPaintProperties = () => paint || (paint = new Properties({
    'model-opacity': new DataDrivenProperty(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']),
    'model-front-cutoff': new DataConstantProperty(spec['paint_model']['model-front-cutoff']),
    'model-color-use-theme': new DataDrivenProperty({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-driven'
    })
}));

const HEIGHTMAP_DIM = 64;
const ModelTraits = {
    CoordinateSpaceTile: 1,
    CoordinateSpaceYUp: 2,
    // not used yet.
    HasMapboxMeshFeatures: 1 << 2,
    HasMeshoptCompression: 1 << 3
};
const DefaultModelScale = [
    1,
    1,
    1
];
function positionModelOnTerrain(rotationOnTerrain, transform, aabb, matrix, position) {
    const elevation = transform.elevation;
    if (!elevation) {
        return 0;
    }
    const corners = Aabb.projectAabbCorners(aabb, matrix);
    const meterToMercator = mercatorZfromAltitude(1, 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);
}
function calculateModelMatrix(matrix, model, state, position, rotation, scale, translation, applyElevation, followTerrainSlope, viewportScale = false) {
    const zoom = state.zoom;
    const projectedPoint = state.project(position);
    const modelMetersPerPixel = getMetersPerPixelAtLatitude(position.lat, zoom);
    const modelPixelsPerMeter = 1 / modelMetersPerPixel;
    cjsExports.mat4.identity(matrix);
    const offset = [
        projectedPoint.x + translation[0] * modelPixelsPerMeter,
        projectedPoint.y + translation[1] * modelPixelsPerMeter,
        translation[2]
    ];
    cjsExports.mat4.translate(matrix, 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 = cjsExports.vec4.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(matrix, state);
            const worldViewProjection = cjsExports.mat4.multiply([], state.projMatrix, globeMatrix);
            const globeProjPos = [
                0,
                0,
                0,
                1
            ];
            cjsExports.vec4.transformMat4(globeProjPos, globeProjPos, worldViewProjection);
            const globeProjectionScale = globeProjPos[3] / state.cameraToCenterDistance;
            const transition = globeToMercatorTransition(zoom);
            const modelPixelConv = state.projection.pixelsPerMeter(position.lat, worldSize) * getMetersPerPixelAtLatitude(position.lat, zoom);
            const viewPixelConv = state.projection.pixelsPerMeter(state.center.lat, worldSize) * getMetersPerPixelAtLatitude(state.center.lat, zoom);
            const viewLatScale = getLatitudeScale(state.center.lat);
            scaleXY = globeProjectionScale / number(modelPixelConv, viewLatScale, transition);
            scaleZ = globeProjectionScale * modelMetersPerPixel / modelPixelConv;
            scaleXY *= viewPixelConv;
            scaleZ *= viewPixelConv;
        }
    } else {
        scaleXY = modelPixelsPerMeter;
    }
    cjsExports.mat4.scale(matrix, matrix, [
        scaleXY,
        scaleXY,
        scaleZ
    ]);
    const modelMatrixBeforeRotationScaleYZFlip = [...matrix];
    const orientation = model.orientation;
    const rotationScaleYZFlip = [];
    rotationScaleYZFlipMatrix(rotationScaleYZFlip, [
        orientation[0] + rotation[0],
        orientation[1] + rotation[1],
        orientation[2] + rotation[2]
    ], scale);
    cjsExports.mat4.multiply(matrix, modelMatrixBeforeRotationScaleYZFlip, rotationScaleYZFlip);
    if (applyElevation && state.elevation) {
        let elevate = 0;
        const rotateOnTerrain = [];
        if (followTerrainSlope && state.elevation) {
            elevate = positionModelOnTerrain(rotateOnTerrain, state, model.aabb, matrix, position);
            const rotationOnTerrain = cjsExports.mat4.fromQuat([], rotateOnTerrain);
            const appendRotation = cjsExports.mat4.multiply([], rotationOnTerrain, rotationScaleYZFlip);
            cjsExports.mat4.multiply(matrix, modelMatrixBeforeRotationScaleYZFlip, appendRotation);
        } else {
            elevate = state.elevation.getAtPointOrZero(new MercatorCoordinate(projectedPoint.x / worldSize, projectedPoint.y / worldSize), 0);
        }
        if (elevate !== 0) {
            matrix[14] += elevate;
        }
    }
}
class Model {
    constructor(id, position, orientation, nodes) {
        this.id = id;
        this.position = position != null ? new LngLat(position[0], position[1]) : new LngLat(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) {
        cjsExports.mat4.multiply(node.matrix, parentMatrix, node.matrix);
        if (node.meshes) {
            for (const mesh of node.meshes) {
                const enclosingBounds = Aabb.applyTransformFast(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 = cjsExports.mat4.identity([]);
        for (const node of this.nodes) {
            this._applyTransformations(node, localMatrix);
        }
    }
    computeModelMatrix(painter, rotation, scale, translation, applyElevation, followTerrainSlope, viewportScale = false) {
        calculateModelMatrix(this.matrix, this, painter.transform, this.position, rotation, scale, translation, applyElevation, followTerrainSlope, viewportScale);
    }
    upload(context) {
        if (this.uploaded)
            return;
        for (const node of this.nodes) {
            uploadNode(node, context);
        }
        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) {
    const textureFormat = useSingleChannelTexture ? context.gl.R8 : context.gl.RGBA8;
    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) {
    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);
    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 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;
        }
        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;
            cjsExports.vec3.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;
        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 {vec4} If there is intersection with terrain, returns vec4(x, y, z, e), a
   * 3D MercatorCoordinate's of intersection in its first 3 components, and elevation in meter in its 4th coordinate.
   * Otherwise returns null.
   */
    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.');
    }
    /**
   * Get elevation minimum and maximum for tiles which are visible on the current frame.
   */
    getMinMaxForVisibleTiles() {
        const visibleTiles = this.visibleDemTiles;
        if (visibleTiles.length === 0) {
            return null;
        }
        let found = false;
        let min = Number.MAX_VALUE;
        let max = Number.MIN_VALUE;
        for (const tile of visibleTiles) {
            const minmax = this.getMinMaxForTile(tile.tileID);
            if (!minmax) {
                continue;
            }
            min = Math.min(min, minmax.min);
            max = Math.max(max, minmax.max);
            found = true;
        }
        if (!found) {
            return null;
        }
        return {
            min,
            max
        };
    }
}
class DEMSampler {
    constructor(demTile, scale, offset) {
        this._demTile = demTile;
        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(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;
    }
}

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;
}
function addAABBsToGridIndex(node, key, grid) {
    if (node.meshes) {
        for (const mesh of node.meshes) {
            if (mesh.aabb.min[0] === Infinity)
                continue;
            const meshAabb = Aabb.applyTransform(mesh.aabb, node.matrix);
            grid.insert(key, meshAabb.min[0], meshAabb.min[1], meshAabb.max[0], meshAabb.max[1]);
        }
    }
    if (node.children) {
        for (const child of node.children) {
            addAABBsToGridIndex(child, key, grid);
        }
    }
}
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
            ]
        ];
        this.hiddenByReplacement = false;
        this.evaluatedScale = [
            1,
            1,
            1
        ];
        this.evaluatedColor = [];
        this.emissionHeightBasedParams = [];
        this.cameraCollisionOpacity = 1;
        this.feature = {
            type: 'Point',
            id: node.id,
            geometry: [],
            properties: { 'height': getNodeHeight(node) }
        };
        this.aabb = this._getLocalBounds();
        this.state = null;
    }
    _getLocalBounds() {
        if (!this.node.meshes) {
            return new Aabb([
                Infinity,
                Infinity,
                Infinity
            ], [
                -Infinity,
                -Infinity,
                -Infinity
            ]);
        }
        if (!this.aabb) {
            let i = 0;
            const aabb = new Aabb([
                Infinity,
                Infinity,
                Infinity
            ], [
                -Infinity,
                -Infinity,
                -Infinity
            ]);
            for (const mesh of this.node.meshes) {
                if (this.node.lightMeshIndex !== i) {
                    mesh.transformedAabb = Aabb.applyTransformFast(mesh.aabb, this.node.matrix);
                    aabb.encapsulate(mesh.transformedAabb);
                }
                i++;
            }
            this.aabb = aabb;
        }
        return this.aabb;
    }
}
class Tiled3dModelBucket {
    constructor(layers, nodes, id, hasMbxMeshFeatures, hasMeshoptCompression, brightness, featureIndex) {
        this.id = id;
        this.layers = layers;
        this.layerIds = this.layers.map(layer => layer.fqid);
        this.stateDependentLayerIds = this.layers.filter(l => l.isStateDependent()).map(l => l.id);
        this.modelTraits |= ModelTraits.CoordinateSpaceTile;
        this.uploaded = false;
        this.hasPattern = false;
        if (hasMbxMeshFeatures) {
            this.modelTraits |= ModelTraits.HasMapboxMeshFeatures;
        }
        if (hasMeshoptCompression) {
            this.modelTraits |= ModelTraits.HasMeshoptCompression;
        }
        this.zoom = -1;
        this.terrainExaggeration = 1;
        this.projection = { name: 'mercator' };
        this.replacementUpdateTime = 0;
        this.elevationReadFromZ = 255;
        this.brightness = brightness;
        this.dirty = true;
        this.needsUpload = false;
        this.nodesInfo = [];
        for (const node of nodes) {
            this.nodesInfo.push(new Tiled3dModelFeature(node));
            addAABBsToGridIndex(node, featureIndex.featureIndexArray.length, featureIndex.grid);
            featureIndex.featureIndexArray.emplaceBack(this.nodesInfo.length - 1, 0, featureIndex.bucketLayerIDs.length - 1, 0);
        }
        this.states = {};
    }
    updateFootprints(id, footprints) {
        for (const nodeInfo of this.getNodesInfo()) {
            const node = nodeInfo.node;
            if (!node.footprint) {
                continue;
            }
            footprints.push({
                footprint: node.footprint,
                id
            });
        }
    }
    update(states) {
        const withStateUpdates = Object.keys(states).length !== 0;
        if (withStateUpdates && !this.stateDependentLayers.length)
            return;
        const layers = withStateUpdates ? this.stateDependentLayers : this.layers;
        if (!deepEqual(states, this.states)) {
            for (const layer of layers) {
                this.evaluate(layer, states);
            }
        }
        this.states = structuredClone(states);
    }
    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);
        }
        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;
            const nodesInfo = this.getNodesInfo();
            for (const nodeInfo of nodesInfo) {
                nodeInfo.state = null;
            }
            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, states) {
        const nodesInfo = this.getNodesInfo();
        for (const nodeInfo of nodesInfo) {
            if (!nodeInfo.node.meshes)
                continue;
            const evaluationFeature = nodeInfo.feature;
            const state = states && states[evaluationFeature.id];
            if (deepEqual(state, nodeInfo.state))
                continue;
            nodeInfo.state = structuredClone(state);
            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, state, canonical).toRenderColor(null);
                    const colorMixIntensity = layer.paint.get('model-color-mix-intensity').evaluate(evaluationFeature, state, canonical);
                    nodeInfo.evaluatedColor[i] = [
                        color.r,
                        color.g,
                        color.b,
                        colorMixIntensity
                    ];
                    nodeInfo.evaluatedRMEA[i][0] = layer.paint.get('model-roughness').evaluate(evaluationFeature, state, canonical);
                    nodeInfo.evaluatedRMEA[i][2] = layer.paint.get('model-emissive-strength').evaluate(evaluationFeature, state, canonical);
                    nodeInfo.evaluatedRMEA[i][3] = color.a;
                    nodeInfo.emissionHeightBasedParams[i] = layer.paint.get('model-height-based-emissive-strength-multiplier').evaluate(evaluationFeature, state, 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, this.modelTraits);
            } else {
                nodeInfo.evaluatedRMEA[0][2] = layer.paint.get('model-emissive-strength').evaluate(evaluationFeature, state, canonical);
            }
            nodeInfo.evaluatedScale = layer.paint.get('model-scale').evaluate(evaluationFeature, state, 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 === void 0) {
            dem._dem._modifiedForSources[source] = [];
            tiles = dem._dem._modifiedForSources[source];
        }
        if (tiles.includes(coord.canonical)) {
            return;
        }
        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;
            }
            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;
            }
            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;
                }
            }
            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;
            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);
            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);
                    }
                }
            }
            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 (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;
                                const parent = dem._dem.get(x + xoffset, y + yoffset);
                                const child = dem._dem.get(x - xoffset, y - yoffset, true);
                                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() {
        return this.nodesInfo;
    }
    destroy() {
        const nodesInfo = this.getNodesInfo();
        for (const nodeInfo of nodesInfo) {
            destroyNodeArrays(nodeInfo.node);
            destroyBuffers(nodeInfo.node);
        }
    }
    isEmpty() {
        return !this.nodesInfo.length;
    }
    updateReplacement(coord, source) {
        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;
            nodesInfo[i].hiddenByReplacement = !!node.footprint && !activeReplacements.find(region => region.footprint === node.footprint);
        }
    }
    getHeightAtTileCoord(x, y) {
        const nodesInfo = this.getNodesInfo();
        const candidates = [];
        const tmpVertex = [
            0,
            0,
            0
        ];
        const nodeInverse = cjsExports.mat4.identity([]);
        for (let i = 0; i < this.nodesInfo.length; i++) {
            const nodeInfo = nodesInfo[i];
            const mesh = nodeInfo.node.meshes[0];
            const meshAabb = mesh.transformedAabb;
            if (x < meshAabb.min[0] || y < meshAabb.min[1] || x > meshAabb.max[0] || y > meshAabb.max[1])
                continue;
            if (nodeInfo.node.hidden === true)
                return {
                    height: Infinity,
                    maxHeight: nodeInfo.feature.properties['height'],
                    hidden: false,
                    verticalScale: nodeInfo.evaluatedScale[2]
                };
            cjsExports.mat4.invert(nodeInverse, nodeInfo.node.matrix);
            tmpVertex[0] = x;
            tmpVertex[1] = y;
            cjsExports.vec3.transformMat4(tmpVertex, tmpVertex, nodeInverse);
            const xCell = (tmpVertex[0] - mesh.aabb.min[0]) / (mesh.aabb.max[0] - mesh.aabb.min[0]) * HEIGHTMAP_DIM | 0;
            const yCell = (tmpVertex[1] - 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);
            const heightValue = mesh.heightmap[heightmapIndex];
            if (heightValue < 0 && nodeInfo.node.footprint) {
                nodeInfo.node.footprint.grid.query(new Point(x, y), new Point(x, y), candidates);
                if (candidates.length > 0) {
                    return {
                        height: void 0,
                        maxHeight: nodeInfo.feature.properties['height'],
                        hidden: nodeInfo.hiddenByReplacement,
                        verticalScale: nodeInfo.evaluatedScale[2]
                    };
                }
                continue;
            }
            if (nodeInfo.hiddenByReplacement)
                return;
            return {
                height: heightValue,
                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, modelTraits) {
    const node = nodeInfo.node;
    let i = 0;
    const isV2Tile = modelTraits & ModelTraits.HasMeshoptCompression;
    for (const mesh of node.meshes) {
        if (node.lights && node.lightMeshIndex === i)
            continue;
        if (!mesh.featureData)
            continue;
        mesh.featureArray = new StructArrayLayout4ui3f20();
        mesh.featureArray.reserve(mesh.featureData.length);
        let pendingDoorLightUpdate = doorLightChanged;
        for (const feature of mesh.featureData) {
            const featureColor = isV2Tile ? feature & 65535 : feature >> 16 & 65535;
            const id = isV2Tile ? feature >> 16 & 65535 : feature & 65535;
            const partId = (id & 15) < 8 ? id & 15 : 0;
            const rmea = nodeInfo.evaluatedRMEA[partId];
            const evaluatedColor = nodeInfo.evaluatedColor[partId];
            const emissionParams = nodeInfo.emissionHeightBasedParams[partId];
            let lightsFeatureArray;
            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');

class ModelStyleLayer extends StyleLayer {
    constructor(layer, scope, lut, options) {
        const properties = {
            layout: getLayoutProperties(),
            paint: getPaintProperties()
        };
        super(layer, properties, scope, lut, options);
        this._stats = {
            numRenderedVerticesInShadowPass: 0,
            numRenderedVerticesInTransparentPass: 0
        };
    }
    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');
    }
    queryRadius(bucket) {
        return bucket instanceof Tiled3dModelBucket ? EXTENT - 1 : 0;
    }
    queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform) {
        if (!this.modelManager)
            return false;
        const modelManager = this.modelManager;
        const bucket = queryGeometry.tile.getBucket(this);
        if (!bucket || !(bucket instanceof ModelBucket))
            return false;
        for (const modelId in bucket.instancesPerModel) {
            const instances = bucket.instancesPerModel[modelId];
            const featureId = feature.id !== void 0 ? feature.id : feature.properties && feature.properties.hasOwnProperty('id') ? feature.properties['id'] : void 0;
            if (instances.idToFeaturesIndex.hasOwnProperty(featureId)) {
                const modelFeature = instances.features[instances.idToFeaturesIndex[featureId]];
                const model = modelManager.getModel(modelId, this.scope);
                if (!model)
                    return false;
                let matrix = cjsExports.mat4.create();
                const position = new LngLat(0, 0);
                const id = bucket.canonical;
                let minDepth = Number.MAX_VALUE;
                for (let i = 0; i < modelFeature.instancedDataCount; ++i) {
                    const instanceOffset = modelFeature.instancedDataOffset + i;
                    const offset = instanceOffset * 16;
                    const va = instances.instancedDataArray.float32;
                    const translation = [
                        va[offset + 4],
                        va[offset + 5],
                        va[offset + 6]
                    ];
                    const pointX = va[offset];
                    const pointY = va[offset + 1] | 0;
                    tileToLngLat(id, position, pointX, pointY);
                    calculateModelMatrix(matrix, model, transform, position, modelFeature.rotation, modelFeature.scale, translation, false, false, false);
                    if (transform.projection.name === 'globe') {
                        matrix = convertModelMatrixForGlobe(matrix, transform);
                    }
                    const worldViewProjection = cjsExports.mat4.multiply([], transform.projMatrix, matrix);
                    const screenQuery = queryGeometry.queryGeometry;
                    const projectedQueryGeometry = screenQuery.isPointQuery() ? screenQuery.screenBounds : screenQuery.screenGeometry;
                    const depth = queryGeometryIntersectsProjectedAabb(projectedQueryGeometry, transform, worldViewProjection, model.aabb);
                    if (depth != null) {
                        minDepth = Math.min(depth, minDepth);
                    }
                }
                if (minDepth !== Number.MAX_VALUE) {
                    return minDepth;
                }
                return false;
            }
        }
        return false;
    }
    _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) {
        if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {
            return false;
        }
        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');
    }
}
function tileToLngLat(id, position, pointX, pointY) {
    const tileCount = 1 << id.z;
    position.lat = latFromMercatorY((pointY / EXTENT + id.y) / tileCount);
    position.lng = lngFromMercatorX((pointX / EXTENT + id.x) / tileCount);
}
function loadMatchingModelFeature(bucket, featureIndex, tilespaceGeometry, transform) {
    const nodeInfo = bucket.getNodesInfo()[featureIndex];
    if (nodeInfo.hiddenByReplacement || !nodeInfo.node.meshes)
        return;
    let intersectionZ = Number.MAX_VALUE;
    const node = nodeInfo.node;
    const tile = tilespaceGeometry.tile;
    const tileMatrix = transform.calculatePosMatrix(tile.tileID.toUnwrapped(), transform.worldSize);
    const modelMatrix = tileMatrix;
    const scale = nodeInfo.evaluatedScale;
    let elevation = 0;
    if (transform.elevation && node.elevation) {
        elevation = node.elevation * transform.elevation.exaggeration();
    }
    const anchorX = node.anchor ? node.anchor[0] : 0;
    const anchorY = node.anchor ? node.anchor[1] : 0;
    cjsExports.mat4.translate(modelMatrix, modelMatrix, [
        anchorX * (scale[0] - 1),
        anchorY * (scale[1] - 1),
        elevation
    ]);
    cjsExports.mat4.scale(modelMatrix, modelMatrix, scale);
    const screenQuery = tilespaceGeometry.queryGeometry;
    const projectedQueryGeometry = screenQuery.isPointQuery() ? screenQuery.screenBounds : screenQuery.screenGeometry;
    const checkNode = function (n) {
        const worldViewProjectionForNode = cjsExports.mat4.multiply([], modelMatrix, n.matrix);
        cjsExports.mat4.multiply(worldViewProjectionForNode, transform.expandedFarZProjMatrix, worldViewProjectionForNode);
        for (let i = 0; i < n.meshes.length; ++i) {
            const mesh = n.meshes[i];
            if (i === n.lightMeshIndex) {
                continue;
            }
            const depth = queryGeometryIntersectsProjectedAabb(projectedQueryGeometry, transform, worldViewProjectionForNode, mesh.aabb);
            if (depth != null) {
                intersectionZ = Math.min(depth, intersectionZ);
            }
        }
        if (n.children) {
            for (const child of n.children) {
                checkNode(child);
            }
        }
    };
    checkNode(node);
    if (intersectionZ === Number.MAX_VALUE)
        return;
    const position = new LngLat(0, 0);
    tileToLngLat(tile.tileID.canonical, position, nodeInfo.node.anchor[0], nodeInfo.node.anchor[1]);
    return {
        intersectionZ,
        position,
        feature: nodeInfo.feature
    };
}

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

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 = void 0;
        this._callback = () => {
        };
    }
}

class Scheduler {
    constructor() {
        this.tasks = {};
        this.taskQueue = [];
        bindAll(['process'], this);
        this.invoker = new ThrottledInvoker(this.process);
        this.nextId = 0;
    }
    add(fn, metadata) {
        const id = this.nextId++;
        const priority = getPriority(metadata);
        if (priority === 0) {
            try {
                fn();
            } finally {
            }
            return null;
        }
        this.tasks[id] = {
            fn,
            metadata,
            priority,
            id
        };
        this.taskQueue.push(id);
        this.invoker.trigger();
        return {
            cancel: () => {
                delete this.tasks[id];
            }
        };
    }
    process() {
        try {
            this.taskQueue = this.taskQueue.filter(id2 => !!this.tasks[id2]);
            if (!this.taskQueue.length) {
                return;
            }
            const id = this.pick();
            if (id === null)
                return;
            const task = this.tasks[id];
            delete this.tasks[id];
            if (this.taskQueue.length) {
                this.invoker.trigger();
            }
            if (!task) {
                return;
            }
            task.fn();
        } finally {
        }
    }
    pick() {
        let minIndex = null;
        let minPriority = Infinity;
        for (let i = 0; i < this.taskQueue.length; i++) {
            const id2 = this.taskQueue[i];
            const task = this.tasks[id2];
            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;
}

class Actor {
    constructor(target, parent, mapId) {
        this.target = target;
        this.parent = parent;
        this.mapId = mapId;
        this.callbacks = {};
        this.cancelCallbacks = {};
        bindAll(['receive'], this);
        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) {
        const id = Math.round(Math.random() * 1000000000000000000).toString(36).substring(0, 10);
        if (callback) {
            callback.metadata = callbackMetadata;
            this.callbacks[id] = callback;
        }
        const buffers = /* @__PURE__ */
        new Set();
        this.target.postMessage({
            id,
            type,
            hasCallback: !!callback,
            targetMapId,
            mustQueue,
            sourceMapId: this.mapId,
            data: serialize(data, buffers)
        }, buffers);
        return {
            cancel: () => {
                if (callback) {
                    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>') {
            const cancel = this.cancelCallbacks[id];
            delete this.cancelCallbacks[id];
            if (cancel) {
                cancel.cancel();
            }
        } else {
            if (data.mustQueue || isWorker()) {
                const callback = this.callbacks[id];
                const metadata = callback && callback.metadata || { type: 'message' };
                const cancel = this.scheduler.add(() => this.processTask(id, data), metadata);
                if (cancel)
                    this.cancelCallbacks[id] = cancel;
            } else {
                this.processTask(id, data);
            }
        }
    }
    processTask(id, task) {
        delete this.cancelCallbacks[id];
        if (task.type === '<response>') {
            const callback = this.callbacks[id];
            delete this.callbacks[id];
            if (callback) {
                if (task.error) {
                    callback(deserialize(task.error));
                } else {
                    callback(null, deserialize(task.data));
                }
            }
        } else {
            const buffers = /* @__PURE__ */
            new Set();
            const done = task.hasCallback ? (err, data) => {
                this.target.postMessage({
                    id,
                    type: '<response>',
                    sourceMapId: this.mapId,
                    error: err ? serialize(err) : null,
                    data: serialize(data, buffers)
                }, buffers);
            } : () => {
            };
            const params = deserialize(task.data);
            if (this.parent[task.type]) {
                this.parent[task.type](task.sourceMapId, params, done);
            } else if (this.parent.getWorkerSource) {
                const keys = task.type.split('.');
                const scope = this.parent.getWorkerSource(task.sourceMapId, keys[0], params.source, params.scope);
                scope[keys[1]](params, done);
            } else {
                done(new Error(`Could not find function ${ task.type }`));
            }
        }
    }
    remove() {
        this.scheduler.remove();
        this.target.removeEventListener('message', this.receive, false);
    }
}

var WorkerClass = {
    workerUrl: '',
    workerClass: null,
    workerParams: void 0
};

function createWorker() {
    return WorkerClass.workerClass != null ? new WorkerClass.workerClass() : new self.Worker(WorkerClass.workerUrl, WorkerClass.workerParams);
}

const PRELOAD_POOL_ID = 'mapboxgl_preloaded_worker_pool';
class WorkerPool {
    constructor() {
        this.active = {};
    }
    acquire(mapId, count = WorkerPool.workerCount) {
        if (!this.workers) {
            this.workers = [];
            while (this.workers.length < count) {
                this.workers.push(createWorker());
            }
        }
        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;
    }
}
WorkerPool.workerCount = 2;

class Dispatcher {
    constructor(workerPool, parent, name = 'Worker', count = WorkerPool.workerCount) {
        this.workerPool = workerPool;
        this.actors = [];
        this.currentActor = 0;
        this.id = uniqueId();
        const workers = this.workerPool.acquire(this.id, count);
        for (let i = 0; i < workers.length; i++) {
            const worker = workers[i];
            const actor = new Dispatcher.Actor(worker, parent, this.id);
            actor.name = `${ name } ${ i }`;
            this.actors.push(actor);
        }
        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;

let globalWorkerPool;
let imageRasterizerWorkerPool;
function getGlobalWorkerPool() {
    if (!globalWorkerPool) {
        globalWorkerPool = new WorkerPool();
    }
    return globalWorkerPool;
}
function getImageRasterizerWorkerPool() {
    if (!imageRasterizerWorkerPool) {
        imageRasterizerWorkerPool = new WorkerPool();
    }
    return imageRasterizerWorkerPool;
}
function prewarm() {
    const workerPool = getGlobalWorkerPool();
    workerPool.acquire(PRELOAD_POOL_ID);
}
function clearPrewarmedResources() {
    const pool = globalWorkerPool;
    if (pool) {
        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()');
        }
    }
}

const defaultColor = new Color(0, 0, 0);
var PathRule = /* @__PURE__ */
(PathRule2 => {
    PathRule2[PathRule2['PATH_RULE_UNSPECIFIED'] = 0] = 'PATH_RULE_UNSPECIFIED';
    PathRule2[PathRule2['PATH_RULE_NON_ZERO'] = 1] = 'PATH_RULE_NON_ZERO';
    PathRule2[PathRule2['PATH_RULE_EVEN_ODD'] = 2] = 'PATH_RULE_EVEN_ODD';
    return PathRule2;
})(PathRule || {});
var LineCap = /* @__PURE__ */
(LineCap2 => {
    LineCap2[LineCap2['LINE_CAP_UNSPECIFIED'] = 0] = 'LINE_CAP_UNSPECIFIED';
    LineCap2[LineCap2['LINE_CAP_BUTT'] = 1] = 'LINE_CAP_BUTT';
    LineCap2[LineCap2['LINE_CAP_ROUND'] = 2] = 'LINE_CAP_ROUND';
    LineCap2[LineCap2['LINE_CAP_SQUARE'] = 3] = 'LINE_CAP_SQUARE';
    return LineCap2;
})(LineCap || {});
var LineJoin = /* @__PURE__ */
(LineJoin2 => {
    LineJoin2[LineJoin2['LINE_JOIN_UNSPECIFIED'] = 0] = 'LINE_JOIN_UNSPECIFIED';
    LineJoin2[LineJoin2['LINE_JOIN_MITER'] = 1] = 'LINE_JOIN_MITER';
    LineJoin2[LineJoin2['LINE_JOIN_MITER_CLIP'] = 2] = 'LINE_JOIN_MITER_CLIP';
    LineJoin2[LineJoin2['LINE_JOIN_ROUND'] = 3] = 'LINE_JOIN_ROUND';
    LineJoin2[LineJoin2['LINE_JOIN_BEVEL'] = 4] = 'LINE_JOIN_BEVEL';
    return LineJoin2;
})(LineJoin || {});
var PaintOrder = /* @__PURE__ */
(PaintOrder2 => {
    PaintOrder2[PaintOrder2['PAINT_ORDER_UNSPECIFIED'] = 0] = 'PAINT_ORDER_UNSPECIFIED';
    PaintOrder2[PaintOrder2['PAINT_ORDER_FILL_AND_STROKE'] = 1] = 'PAINT_ORDER_FILL_AND_STROKE';
    PaintOrder2[PaintOrder2['PAINT_ORDER_STROKE_AND_FILL'] = 2] = 'PAINT_ORDER_STROKE_AND_FILL';
    return PaintOrder2;
})(PaintOrder || {});
var PathCommand = /* @__PURE__ */
(PathCommand2 => {
    PathCommand2[PathCommand2['PATH_COMMAND_UNSPECIFIED'] = 0] = 'PATH_COMMAND_UNSPECIFIED';
    PathCommand2[PathCommand2['PATH_COMMAND_MOVE'] = 1] = 'PATH_COMMAND_MOVE';
    PathCommand2[PathCommand2['PATH_COMMAND_LINE'] = 2] = 'PATH_COMMAND_LINE';
    PathCommand2[PathCommand2['PATH_COMMAND_QUAD'] = 3] = 'PATH_COMMAND_QUAD';
    PathCommand2[PathCommand2['PATH_COMMAND_CUBIC'] = 4] = 'PATH_COMMAND_CUBIC';
    PathCommand2[PathCommand2['PATH_COMMAND_CLOSE'] = 5] = 'PATH_COMMAND_CLOSE';
    return PathCommand2;
})(PathCommand || {});
var MaskType = /* @__PURE__ */
(MaskType2 => {
    MaskType2[MaskType2['MASK_TYPE_UNSPECIFIED'] = 0] = 'MASK_TYPE_UNSPECIFIED';
    MaskType2[MaskType2['MASK_TYPE_LUMINANCE'] = 1] = 'MASK_TYPE_LUMINANCE';
    MaskType2[MaskType2['MASK_TYPE_ALPHA'] = 2] = 'MASK_TYPE_ALPHA';
    return MaskType2;
})(MaskType || {});
function readIconSet(pbf, end) {
    return pbf.readFields(readIconSetField, { icons: [] }, end);
}
function readIconSetField(tag, obj, pbf) {
    if (tag === 1)
        obj.icons.push(readIcon(pbf, pbf.readVarint() + pbf.pos));
}
function buildStretchedAreas(metadata, axis) {
    const areas = [];
    const stretch = metadata[`stretch_${ axis }`];
    let left = null;
    for (let i = 0; i < stretch.length; i++) {
        if (left === null) {
            if (areas.length === 0) {
                left = stretch[0];
            } else {
                left = areas[areas.length - 1][1] + stretch[i];
            }
        } else {
            const right = left + stretch[i];
            areas.push([
                left,
                right
            ]);
            left = null;
        }
    }
    metadata[`stretch_${ axis }_areas`] = areas;
}
function postProcessIcon(icon) {
    if (!icon.usvg_tree.height) {
        icon.usvg_tree.height = icon.usvg_tree.width;
    }
    if (!icon.metadata) {
        return icon;
    }
    const {metadata} = icon;
    if (metadata.content_area) {
        const {content_area: contentArea} = metadata;
        if (contentArea.top == null) {
            contentArea.top = contentArea.left;
        }
        if (contentArea.width == null) {
            contentArea.width = icon.usvg_tree.width;
        }
        if (contentArea.height == null) {
            contentArea.height = contentArea.width;
        }
    }
    if (metadata.stretch_x && metadata.stretch_x.length) {
        buildStretchedAreas(metadata, 'x');
    }
    if (metadata.stretch_y && metadata.stretch_y.length) {
        buildStretchedAreas(metadata, 'y');
    }
    return icon;
}
function readIcon(pbf, end) {
    return postProcessIcon(pbf.readFields(readIconField, { name: void 0 }, end));
}
function readIconField(tag, obj, pbf) {
    if (tag === 1)
        obj.name = pbf.readString();
    else if (tag === 2)
        obj.metadata = readIconMetadata(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 3) {
        obj.usvg_tree = readUsvgTree(pbf, pbf.readVarint() + pbf.pos);
        obj.data = 'usvg_tree';
    }
}
function readIconMetadata(pbf, end) {
    return pbf.readFields(readIconMetadataField, {
        stretch_x: null,
        stretch_y: null,
        stretch_x_areas: null,
        stretch_y_areas: null,
        variables: []
    }, end);
}
function readIconMetadataField(tag, obj, pbf) {
    if (tag === 1)
        obj.stretch_x = pbf.readPackedVarint();
    else if (tag === 2)
        obj.stretch_y = pbf.readPackedVarint();
    else if (tag === 3)
        obj.content_area = readContentArea(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 4)
        obj.variables.push(readVariable(pbf, pbf.readVarint() + pbf.pos));
}
function readContentArea(pbf, end) {
    return pbf.readFields(readContentAreaField, { left: 0 }, end);
}
function readContentAreaField(tag, obj, pbf) {
    if (tag === 1)
        obj.left = pbf.readVarint();
    else if (tag === 2)
        obj.width = pbf.readVarint();
    else if (tag === 3)
        obj.top = pbf.readVarint();
    else if (tag === 4)
        obj.height = pbf.readVarint();
}
function readVariable(pbf, end) {
    return pbf.readFields(readVariableField, { name: void 0 }, end);
}
function readVariableField(tag, obj, pbf) {
    if (tag === 1)
        obj.name = pbf.readString();
    else if (tag === 2) {
        obj.rgb_color = readColor(pbf.readVarint());
        obj.value = 'rgb_color';
    }
}
function readUsvgTree(pbf, end) {
    return pbf.readFields(readUsvgTreeField, {
        width: 20,
        children: [],
        linear_gradients: [],
        radial_gradients: [],
        clip_paths: [],
        masks: []
    }, end);
}
function readUsvgTreeField(tag, obj, pbf) {
    if (tag === 1)
        obj.width = obj.height = pbf.readVarint();
    else if (tag === 2)
        obj.height = pbf.readVarint();
    else if (tag === 3)
        obj.children.push(readNode(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 4)
        obj.linear_gradients.push(readLinearGradient(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 5)
        obj.radial_gradients.push(readRadialGradient(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 7)
        obj.clip_paths.push(readClipPath(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 8)
        obj.masks.push(readMask(pbf, pbf.readVarint() + pbf.pos));
}
function readNode(pbf, end) {
    return pbf.readFields(readNodeField, {}, end);
}
function readNodeField(tag, obj, pbf) {
    if (tag === 1) {
        obj.group = readGroup(pbf, pbf.readVarint() + pbf.pos);
        obj.node = 'group';
    } else if (tag === 2) {
        obj.path = readPath(pbf, pbf.readVarint() + pbf.pos);
        obj.node = 'path';
    }
}
function readGroup(pbf, end) {
    return pbf.readFields(readGroupField, {
        opacity: 255,
        children: []
    }, end);
}
function readGroupField(tag, obj, pbf) {
    if (tag === 1)
        obj.transform = readTransform(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 2)
        obj.opacity = pbf.readVarint();
    else if (tag === 5)
        obj.clip_path_idx = pbf.readVarint();
    else if (tag === 6)
        obj.mask_idx = pbf.readVarint();
    else if (tag === 7)
        obj.children.push(readNode(pbf, pbf.readVarint() + pbf.pos));
}
function readTransform(pbf, end) {
    return pbf.readFields(readTransformField, {
        sx: 1,
        ky: 0,
        kx: 0,
        sy: 1,
        tx: 0,
        ty: 0
    }, end);
}
function readTransformField(tag, obj, pbf) {
    if (tag === 1)
        obj.sx = pbf.readFloat();
    else if (tag === 2)
        obj.ky = pbf.readFloat();
    else if (tag === 3)
        obj.kx = pbf.readFloat();
    else if (tag === 4)
        obj.sy = pbf.readFloat();
    else if (tag === 5)
        obj.tx = pbf.readFloat();
    else if (tag === 6)
        obj.ty = pbf.readFloat();
}
function readPath(pbf, end) {
    return pbf.readFields(readPathField, {
        paint_order: 1,
        commands: [],
        step: 1,
        diffs: [],
        rule: 1    /* PATH_RULE_NON_ZERO */
    }, end);
}
function readPathField(tag, obj, pbf) {
    if (tag === 1)
        obj.fill = readFill(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 2)
        obj.stroke = readStroke(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 3)
        obj.paint_order = pbf.readVarint();
    else if (tag === 5)
        pbf.readPackedVarint(obj.commands);
    else if (tag === 6)
        obj.step = pbf.readFloat();
    else if (tag === 7)
        pbf.readPackedSVarint(obj.diffs);
    else if (tag === 8)
        obj.rule = pbf.readVarint();
}
function readFill(pbf, end) {
    return pbf.readFields(readFillField, {
        rgb_color: defaultColor,
        paint: 'rgb_color',
        opacity: 255
    }, end);
}
function readFillField(tag, obj, pbf) {
    if (tag === 1) {
        obj.rgb_color = readColor(pbf.readVarint());
        obj.paint = 'rgb_color';
    } else if (tag === 2) {
        obj.linear_gradient_idx = pbf.readVarint();
        obj.paint = 'linear_gradient_idx';
    } else if (tag === 3) {
        obj.radial_gradient_idx = pbf.readVarint();
        obj.paint = 'radial_gradient_idx';
    } else if (tag === 5)
        obj.opacity = pbf.readVarint();
}
function readStroke(pbf, end) {
    return pbf.readFields(readStrokeField, {
        rgb_color: defaultColor,
        paint: 'rgb_color',
        dasharray: [],
        dashoffset: 0,
        miterlimit: 4,
        opacity: 255,
        width: 1,
        linecap: 1,
        linejoin: 1
    }, end);
}
function readColor(number) {
    return new Color((number >> 16 & 255) / 255, (number >> 8 & 255) / 255, (number & 255) / 255, 1);
}
function readStrokeField(tag, obj, pbf) {
    if (tag === 1) {
        obj.rgb_color = readColor(pbf.readVarint());
        obj.paint = 'rgb_color';
    } else if (tag === 2) {
        obj.linear_gradient_idx = pbf.readVarint();
        obj.paint = 'linear_gradient_idx';
    } else if (tag === 3) {
        obj.radial_gradient_idx = pbf.readVarint();
        obj.paint = 'radial_gradient_idx';
    } else if (tag === 5)
        pbf.readPackedFloat(obj.dasharray);
    else if (tag === 6)
        obj.dashoffset = pbf.readFloat();
    else if (tag === 7)
        obj.miterlimit = pbf.readFloat();
    else if (tag === 8)
        obj.opacity = pbf.readVarint();
    else if (tag === 9)
        obj.width = pbf.readFloat();
    else if (tag === 10)
        obj.linecap = pbf.readVarint();
    else if (tag === 11)
        obj.linejoin = pbf.readVarint();
}
function readLinearGradient(pbf, end) {
    return pbf.readFields(readLinearGradientField, {
        spread_method: 1,
        stops: [],
        x1: 0,
        y1: 0,
        x2: 1,
        y2: 0
    }, end);
}
function readLinearGradientField(tag, obj, pbf) {
    if (tag === 1)
        obj.transform = readTransform(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 2)
        obj.spread_method = pbf.readVarint();
    else if (tag === 3)
        obj.stops.push(readStop(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 4)
        obj.x1 = pbf.readFloat();
    else if (tag === 5)
        obj.y1 = pbf.readFloat();
    else if (tag === 6)
        obj.x2 = pbf.readFloat();
    else if (tag === 7)
        obj.y2 = pbf.readFloat();
}
function readStop(pbf, end) {
    return pbf.readFields(readStopField, {
        offset: 0,
        opacity: 255,
        rgb_color: defaultColor
    }, end);
}
function readStopField(tag, obj, pbf) {
    if (tag === 1)
        obj.offset = pbf.readFloat();
    else if (tag === 2)
        obj.opacity = pbf.readVarint();
    else if (tag === 3)
        obj.rgb_color = readColor(pbf.readVarint());
}
function readRadialGradient(pbf, end) {
    return pbf.readFields(readRadialGradientField, {
        spread_method: 1,
        stops: [],
        cx: 0.5,
        cy: 0.5,
        r: 0.5,
        fx: 0.5,
        fy: 0.5,
        fr: 0
    }, end);
}
function readRadialGradientField(tag, obj, pbf) {
    if (tag === 1)
        obj.transform = readTransform(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 2)
        obj.spread_method = pbf.readVarint();
    else if (tag === 3)
        obj.stops.push(readStop(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 4)
        obj.cx = pbf.readFloat();
    else if (tag === 5)
        obj.cy = pbf.readFloat();
    else if (tag === 6)
        obj.r = pbf.readFloat();
    else if (tag === 7)
        obj.fx = pbf.readFloat();
    else if (tag === 8)
        obj.fy = pbf.readFloat();
    else if (tag === 9)
        obj.fr = pbf.readFloat();
}
function readClipPath(pbf, end) {
    return pbf.readFields(readClipPathField, { children: [] }, end);
}
function readClipPathField(tag, obj, pbf) {
    if (tag === 1)
        obj.transform = readTransform(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 2)
        obj.clip_path_idx = pbf.readVarint();
    else if (tag === 3)
        obj.children.push(readNode(pbf, pbf.readVarint() + pbf.pos));
}
function readMask(pbf, end) {
    const mask = pbf.readFields(readMaskField, {
        left: 0,
        width: 20,
        mask_type: 1    /* MASK_TYPE_LUMINANCE */,
        children: []
    }, end);
    if (mask.height == null) {
        mask.height = mask.width;
    }
    if (mask.top == null) {
        mask.top = mask.left;
    }
    return mask;
}
function readMaskField(tag, obj, pbf) {
    if (tag === 1)
        obj.left = obj.top = pbf.readFloat();
    else if (tag === 2)
        obj.width = obj.height = pbf.readFloat();
    else if (tag === 3)
        obj.top = pbf.readFloat();
    else if (tag === 4)
        obj.height = pbf.readFloat();
    else if (tag === 5)
        obj.mask_type = pbf.readVarint();
    else if (tag === 6)
        obj.mask_idx = pbf.readVarint();
    else if (tag === 7)
        obj.children.push(readNode(pbf, pbf.readVarint() + pbf.pos));
}

class ColorReplacements {
    static calculate(params, variables) {
        const replacements = /* @__PURE__ */
        new Map();
        const variablesMap = /* @__PURE__ */
        new Map();
        if (Object.keys(params).length === 0) {
            return replacements;
        }
        variables.forEach(variable => {
            variablesMap.set(variable.name, variable.rgb_color || new Color(0, 0, 0));
        });
        for (const [key, value] of Object.entries(params)) {
            if (variablesMap.has(key)) {
                replacements.set(variablesMap.get(key).toStringPremultipliedAlpha(), value);
            } else {
                console.warn(`Ignoring unknown image variable "${ key }"`);
            }
        }
        return replacements;
    }
}
function getStyleColor(iconColor, opacity = 255, colorReplacements) {
    const alpha = opacity / 255;
    const serializedColor = iconColor.toStringPremultipliedAlpha();
    const color = colorReplacements.has(serializedColor) ? colorReplacements.get(serializedColor).clone() : iconColor.clone();
    color.a = alpha;
    return color.toString();
}
function getCanvas(width, height) {
    if (!offscreenCanvasSupported()) {
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        return canvas;
    }
    return new OffscreenCanvas(width, height);
}
function renderIcon(icon, options) {
    const colorReplacements = ColorReplacements.calculate(options.params, icon.metadata ? icon.metadata.variables : []);
    const tree = icon.usvg_tree;
    const naturalWidth = tree.width;
    const naturalHeight = tree.height;
    const tr = options.transform ? options.transform : new DOMMatrix();
    const renderedWidth = Math.max(1, Math.round(naturalWidth * tr.a));
    const renderedHeight = Math.max(1, Math.round(naturalHeight * tr.d));
    const finalTr = new DOMMatrix([
        renderedWidth / naturalWidth,
        0,
        0,
        renderedHeight / naturalHeight,
        0,
        0
    ]);
    const canvas = getCanvas(renderedWidth, renderedHeight);
    const context = canvas.getContext('2d');
    renderNodes(context, finalTr, tree, tree, colorReplacements);
    return context.getImageData(0, 0, renderedWidth, renderedHeight);
}
function renderNodes(context, transform, tree, parent, colorReplacements) {
    for (const node of parent.children) {
        renderNode(context, transform, tree, node, colorReplacements);
    }
}
function renderNode(context, transform, tree, node, colorReplacements) {
    if (node.group) {
        context.save();
        renderGroup(context, transform, tree, node.group, colorReplacements);
        context.restore();
    } else if (node.path) {
        context.save();
        renderPath(context, transform, tree, node.path, colorReplacements);
        context.restore();
    } else ;
}
function shouldIsolate(group, hasClipPath, hasMask) {
    return group.opacity !== 255 || hasClipPath || hasMask;
}
function renderGroup(context, transform, tree, group, colorReplacements) {
    const mask = group.mask_idx != null ? tree.masks[group.mask_idx] : null;
    const clipPath = group.clip_path_idx != null ? tree.clip_paths[group.clip_path_idx] : null;
    if (group.transform) {
        transform = makeTransform(group.transform).preMultiplySelf(transform);
    }
    if (!shouldIsolate(group, clipPath != null, mask != null)) {
        renderNodes(context, transform, tree, group, colorReplacements);
        return;
    }
    const groupCanvas = getCanvas(context.canvas.width, context.canvas.height);
    const groupContext = groupCanvas.getContext('2d');
    renderNodes(groupContext, transform, tree, group, colorReplacements);
    if (clipPath) {
        applyClipPath(groupContext, transform, tree, clipPath);
    }
    if (mask) {
        applyMask(groupContext, transform, tree, mask, colorReplacements);
    }
    context.globalAlpha = group.opacity / 255;
    context.drawImage(groupCanvas, 0, 0);
}
function renderPath(context, transform, tree, path, colorReplacements) {
    const path2d = makePath2d(path);
    context.setTransform(transform);
    if (path.paint_order === PaintOrder.PAINT_ORDER_FILL_AND_STROKE) {
        fillPath(context, tree, path, path2d, colorReplacements);
        strokePath(context, tree, path, path2d, colorReplacements);
    } else {
        strokePath(context, tree, path, path2d, colorReplacements);
        fillPath(context, tree, path, path2d, colorReplacements);
    }
}
function fillPath(context, tree, path, path2d, colorReplacements) {
    const fill = path.fill;
    if (!fill)
        return;
    const alpha = fill.opacity / 255;
    switch (fill.paint) {
    case 'rgb_color': {
            context.fillStyle = getStyleColor(fill.rgb_color, fill.opacity, colorReplacements);
            break;
        }
    case 'linear_gradient_idx':
        context.fillStyle = convertLinearGradient(context, tree.linear_gradients[fill.linear_gradient_idx], alpha, colorReplacements);
        break;
    case 'radial_gradient_idx':
        context.fillStyle = convertRadialGradient(context, tree.radial_gradients[fill.radial_gradient_idx], alpha, colorReplacements);
    }
    context.fill(path2d, getFillRule(path));
}
function getFillRule(path) {
    return path.rule === PathRule.PATH_RULE_NON_ZERO ? 'nonzero' : path.rule === PathRule.PATH_RULE_EVEN_ODD ? 'evenodd' : void 0;
}
function strokePath(context, tree, path, path2d, colorReplacements) {
    const stroke = path.stroke;
    if (!stroke)
        return;
    context.lineWidth = stroke.width;
    context.miterLimit = stroke.miterlimit;
    context.setLineDash(stroke.dasharray);
    context.lineDashOffset = stroke.dashoffset;
    const alpha = stroke.opacity / 255;
    switch (stroke.paint) {
    case 'rgb_color': {
            context.strokeStyle = getStyleColor(stroke.rgb_color, stroke.opacity, colorReplacements);
            break;
        }
    case 'linear_gradient_idx':
        context.strokeStyle = convertLinearGradient(context, tree.linear_gradients[stroke.linear_gradient_idx], alpha, colorReplacements);
        break;
    case 'radial_gradient_idx':
        context.strokeStyle = convertRadialGradient(context, tree.radial_gradients[stroke.radial_gradient_idx], alpha, colorReplacements);
    }
    switch (stroke.linejoin) {
    case LineJoin.LINE_JOIN_MITER_CLIP:
    case LineJoin.LINE_JOIN_MITER:
        context.lineJoin = 'miter';
        break;
    case LineJoin.LINE_JOIN_ROUND:
        context.lineJoin = 'round';
        break;
    case LineJoin.LINE_JOIN_BEVEL:
        context.lineJoin = 'bevel';
    }
    switch (stroke.linecap) {
    case LineCap.LINE_CAP_BUTT:
        context.lineCap = 'butt';
        break;
    case LineCap.LINE_CAP_ROUND:
        context.lineCap = 'round';
        break;
    case LineCap.LINE_CAP_SQUARE:
        context.lineCap = 'square';
    }
    context.stroke(path2d);
}
function convertLinearGradient(context, gradient, alpha, colorReplacements) {
    if (gradient.stops.length === 1) {
        const stop = gradient.stops[0];
        return getStyleColor(stop.rgb_color, stop.opacity * alpha, colorReplacements);
    }
    const tr = makeTransform(gradient.transform);
    const {x1, y1, x2, y2} = gradient;
    const start = tr.transformPoint(new DOMPoint(x1, y1));
    const end = tr.transformPoint(new DOMPoint(x2, y2));
    const linearGradient = context.createLinearGradient(start.x, start.y, end.x, end.y);
    for (const stop of gradient.stops) {
        linearGradient.addColorStop(stop.offset, getStyleColor(stop.rgb_color, stop.opacity * alpha, colorReplacements));
    }
    return linearGradient;
}
function convertRadialGradient(context, gradient, alpha, colorReplacements) {
    if (gradient.stops.length === 1) {
        const stop = gradient.stops[0];
        return getStyleColor(stop.rgb_color, stop.opacity * alpha, colorReplacements);
    }
    const tr = makeTransform(gradient.transform);
    const {fx, fy, cx, cy} = gradient;
    const start = tr.transformPoint(new DOMPoint(fx, fy));
    const end = tr.transformPoint(new DOMPoint(cx, cy));
    const uniformScale = (tr.a + tr.d) / 2;
    const r1 = gradient.r * uniformScale;
    const radialGradient = context.createRadialGradient(start.x, start.y, 0, end.x, end.y, r1);
    for (const stop of gradient.stops) {
        radialGradient.addColorStop(stop.offset, getStyleColor(stop.rgb_color, stop.opacity * alpha, colorReplacements));
    }
    return radialGradient;
}
function renderClipPath(context, transform, tree, clipPath) {
    const tr = clipPath.transform ? makeTransform(clipPath.transform).preMultiplySelf(transform) : transform;
    const groupCanvas = getCanvas(context.canvas.width, context.canvas.height);
    const groupContext = groupCanvas.getContext('2d');
    for (const node of clipPath.children) {
        if (node.group) {
            renderClipPath(groupContext, tr, tree, node.group);
        } else if (node.path) {
            const path = node.path;
            const path2d = new Path2D();
            path2d.addPath(makePath2d(path), tr);
            groupContext.fill(path2d, getFillRule(path));
        }
    }
    const selfClipPath = clipPath.clip_path_idx != null ? tree.clip_paths[clipPath.clip_path_idx] : null;
    if (selfClipPath) {
        applyClipPath(groupContext, tr, tree, selfClipPath);
    }
    context.globalCompositeOperation = 'source-over';
    context.drawImage(groupCanvas, 0, 0);
}
function applyClipPath(context, transform, tree, clipPath) {
    const maskCanvas = getCanvas(context.canvas.width, context.canvas.height);
    const maskContext = maskCanvas.getContext('2d');
    renderClipPath(maskContext, transform, tree, clipPath);
    context.globalCompositeOperation = 'destination-in';
    context.drawImage(maskCanvas, 0, 0);
}
function applyMask(context, transform, tree, mask, colorReplacements) {
    if (mask.children.length === 0) {
        return;
    }
    const childMask = mask.mask_idx != null ? tree.masks[mask.mask_idx] : null;
    if (childMask) {
        applyMask(context, transform, tree, childMask, colorReplacements);
    }
    const width = context.canvas.width;
    const height = context.canvas.height;
    const maskCanvas = getCanvas(width, height);
    const maskContext = maskCanvas.getContext('2d');
    const maskWidth = mask.width;
    const maskHeight = mask.height;
    const maskLeft = mask.left;
    const maskTop = mask.top;
    const clipPath = new Path2D();
    const rect = new Path2D();
    rect.rect(maskLeft, maskTop, maskWidth, maskHeight);
    clipPath.addPath(rect, transform);
    maskContext.clip(clipPath);
    for (const node of mask.children) {
        renderNode(maskContext, transform, tree, node, colorReplacements);
    }
    const maskImageData = maskContext.getImageData(0, 0, width, height);
    const maskData = maskImageData.data;
    if (mask.mask_type === MaskType.MASK_TYPE_LUMINANCE) {
        for (let i = 0; i < maskData.length; i += 4) {
            const r = maskData[i];
            const g = maskData[i + 1];
            const b = maskData[i + 2];
            const a = maskData[i + 3] / 255;
            const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            maskData[i + 3] = luminance * a;
        }
    }
    maskContext.putImageData(maskImageData, 0, 0);
    context.globalCompositeOperation = 'destination-in';
    context.drawImage(maskCanvas, 0, 0);
}
function makeTransform(transform) {
    return transform ? new DOMMatrix([
        transform.sx,
        transform.ky,
        transform.kx,
        transform.sy,
        transform.tx,
        transform.ty
    ]) : new DOMMatrix();
}
function makePath2d(path) {
    const path2d = new Path2D();
    const step = path.step;
    let x = path.diffs[0] * step;
    let y = path.diffs[1] * step;
    path2d.moveTo(x, y);
    for (let i = 0, j = 2; i < path.commands.length; i++) {
        switch (path.commands[i]) {
        case PathCommand.PATH_COMMAND_MOVE: {
                x += path.diffs[j++] * step;
                y += path.diffs[j++] * step;
                path2d.moveTo(x, y);
                break;
            }
        case PathCommand.PATH_COMMAND_LINE: {
                x += path.diffs[j++] * step;
                y += path.diffs[j++] * step;
                path2d.lineTo(x, y);
                break;
            }
        case PathCommand.PATH_COMMAND_QUAD: {
                const cpx = x + path.diffs[j++] * step;
                const cpy = y + path.diffs[j++] * step;
                x = cpx + path.diffs[j++] * step;
                y = cpy + path.diffs[j++] * step;
                path2d.quadraticCurveTo(cpx, cpy, x, y);
                break;
            }
        case PathCommand.PATH_COMMAND_CUBIC: {
                const cp1x = x + path.diffs[j++] * step;
                const cp1y = y + path.diffs[j++] * step;
                const cp2x = cp1x + path.diffs[j++] * step;
                const cp2y = cp1y + path.diffs[j++] * step;
                x = cp2x + path.diffs[j++] * step;
                y = cp2y + path.diffs[j++] * step;
                path2d.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
                break;
            }
        case PathCommand.PATH_COMMAND_CLOSE: {
                path2d.closePath();
                break;
            }
        default:
            assert(false, `Unknown path command "${ path.commands[i] }"`);
        }
    }
    return path2d;
}
function assert(condition, message) {
}

class LRUCache {
    /**
   * @param {number} capacity - max size of cache
   */
    constructor(capacity) {
        this.capacity = capacity;
        this.cache = /* @__PURE__ */
        new Map();
    }
    get(key) {
        if (!this.cache.has(key))
            return void 0;
        const value = this.cache.get(key);
        this.cache.delete(key);
        this.cache.set(key, value);
        return value;
    }
    put(key, value) {
        if (this.cache.has(key)) {
            this.cache.delete(key);
        } else if (this.cache.size === this.capacity) {
            this.cache.delete(this.cache.keys().next().value);
        }
        this.cache.set(key, value);
    }
    delete(key) {
        this.cache.delete(key);
    }
}

const MAX_CACHE_SIZE = 150;
class ImageRasterizer {
    constructor() {
        this.cacheMap = /* @__PURE__ */
        new Map();
        this.cacheDependenciesMap = /* @__PURE__ */
        new Map();
    }
    static _getImage(imageData) {
        return new RGBAImage(imageData, imageData.data);
    }
    getFromCache(imageIdWithOptions, scope, mapId) {
        if (!this.cacheMap.has(mapId)) {
            this.cacheMap.set(mapId, new LRUCache(MAX_CACHE_SIZE));
        }
        return this.cacheMap.get(mapId).get(makeFQID(imageIdWithOptions.serialize(), scope));
    }
    setInCache(imageIdWithOptions, image, scope, mapId) {
        if (!this.cacheDependenciesMap.has(mapId)) {
            this.cacheDependenciesMap.set(mapId, /* @__PURE__ */
            new Map());
        }
        if (!this.cacheMap.has(mapId)) {
            this.cacheMap.set(mapId, new LRUCache(MAX_CACHE_SIZE));
        }
        const cacheDependencies = this.cacheDependenciesMap.get(mapId);
        if (!cacheDependencies.get(makeFQID(imageIdWithOptions.id, scope))) {
            cacheDependencies.set(makeFQID(imageIdWithOptions.id, scope), /* @__PURE__ */
            new Set());
        }
        const cache = this.cacheMap.get(mapId);
        const serializedId = imageIdWithOptions.serialize();
        cacheDependencies.get(makeFQID(imageIdWithOptions.id, scope)).add(serializedId);
        cache.put(makeFQID(imageIdWithOptions.serialize(), scope), image);
    }
    removeImagesFromCacheByIds(ids, scope, mapId = '') {
        if (!this.cacheMap.has(mapId) || !this.cacheDependenciesMap.has(mapId)) {
            return;
        }
        const cache = this.cacheMap.get(mapId);
        const cacheDependencies = this.cacheDependenciesMap.get(mapId);
        for (const id of ids) {
            if (cacheDependencies.has(makeFQID(id, scope))) {
                for (const dependency of cacheDependencies.get(makeFQID(id, scope))) {
                    cache.delete(dependency);
                }
                cacheDependencies.delete(makeFQID(id, scope));
            }
        }
    }
    rasterize(imageIdWithOptions, image, scope, mapId, rasterize = renderIcon) {
        const cachedImage = this.getFromCache(imageIdWithOptions, scope, mapId);
        if (cachedImage) {
            return cachedImage.clone();
        }
        const imageData = rasterize(image.icon, imageIdWithOptions.options);
        const imageResult = ImageRasterizer._getImage(imageData);
        this.setInCache(imageIdWithOptions, imageResult, scope, mapId);
        return imageResult.clone();
    }
}

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];
            }
        };
    }
}
function loadVectorTile(params, callback, skipParse) {
    const key = JSON.stringify(params.request);
    const makeRequest = callback2 => {
        const request = getArrayBuffer(params.request, (err, data, cacheControl, expires) => {
            if (err) {
                callback2(err);
            } else if (data) {
                callback2(null, {
                    vectorTile: skipParse ? void 0 : new vectorTileExports.VectorTile(new Pbf$1(data)),
                    rawData: data,
                    cacheControl,
                    expires
                });
            }
        });
        return () => {
            request.cancel();
            callback2();
        };
    };
    if (params.data) {
        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);
}

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) {
            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) {
    const abX = bx - ax;
    const abY = by - ay;
    const abZ = bz - az;
    const acX = cx - ax;
    const acY = cy - ay;
    const acZ = cz - az;
    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;
    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;
}
const aabbSkirtPadding = 100;
class DemMinMaxQuadTree {
    constructor(dem_) {
        this.maximums = [];
        this.minimums = [];
        this.leaves = [];
        this.childOffsets = [];
        this.nodeCount = 0;
        this.dem = dem_;
        this._siblingOffset = [
            [
                0,
                0
            ],
            [
                1,
                0
            ],
            [
                0,
                1
            ],
            [
                1,
                1
            ]
        ];
        if (!this.dem)
            return;
        const mips = buildDemMipmap(this.dem);
        const maxLvl = mips.length - 1;
        const rootMip = mips[maxLvl];
        const min = rootMip.minimums;
        const max = rootMip.maximums;
        const leaves = rootMip.leaves;
        this._addNode(min[0], max[0], leaves[0]);
        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
            }];
        while (stack.length > 0) {
            const {
                idx,
                t: t2,
                nodex,
                nodey,
                depth
            } = stack.pop();
            if (this.leaves[idx]) {
                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;
                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);
                if (tMin === Number.MAX_VALUE) {
                    const hitPos = cjsExports.vec3.scaleAndAdd([], p, d, t2);
                    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 t2;
                } else {
                    return tMin;
                }
                continue;
            }
            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];
                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) {
                    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++;
                }
            }
            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;
        }
        if (!this.childOffsets[parentIdx])
            this.childOffsets[parentIdx] = this.nodeCount;
        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;
        }
        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);
}
function sampleElevation(fx, fy, dem) {
    const demSize = dem.dim;
    const x = clamp(fx * demSize - 0.5, 0, demSize - 1);
    const y = clamp(fy * demSize - 0.5, 0, demSize - 1);
    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;
    };
    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);
        const e1 = sampleElevation(blockBounds[2], blockBounds[1], dem);
        const e2 = sampleElevation(blockBounds[2], blockBounds[3], dem);
        const e3 = sampleElevation(blockBounds[0], blockBounds[3], dem);
        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);
    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;
            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) {
                mip.leaves.push(1);
            } else {
                mip.leaves.push(0);
            }
        }
        mips.push(mip);
    }
    return mips;
}

const unpackVectors = {
    mapbox: [
        6553.6,
        25.6,
        0.1,
        10000
    ],
    terrarium: [
        256,
        1,
        1 / 256,
        32768
    ]
};
function unpackMapbox(r, g, b) {
    return (r * 256 * 256 + g * 256 + b) / 10 - 10000;
}
function unpackTerrarium(r, g, b) {
    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, borderReady = false) {
        this.uid = uid;
        if (data.height !== data.width)
            throw new RangeError('DEM tiles must be square');
        if (sourceEncoding && sourceEncoding !== 'mapbox' && sourceEncoding !== 'terrarium') {
            warnOnce(`"${ sourceEncoding }" is not a valid encoding type. Valid types include "mapbox" and "terrarium".`);
            return;
        }
        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.floatView = new Float32Array(data.data.buffer);
        this.borderReady = borderReady;
        this._modifiedForSources = {};
        if (!borderReady) {
            for (let x = 0; x < dim; x++) {
                values[this._idx(-1, x)] = values[this._idx(0, x)];
                values[this._idx(dim, x)] = values[this._idx(dim - 1, x)];
                values[this._idx(x, -1)] = values[this._idx(x, 0)];
                values[this._idx(x, dim)] = values[this._idx(x, dim - 1)];
            }
            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)];
        }
        const unpack = sourceEncoding === 'terrarium' ? unpackTerrarium : unpackMapbox;
        for (let i = 0; i < values.length; ++i) {
            const byteIdx = i * 4;
            this.floatView[i] = unpack(this.pixels[byteIdx], this.pixels[byteIdx + 1], this.pixels[byteIdx + 2]);
        }
        this._timestamp = exported$1.now();
    }
    _buildQuadTree() {
        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);
        return this.floatView[idx];
    }
    set(x, y, v) {
        const idx = this._idx(x, y);
        const p = this.floatView[idx];
        this.floatView[idx] = v;
        return v - p;
    }
    static getUnpackVector(encoding) {
        return unpackVectors[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() {
        return new Float32Image({
            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'] });

function readTileHeader(pbf, end) {
    return pbf.readFields(readTileHeaderTag, {
        headerLength: 0,
        x: 0,
        y: 0,
        z: 0,
        layers: []
    }, end);
}
function readTileHeaderTag(tag, obj, pbf) {
    if (tag === 1)
        obj.headerLength = pbf.readFixed32();
    else if (tag === 2)
        obj.x = pbf.readVarint();
    else if (tag === 3)
        obj.y = pbf.readVarint();
    else if (tag === 4)
        obj.z = pbf.readVarint();
    else if (tag === 5)
        obj.layers.push(readLayer(pbf, pbf.readVarint() + pbf.pos));
}
function readFilter(pbf, end) {
    return pbf.readFields(readFilterTag, {}, end);
}
function readFilterTag(tag, obj, pbf) {
    if (tag === 1) {
        obj.delta_filter = readFilterDelta(pbf, pbf.readVarint() + pbf.pos);
        obj.filter = 'delta_filter';
    } else if (tag === 2) {
        pbf.readVarint();
        obj.filter = 'zigzag_filter';
    } else if (tag === 3) {
        pbf.readVarint();
        obj.filter = 'bitshuffle_filter';
    } else if (tag === 4) {
        pbf.readVarint();
        obj.filter = 'byteshuffle_filter';
    }
}
function readFilterDelta(pbf, end) {
    return pbf.readFields(readFilterDeltaTag, { blockSize: 0 }, end);
}
function readFilterDeltaTag(tag, obj, pbf) {
    if (tag === 1)
        obj.blockSize = pbf.readVarint();
}
function readCodec(pbf, end) {
    return pbf.readFields(readCodecTag, {}, end);
}
function readCodecTag(tag, obj, pbf) {
    if (tag === 1) {
        pbf.readVarint();
        obj.codec = 'gzip_data';
    } else if (tag === 2) {
        pbf.readVarint();
        obj.codec = 'jpeg_image';
    } else if (tag === 3) {
        pbf.readVarint();
        obj.codec = 'webp_image';
    } else if (tag === 4) {
        pbf.readVarint();
        obj.codec = 'png_image';
    }
}
function readDataIndexEntry(pbf, end) {
    return pbf.readFields(readDataIndexEntryTag, {
        firstByte: 0,
        lastByte: 0,
        filters: [],
        codec: null,
        offset: 0,
        scale: 0,
        bands: []
    }, end);
}
function readDataIndexEntryTag(tag, obj, pbf) {
    let deprecated_scale = 0;
    let deprecated_offset = 0;
    if (tag === 1)
        obj.firstByte = pbf.readFixed64();
    else if (tag === 2)
        obj.lastByte = pbf.readFixed64();
    else if (tag === 3)
        obj.filters.push(readFilter(pbf, pbf.readVarint() + pbf.pos));
    else if (tag === 4)
        obj.codec = readCodec(pbf, pbf.readVarint() + pbf.pos);
    else if (tag === 5)
        deprecated_offset = pbf.readFloat();
    else if (tag === 6)
        deprecated_scale = pbf.readFloat();
    else if (tag === 7)
        obj.bands.push(pbf.readString());
    else if (tag === 8)
        obj.offset = pbf.readDouble();
    else if (tag === 9)
        obj.scale = pbf.readDouble();
    if (obj.offset === 0)
        obj.offset = deprecated_offset;
    if (obj.scale === 0)
        obj.scale = deprecated_scale;
}
function readLayer(pbf, end) {
    return pbf.readFields(readLayerTag, {
        version: 0,
        name: '',
        units: '',
        tileSize: 0,
        buffer: 0,
        pixelFormat: 0,
        dataIndex: []
    }, end);
}
function readLayerTag(tag, obj, pbf) {
    if (tag === 1)
        obj.version = pbf.readVarint();
    else if (tag === 2)
        obj.name = pbf.readString();
    else if (tag === 3)
        obj.units = pbf.readString();
    else if (tag === 4)
        obj.tileSize = pbf.readVarint();
    else if (tag === 5)
        obj.buffer = pbf.readVarint();
    else if (tag === 6)
        obj.pixelFormat = pbf.readVarint();
    else if (tag === 7)
        obj.dataIndex.push(readDataIndexEntry(pbf, pbf.readVarint() + pbf.pos));
}
function readNumericData(pbf, values) {
    pbf.readFields(readNumericDataTag, values);
}
function readNumericDataTag(tag, values, pbf) {
    if (tag === 2) {
        readUint32Values(pbf, pbf.readVarint() + pbf.pos, values);
    } else if (tag === 3) {
        throw new Error('Not implemented');
    }
}
function readUint32Values(pbf, end, values) {
    return pbf.readFields(readUint32ValuesTag, values, end);
}
function readUint32ValuesTag(tag, values, pbf) {
    if (tag === 1) {
        let i = 0;
        const end = pbf.readVarint() + pbf.pos;
        while (pbf.pos < end) {
            values[i++] = pbf.readVarint();
        }
    }
}
function deltaDecode(data, shape) {
    if (shape.length !== 4) {
        throw new Error(`Expected data of dimension 4 but got ${ shape.length }.`);
    }
    let axisOffset = shape[3];
    for (let axis = 2; axis >= 1; axis--) {
        const start1 = axis === 1 ? 1 : 0;
        const start2 = axis === 2 ? 1 : 0;
        for (let i0 = 0; i0 < shape[0]; i0++) {
            const offset0 = shape[1] * i0;
            for (let i1 = start1; i1 < shape[1]; i1++) {
                const offset1 = shape[2] * (i1 + offset0);
                for (let i2 = start2; i2 < shape[2]; i2++) {
                    const offset2 = shape[3] * (i2 + offset1);
                    for (let i3 = 0; i3 < shape[3]; i3++) {
                        const offset3 = offset2 + i3;
                        data[offset3] += data[offset3 - axisOffset];
                    }
                }
            }
        }
        axisOffset *= shape[axis];
    }
    return data;
}
function zigzagDecode(data) {
    for (let i = 0, n = data.length; i < n; i++) {
        data[i] = data[i] >>> 1 ^ -(data[i] & 1);
    }
    return data;
}
function bitshuffleDecode(data, pixelFormat) {
    switch (pixelFormat) {
    case 'uint32':
        return data;
    case 'uint16':
        for (let i = 0; i < data.length; i += 2) {
            const a = data[i];
            const b = data[i + 1];
            data[i] = (a & 240) >> 4 | (a & 61440) >> 8 | (b & 240) << 4 | b & 61440;
            data[i + 1] = a & 15 | (a & 3840) >> 4 | (b & 15) << 8 | (b & 3840) << 4;
        }
        return data;
    case 'uint8':
        for (let i = 0; i < data.length; i += 4) {
            const a = data[i];
            const b = data[i + 1];
            const c = data[i + 2];
            const d = data[i + 3];
            data[i + 0] = (a & 192) >> 6 | (b & 192) >> 4 | (c & 192) >> 2 | (d & 192) >> 0;
            data[i + 1] = (a & 48) >> 4 | (b & 48) >> 2 | (c & 48) >> 0 | (d & 48) << 2;
            data[i + 2] = (a & 12) >> 2 | (b & 12) >> 0 | (c & 12) << 2 | (d & 12) << 4;
            data[i + 3] = (a & 3) >> 0 | (b & 3) << 2 | (c & 3) << 4 | (d & 3) << 6;
        }
        return data;
    default:
        throw new Error(`Invalid pixel format, "${ pixelFormat }"`);
    }
}
var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
var fleb = new u8([
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    1,
    1,
    1,
    1,
    2,
    2,
    2,
    2,
    3,
    3,
    3,
    3,
    4,
    4,
    4,
    4,
    5,
    5,
    5,
    5,
    0,
    /* unused */
    0,
    0,
    /* impossible */
    0
]);
var fdeb = new u8([
    0,
    0,
    0,
    0,
    1,
    1,
    2,
    2,
    3,
    3,
    4,
    4,
    5,
    5,
    6,
    6,
    7,
    7,
    8,
    8,
    9,
    9,
    10,
    10,
    11,
    11,
    12,
    12,
    13,
    13,
    /* unused */
    0,
    0
]);
var clim = new u8([
    16,
    17,
    18,
    0,
    8,
    7,
    9,
    6,
    10,
    5,
    11,
    4,
    12,
    3,
    13,
    2,
    14,
    1,
    15
]);
var freb = function (eb, start) {
    var b = new u16(31);
    for (var i = 0; i < 31; ++i) {
        b[i] = start += 1 << eb[i - 1];
    }
    var r = new i32(b[30]);
    for (var i = 1; i < 30; ++i) {
        for (var j = b[i]; j < b[i + 1]; ++j) {
            r[j] = j - b[i] << 5 | i;
        }
    }
    return {
        b,
        r
    };
};
var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0), fd = _b.b;
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
    var x = (i & 43690) >> 1 | (i & 21845) << 1;
    x = (x & 52428) >> 2 | (x & 13107) << 2;
    x = (x & 61680) >> 4 | (x & 3855) << 4;
    rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
}
var hMap = function (cd, mb, r) {
    var s = cd.length;
    var i = 0;
    var l = new u16(mb);
    for (; i < s; ++i) {
        if (cd[i])
            ++l[cd[i] - 1];
    }
    var le = new u16(mb);
    for (i = 1; i < mb; ++i) {
        le[i] = le[i - 1] + l[i - 1] << 1;
    }
    var co;
    {
        co = new u16(1 << mb);
        var rvb = 15 - mb;
        for (i = 0; i < s; ++i) {
            if (cd[i]) {
                var sv = i << 4 | cd[i];
                var r_1 = mb - cd[i];
                var v = le[cd[i] - 1]++ << r_1;
                for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
                    co[rev[v] >> rvb] = sv;
                }
            }
        }
    }
    return co;
};
var flt = new u8(288);
for (var i = 0; i < 144; ++i)
    flt[i] = 8;
for (var i = 144; i < 256; ++i)
    flt[i] = 9;
for (var i = 256; i < 280; ++i)
    flt[i] = 7;
for (var i = 280; i < 288; ++i)
    flt[i] = 8;
var fdt = new u8(32);
for (var i = 0; i < 32; ++i)
    fdt[i] = 5;
var flrm = /* @__PURE__ */
hMap(flt, 9);
var fdrm = /* @__PURE__ */
hMap(fdt, 5);
var max = function (a) {
    var m = a[0];
    for (var i = 1; i < a.length; ++i) {
        if (a[i] > m)
            m = a[i];
    }
    return m;
};
var bits = function (d, p, m) {
    var o = p / 8 | 0;
    return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
};
var bits16 = function (d, p) {
    var o = p / 8 | 0;
    return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
};
var shft = function (p) {
    return (p + 7) / 8 | 0;
};
var slc = function (v, s, e) {
    if (e == null || e > v.length)
        e = v.length;
    return new u8(v.subarray(s, e));
};
var ec = [
    'unexpected EOF',
    'invalid block type',
    'invalid length/literal',
    'invalid distance',
    'stream finished',
    'no stream handler',
    ,
    'no callback',
    'invalid UTF-8 data',
    'extra field too long',
    'date not in range 1980-2099',
    'filename too long',
    'stream finishing',
    'invalid zip data'    // determined by unknown compression method
];
var err = function (ind, msg, nt) {
    var e = new Error(msg || ec[ind]);
    e.code = ind;
    if (Error.captureStackTrace)
        Error.captureStackTrace(e, err);
    if (!nt)
        throw e;
    return e;
};
var inflt = function (dat, st, buf, dict) {
    var sl = dat.length, dl = 0;
    if (!sl || st.f && !st.l)
        return buf || new u8(0);
    var noBuf = !buf;
    var resize = noBuf || st.i != 2;
    var noSt = st.i;
    if (noBuf)
        buf = new u8(sl * 3);
    var cbuf = function (l2) {
        var bl = buf.length;
        if (l2 > bl) {
            var nbuf = new u8(Math.max(bl * 2, l2));
            nbuf.set(buf);
            buf = nbuf;
        }
    };
    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
    var tbts = sl * 8;
    do {
        if (!lm) {
            final = bits(dat, pos, 1);
            var type = bits(dat, pos + 1, 3);
            pos += 3;
            if (!type) {
                var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
                if (t > sl) {
                    if (noSt)
                        err(0);
                    break;
                }
                if (resize)
                    cbuf(bt + l);
                buf.set(dat.subarray(s, t), bt);
                st.b = bt += l, st.p = pos = t * 8, st.f = final;
                continue;
            } else if (type == 1)
                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
            else if (type == 2) {
                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                var tl = hLit + bits(dat, pos + 5, 31) + 1;
                pos += 14;
                var ldt = new u8(tl);
                var clt = new u8(19);
                for (var i = 0; i < hcLen; ++i) {
                    clt[clim[i]] = bits(dat, pos + i * 3, 7);
                }
                pos += hcLen * 3;
                var clb = max(clt), clbmsk = (1 << clb) - 1;
                var clm = hMap(clt, clb);
                for (var i = 0; i < tl;) {
                    var r = clm[bits(dat, pos, clbmsk)];
                    pos += r & 15;
                    var s = r >> 4;
                    if (s < 16) {
                        ldt[i++] = s;
                    } else {
                        var c = 0, n = 0;
                        if (s == 16)
                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                        else if (s == 17)
                            n = 3 + bits(dat, pos, 7), pos += 3;
                        else if (s == 18)
                            n = 11 + bits(dat, pos, 127), pos += 7;
                        while (n--)
                            ldt[i++] = c;
                    }
                }
                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                lbt = max(lt);
                dbt = max(dt);
                lm = hMap(lt, lbt);
                dm = hMap(dt, dbt);
            } else
                err(1);
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
        }
        if (resize)
            cbuf(bt + 131072);
        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
        var lpos = pos;
        for (;; lpos = pos) {
            var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
            pos += c & 15;
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
            if (!c)
                err(2);
            if (sym < 256)
                buf[bt++] = sym;
            else if (sym == 256) {
                lpos = pos, lm = null;
                break;
            } else {
                var add = sym - 254;
                if (sym > 264) {
                    var i = sym - 257, b = fleb[i];
                    add = bits(dat, pos, (1 << b) - 1) + fl[i];
                    pos += b;
                }
                var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
                if (!d)
                    err(3);
                pos += d & 15;
                var dt = fd[dsym];
                if (dsym > 3) {
                    var b = fdeb[dsym];
                    dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
                }
                if (pos > tbts) {
                    if (noSt)
                        err(0);
                    break;
                }
                if (resize)
                    cbuf(bt + 131072);
                var end = bt + add;
                if (bt < dt) {
                    var shift = dl - dt, dend = Math.min(dt, end);
                    if (shift + bt < 0)
                        err(3);
                    for (; bt < dend; ++bt)
                        buf[bt] = dict[shift + bt];
                }
                for (; bt < end; ++bt)
                    buf[bt] = buf[bt - dt];
            }
        }
        st.l = lm, st.p = lpos, st.b = bt, st.f = final;
        if (lm)
            final = 1, st.m = lbt, st.d = dm, st.n = dbt;
    } while (!final);
    return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
var et = /* @__PURE__ */
new u8(0);
var gzs = function (d) {
    if (d[0] != 31 || d[1] != 139 || d[2] != 8)
        err(6, 'invalid gzip data');
    var flg = d[3];
    var st = 10;
    if (flg & 4)
        st += (d[10] | d[11] << 8) + 2;
    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]);
    return st + (flg & 2);
};
var gzl = function (d) {
    var l = d.length;
    return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
function gunzipSync(data, opts) {
    var st = gzs(data);
    if (st + 8 > data.length)
        err(6, 'invalid gzip data');
    return inflt(data.subarray(st, -8), { i: 2 }, new u8(gzl(data)), opts);
}
var td = typeof TextDecoder != 'undefined' && /* @__PURE__ */
new TextDecoder();
var tds = 0;
try {
    td.decode(et, { stream: true });
    tds = 1;
} catch (e) {
}
const DS_TYPES = { gzip_data: 'gzip' };
function decompress(bytes, codec) {
    if (!globalThis.DecompressionStream) {
        switch (codec) {
        case 'gzip_data':
            return Promise.resolve(gunzipSync(bytes));
        }
    }
    const decompressionStreamType = DS_TYPES[codec];
    if (!decompressionStreamType) {
        throw new Error(`Unhandled codec: ${ codec }`);
    }
    const ds = new globalThis.DecompressionStream(decompressionStreamType);
    return new Response(new Blob([bytes]).stream().pipeThrough(ds)).arrayBuffer().then(buf => new Uint8Array(buf));
}
class MRTError extends Error {
    /**
   * @param {string} message - error message
   */
    constructor(message) {
        super(message);
        this.name = 'MRTError';
    }
}
const MRT_VERSION = 1;
const PIXEL_FORMAT = {
    0: 'uint32',
    1: 'uint32',
    2: 'uint16',
    3: 'uint8'
};
const PIXEL_FORMAT_TO_DIM_LEN = {
    uint32: 1,
    uint16: 2,
    uint8: 4
};
const PIXEL_FORMAT_TO_CTOR = {
    uint32: Uint32Array,
    uint16: Uint16Array,
    uint8: Uint8Array
};
let Pbf;
class MapboxRasterTile {
    /**
   * @param {number} cacheSize - number of decoded data chunks cached
   */
    constructor(cacheSize = 5) {
        this.x = NaN;
        this.y = NaN;
        this.z = NaN;
        this.layers = {};
        this._cacheSize = cacheSize;
    }
    /**
   * Get a layer instance by name
   * @param {string} layerName - name of requested layer
   * @return {RasterLayer} layer instance
   */
    getLayer(layerName) {
        const layer = this.layers[layerName];
        if (!layer)
            throw new MRTError(`Layer '${ layerName }' not found`);
        return layer;
    }
    /**
   * Get the length of the header from MRT bytes
   * @param {ArrayBuffer} buf - data buffer
   * @return {number} - length of header, in bytes
   */
    getHeaderLength(buf) {
        const bytes = new Uint8Array(buf);
        const view = new DataView(buf);
        if (bytes[0] !== 13)
            throw new MRTError('File is not a valid MRT.');
        return view.getUint32(1, true);
    }
    /**
   * @param {ArrayBuffer} buf - data buffer
   * @return {MapboxRasterTile} raster tile instance
   */
    parseHeader(buf) {
        const bytes = new Uint8Array(buf);
        const headerLength = this.getHeaderLength(buf);
        if (bytes.length < headerLength) {
            throw new MRTError(`Expected header with length >= ${ headerLength } but got buffer of length ${ bytes.length }`);
        }
        const pbf = new Pbf(bytes.subarray(0, headerLength));
        const meta = readTileHeader(pbf);
        if (!isNaN(this.x) && (this.x !== meta.x || this.y !== meta.y || this.z !== meta.z)) {
            throw new MRTError(`Invalid attempt to parse header ${ meta.z }/${ meta.x }/${ meta.y } for tile ${ this.z }/${ this.x }/${ this.y }`);
        }
        this.x = meta.x;
        this.y = meta.y;
        this.z = meta.z;
        for (const layer of meta.layers) {
            this.layers[layer.name] = new RasterLayer(layer, { cacheSize: this._cacheSize });
        }
        return this;
    }
    /**
   * Create a serializable representation of a data parsing task
   * @param {TDataRange} range - range of fetched data
   * @return {MRTDecodingBatch} processing task description
   */
    createDecodingTask(range) {
        const tasks = [];
        const layer = this.getLayer(range.layerName);
        for (let blockIndex of range.blockIndices) {
            const block = layer.dataIndex[blockIndex];
            const firstByte = block.firstByte - range.firstByte;
            const lastByte = block.lastByte - range.firstByte;
            if (layer._blocksInProgress.has(blockIndex))
                continue;
            const task = {
                layerName: layer.name,
                firstByte,
                lastByte,
                pixelFormat: layer.pixelFormat,
                blockIndex,
                blockShape: [block.bands.length].concat(layer.bandShape),
                buffer: layer.buffer,
                codec: block.codec.codec,
                filters: block.filters.map(f => f.filter)
            };
            layer._blocksInProgress.add(blockIndex);
            tasks.push(task);
        }
        const onCancel = () => {
            tasks.forEach(task => layer._blocksInProgress.delete(task.blockIndex));
        };
        const onComplete = (err2, results) => {
            tasks.forEach(task => layer._blocksInProgress.delete(task.blockIndex));
            if (err2)
                throw err2;
            results.forEach(result => {
                this.getLayer(result.layerName).processDecodedData(result);
            });
        };
        return new MRTDecodingBatch(tasks, onCancel, onComplete);
    }
}
class RasterLayer {
    /**
   * @param {object} pbf - layer configuration
   * @param {number} pbf.version - major version of MRT specification with which tile was encoded
   * @param {string} pbf.name - layer name
   * @param {string} pbf.units - layer units
   * @param {number} pbf.tileSize - number of rows and columns in raster data
   * @param {number} pbf.buffer - number of pixels around the edge of each tile
   * @param {number} pbf.pixelFormat - encoded pixel format enum indicating uint32, uint16, or uint8
   * @param {TPbfDataIndexEntry[]} pbf.dataIndex - index of data chunk byte offsets
   * @param {TRasterLayerConfig} [config] - Additional configuration parameters
   */
    constructor({version, name, units, tileSize, pixelFormat, buffer, dataIndex}, config) {
        this.version = version;
        if (this.version !== MRT_VERSION) {
            throw new MRTError(`Cannot parse raster layer encoded with MRT version ${ version }`);
        }
        this.name = name;
        this.units = units;
        this.tileSize = tileSize;
        this.buffer = buffer;
        this.pixelFormat = PIXEL_FORMAT[pixelFormat];
        this.dataIndex = dataIndex;
        this.bandShape = [
            tileSize + 2 * buffer,
            tileSize + 2 * buffer,
            PIXEL_FORMAT_TO_DIM_LEN[this.pixelFormat]
        ];
        const cacheSize = config ? config.cacheSize : 5;
        this._decodedBlocks = new LRUCache(cacheSize);
        this._blocksInProgress = /* @__PURE__ */
        new Set();
    }
    /**
   * Get the dimensionality of data based on pixelFormat
   * @return {number} length of vector dimension
   */
    get dimension() {
        return PIXEL_FORMAT_TO_DIM_LEN[this.pixelFormat];
    }
    /**
   * Return the layer cache size (readonly)
   * @return {number} cache size
   */
    get cacheSize() {
        return this._decodedBlocks.capacity;
    }
    /**
   * List all bands
   * @return {Array<string>} - list of bands
   */
    getBandList() {
        return this.dataIndex.map(({bands}) => bands).flat();
    }
    /**
   * Assimilate results of data loading task
   * @param {TDecodingResult} result - result of processing task
   */
    processDecodedData(result) {
        const key = result.blockIndex.toString();
        if (this._decodedBlocks.get(key))
            return;
        this._decodedBlocks.put(key, result.data);
    }
    /**
   * Find block for a band sequence index
   * @param {string|number} band - label or integer index of desired band
   * @return {TBlockReference} - index of block and index of band within block
   */
    getBlockForBand(band) {
        let blockBandStart = 0;
        switch (typeof band) {
        case 'string':
            for (const [blockIndex, block] of this.dataIndex.entries()) {
                for (const [blockBandIndex, bandName] of block.bands.entries()) {
                    if (bandName !== band)
                        continue;
                    return {
                        bandIndex: blockBandStart + blockBandIndex,
                        blockIndex,
                        blockBandIndex
                    };
                }
                blockBandStart += block.bands.length;
            }
            break;
        case 'number':
            for (const [blockIndex, block] of this.dataIndex.entries()) {
                if (band >= blockBandStart && band < blockBandStart + block.bands.length) {
                    return {
                        bandIndex: band,
                        blockIndex,
                        blockBandIndex: band - blockBandStart
                    };
                }
                blockBandStart += block.bands.length;
            }
            break;
        default:
            throw new MRTError(`Invalid band \`${ JSON.stringify(band) }\`. Expected string or integer.`);
        }
        throw new MRTError(`Band not found: ${ JSON.stringify(band) }`);
    }
    /**
   * Get the byte range of a data slice, for performing a HTTP Range fetch
   * @param {number[]} bandList - list of slices to be covered
   * @return {TDataRange} range of data
   */
    getDataRange(bandList) {
        let firstByte = Infinity;
        let lastByte = -Infinity;
        const blockIndices = [];
        const allBlocks = /* @__PURE__ */
        new Set();
        for (const band of bandList) {
            const {blockIndex} = this.getBlockForBand(band);
            if (blockIndex < 0) {
                throw new MRTError(`Invalid band: ${ JSON.stringify(band) }`);
            }
            const block = this.dataIndex[blockIndex];
            if (!blockIndices.includes(blockIndex)) {
                blockIndices.push(blockIndex);
            }
            allBlocks.add(blockIndex);
            firstByte = Math.min(firstByte, block.firstByte);
            lastByte = Math.max(lastByte, block.lastByte);
        }
        if (allBlocks.size > this.cacheSize) {
            throw new MRTError(`Number of blocks to decode (${ allBlocks.size }) exceeds cache size (${ this.cacheSize }).`);
        }
        return {
            layerName: this.name,
            firstByte,
            lastByte,
            blockIndices
        };
    }
    /**
   * Check if the specified band is valid
   * @param {number} band - sequence band
   * @return {boolean} - true if band exists in layer
   */
    hasBand(band) {
        const {blockIndex} = this.getBlockForBand(band);
        return blockIndex >= 0;
    }
    /**
   * Check if the layer has data for a given sequence band
   * @param {number} band - sequence band
   * @return {boolean} true if data is already available
   */
    hasDataForBand(band) {
        const {blockIndex} = this.getBlockForBand(band);
        return blockIndex >= 0 && !!this._decodedBlocks.get(blockIndex.toString());
    }
    /**
   * Get a typed array view of data
   * @param {number} band - sequence band
   * @return {TBandViewRGBA} view of raster layer
   */
    getBandView(band) {
        const {blockIndex, blockBandIndex} = this.getBlockForBand(band);
        const blockData = this._decodedBlocks.get(blockIndex.toString());
        if (!blockData) {
            throw new MRTError(`Data for band ${ JSON.stringify(band) } of layer "${ this.name }" not decoded.`);
        }
        const block = this.dataIndex[blockIndex];
        const bandDataLength = this.bandShape.reduce((a, b) => a * b, 1);
        const start = blockBandIndex * bandDataLength;
        const data = blockData.subarray(start, start + bandDataLength);
        const bytes = new Uint8Array(data.buffer).subarray(data.byteOffset, data.byteOffset + data.byteLength);
        return {
            data,
            bytes,
            tileSize: this.tileSize,
            buffer: this.buffer,
            pixelFormat: this.pixelFormat,
            dimension: this.dimension,
            offset: block.offset,
            scale: block.scale
        };
    }
}
MapboxRasterTile.setPbf = function (_Pbf) {
    Pbf = _Pbf;
};
class MRTDecodingBatch {
    /**
   * @param {TProcessingTask[]} tasks - processing tasks
   * @param {() => void} onCancel - callback invoked on cancel
   * @param {(err: Error, results: TDecodingResult[]) => void} onComplete - callback invoked on completion
   */
    constructor(tasks, onCancel, onComplete) {
        this.tasks = tasks;
        this._onCancel = onCancel;
        this._onComplete = onComplete;
        this._finalized = false;
    }
    /**
   * Cancel a processing task
   * return {void}
   */
    cancel() {
        if (this._finalized)
            return;
        this._onCancel();
        this._finalized = true;
    }
    /**
   * Complete a processing task
   * @param {Error} err - processing error, if encountered
   * @param {TDecodingResult[]} result - result of processing
   * return {void}
   */
    complete(err2, result) {
        if (this._finalized)
            return;
        this._onComplete(err2, result);
        this._finalized = true;
    }
}
MapboxRasterTile.performDecoding = function (buf, decodingBatch) {
    const bytes = new Uint8Array(buf);
    return Promise.all(decodingBatch.tasks.map(task => {
        const {layerName, firstByte, lastByte, pixelFormat, blockShape, blockIndex, filters, codec} = task;
        const taskBuf = bytes.subarray(firstByte, lastByte + 1);
        const dataLength = blockShape[0] * blockShape[1] * blockShape[2];
        const values = new Uint32Array(dataLength);
        let decoded;
        switch (codec) {
        case 'gzip_data': {
                decoded = decompress(taskBuf, codec).then(bytes2 => {
                    readNumericData(new Pbf(bytes2), values);
                    const Ctor = PIXEL_FORMAT_TO_CTOR[pixelFormat];
                    return new Ctor(values.buffer);
                });
                break;
            }
        default:
            throw new MRTError(`Unhandled codec: ${ codec }`);
        }
        return decoded.then(data => {
            for (let i = filters.length - 1; i >= 0; i--) {
                switch (filters[i]) {
                case 'delta_filter':
                    deltaDecode(data, blockShape);
                    break;
                case 'zigzag_filter':
                    zigzagDecode(data);
                    break;
                case 'bitshuffle_filter':
                    bitshuffleDecode(data, pixelFormat);
                    break;
                default:
                    throw new MRTError(`Unhandled filter "${ filters[i] }"`);
                }
            }
            return {
                layerName,
                blockIndex,
                data
            };
        }).catch(err2 => {
            throw err2;
        });
    }));
};

register(MRTDecodingBatch, 'MRTDecodingBatch', {
    omit: [
        '_onCancel',
        '_onComplete'
    ]
});

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 => {
        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 = /* @__PURE__ */
        ((() => {
            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()
        };
    });
}

function MeshoptDecoder(wasmPromise) {
    let instance;
    const ready = WebAssembly.instantiateStreaming(wasmPromise, {}).then(result => {
        instance = result.instance;
        instance.exports.__wasm_call_ctors();
    });
    function decode(instance2, fun, target, count, size, source, filter) {
        const sbrk = instance2.exports.sbrk;
        const count4 = count + 3 & ~3;
        const tp = sbrk(count4 * size);
        const sp = sbrk(source.length);
        const heap = new Uint8Array(instance2.exports.memory.buffer);
        heap.set(source, sp);
        const res = fun(tp, count, size, sp, source.length);
        if (res === 0 && filter) {
            filter(tp, count4, size);
        }
        target.set(heap.subarray(tp, tp + count * size));
        sbrk(tp - sbrk(0));
        if (res !== 0) {
            throw new Error(`Malformed buffer data: ${ res }`);
        }
    }
    const filters = {
        NONE: '',
        OCTAHEDRAL: 'meshopt_decodeFilterOct',
        QUATERNION: 'meshopt_decodeFilterQuat',
        EXPONENTIAL: 'meshopt_decodeFilterExp'
    };
    const decoders = {
        ATTRIBUTES: 'meshopt_decodeVertexBuffer',
        TRIANGLES: 'meshopt_decodeIndexBuffer',
        INDICES: 'meshopt_decodeIndexSequence'
    };
    return {
        ready,
        supported: true,
        decodeGltfBuffer(target, count, size, source, mode, filter) {
            decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
        }
    };
}

let dispatcher = null;
let dracoLoading;
let dracoUrl;
let draco;
let meshoptUrl;
let meshopt;
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());
    }
    dispatcher.broadcast('setDracoUrl', dracoUrl);
}
function waitForDraco() {
    if (draco)
        return;
    if (dracoLoading != null)
        return dracoLoading;
    dracoLoading = DracoDecoderModule(fetch(getDracoUrl()));
    return dracoLoading.then(module => {
        draco = module;
        dracoLoading = void 0;
    });
}
function getMeshoptUrl() {
    if (isWorker() && self.worker && self.worker.meshoptUrl) {
        return self.worker.meshoptUrl;
    }
    if (meshoptUrl)
        return meshoptUrl;
    const detector = new Uint8Array([
        0,
        97,
        115,
        109,
        1,
        0,
        0,
        0,
        1,
        4,
        1,
        96,
        0,
        0,
        3,
        3,
        2,
        0,
        0,
        5,
        3,
        1,
        0,
        1,
        12,
        1,
        0,
        10,
        22,
        2,
        12,
        0,
        65,
        0,
        65,
        0,
        65,
        0,
        252,
        10,
        0,
        0,
        11,
        7,
        0,
        65,
        0,
        253,
        15,
        26,
        11
    ]);
    if (typeof WebAssembly !== 'object') {
        throw new Error('WebAssembly not supported, cannot instantiate meshoptimizer');
    }
    meshoptUrl = WebAssembly.validate(detector) ? config.MESHOPT_SIMD_URL : config.MESHOPT_URL;
    return meshoptUrl;
}
function setMeshoptUrl(url) {
    meshoptUrl = exported$1.resolveURL(url);
    if (!dispatcher) {
        dispatcher = new Dispatcher(getGlobalWorkerPool(), new Evented());
    }
    dispatcher.broadcast('setMeshoptUrl', meshoptUrl);
}
function waitForMeshopt() {
    if (meshopt)
        return;
    const decoder = MeshoptDecoder(fetch(getMeshoptUrl()));
    return decoder.ready.then(() => {
        meshopt = decoder;
    });
}
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 config2 = primitive.extensions && primitive.extensions[DRACO_EXT];
    if (!config2)
        return;
    const decoder = new draco.Decoder();
    const bytes = getGLTFBytes(gltf, config2.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(config2.attributes)) {
        const attribute = decoder.GetAttributeByUniqueId(mesh, config2.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 ptr2 = draco._malloc(dataSize);
        decoder.GetAttributeDataArrayForAllPoints(mesh, attribute, draco[dracoTypeName], dataSize, ptr2);
        const buffer = draco.memory.buffer.slice(ptr2, ptr2 + dataSize);
        setAccessorBuffer(buffer, accessor, gltf);
        draco._free(ptr2);
    }
    decoder.destroy();
    mesh.destroy();
    delete primitive.extensions[DRACO_EXT];
}
const MESHOPT_EXT = 'EXT_meshopt_compression';
function loadMeshoptBuffer(bufferView, gltf) {
    if (!(bufferView.extensions && bufferView.extensions[MESHOPT_EXT]))
        return;
    const config2 = bufferView.extensions[MESHOPT_EXT];
    const byteOffset = config2.byteOffset || 0;
    const byteLength = config2.byteLength || 0;
    const buffer = gltf.buffers[config2.buffer];
    const source = new Uint8Array(buffer, byteOffset, byteLength);
    const target = new Uint8Array(config2.count * config2.byteStride);
    meshopt.decodeGltfBuffer(target, config2.count, config2.byteStride, source, config2.mode, config2.filter);
    bufferView.buffer = gltf.buffers.length;
    bufferView.byteOffset = 0;
    gltf.buffers[bufferView.buffer] = target.buffer;
    delete bufferView.extensions[MESHOPT_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 => createImageBitmap(blob)).then(imageBitmap => {
            gltf.images[index] = imageBitmap;
        });
    } else if (img.bufferView !== void 0) {
        const bytes = getGLTFBytes(gltf, img.bufferView);
        const blob = new Blob([bytes], { type: img.mimeType });
        return 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, bufferViews} = 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);
        const meshoptUsed = extensionsUsed && extensionsUsed.includes(MESHOPT_EXT);
        if (dracoUsed) {
            assetLoads.push(waitForDraco());
        }
        if (meshoptUsed) {
            assetLoads.push(waitForMeshopt());
        }
        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);
                    }
                }
            }
            if (meshoptUsed && meshes && bufferViews) {
                for (const bufferView of bufferViews) {
                    loadMeshoptBuffer(bufferView, 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);
}

function convertTextures(gltf, images) {
    const textures = [];
    const gl = 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 !== void 0)
                Object.assign(sampler, gltf.json.samplers[textureDesc.sampler]);
            textures.push({
                image: images[textureDesc.source],
                sampler,
                uploaded: false
            });
        }
    }
    return textures;
}
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 || {};
    const modelOcclusionTexture = occlusionTexture ? textures[occlusionTexture.index] : void 0;
    if (occlusionTexture && occlusionTexture.extensions && occlusionTexture.extensions['KHR_texture_transform'] && modelOcclusionTexture) {
        const transform = occlusionTexture.extensions['KHR_texture_transform'];
        modelOcclusionTexture.offsetScale = [
            transform.offset[0],
            transform.offset[1],
            transform.scale[0],
            transform.scale[1]
        ];
    }
    return {
        pbrMetallicRoughness: {
            // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
            baseColorFactor: new Color(...baseColorFactor),
            metallicFactor,
            roughnessFactor,
            baseColorTexture: baseColorTexture ? textures[baseColorTexture.index] : void 0,
            metallicRoughnessTexture: metallicRoughnessTexture ? textures[metallicRoughnessTexture.index] : void 0
        },
        doubleSided,
        emissiveFactor,
        alphaMode,
        alphaCutoff,
        normalTexture: normalTexture ? textures[normalTexture.index] : void 0,
        occlusionTexture: modelOcclusionTexture,
        emissionTexture: emissiveTexture ? textures[emissiveTexture.index] : void 0,
        defined: materialDesc.defined === void 0    // 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 getNormalizedScale(arrayType) {
    switch (arrayType) {
    case Int8Array:
        return 1 / 127;
    case Uint8Array:
        return 1 / 255;
    case Int16Array:
        return 1 / 32767;
    case Uint16Array:
        return 1 / 65535;
    default:
        return 1;
    }
}
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 itemBytes = GLTF_COMPONENTS[accessor.type] * ArrayType.BYTES_PER_ELEMENT;
    const stride = bufferView.byteStride && bufferView.byteStride !== itemBytes ? bufferView.byteStride / ArrayType.BYTES_PER_ELEMENT : GLTF_COMPONENTS[accessor.type];
    const bufferData = new ArrayType(buffer, offset, accessor.count * stride);
    return bufferData;
}
function setArrayData(gltf, accessor, array, buffer) {
    const ArrayType = GLTF_TO_ARRAY_TYPE[accessor.componentType];
    const norm = getNormalizedScale(ArrayType);
    const bufferView = gltf.json.bufferViews[accessor.bufferView];
    const numElements = bufferView.byteStride ? bufferView.byteStride / ArrayType.BYTES_PER_ELEMENT : GLTF_COMPONENTS[accessor.type];
    const float32Array = array.float32;
    const components = float32Array.length / array.capacity;
    for (let i = 0, count = 0; i < accessor.count * numElements; i += numElements, count += components) {
        for (let j = 0; j < components; j++) {
            float32Array[count + j] = buffer[i + j] * norm;
        }
    }
    array._trim();
}
function convertPrimitive(primitive, gltf, textures) {
    const indicesIdx = primitive.indices;
    const attributeMap = primitive.attributes;
    const mesh = {};
    mesh.indexArray = new StructArrayLayout3ui6();
    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();
    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();
    mesh.aabb = new Aabb(positionAccessor.min, positionAccessor.max);
    mesh.centroid = computeCentroid(indexArrayBuffer, vertexArrayBuffer);
    if (attributeMap.COLOR_0 !== void 0) {
        const colorAccessor = gltf.json.accessors[attributeMap.COLOR_0];
        const numElements = GLTF_COMPONENTS[colorAccessor.type];
        const colorArrayBuffer = getBufferData(gltf, colorAccessor);
        mesh.colorArray = numElements === 3 ? new StructArrayLayout3f12() : new StructArrayLayout4f16();
        mesh.colorArray.resize(colorAccessor.count);
        setArrayData(gltf, colorAccessor, mesh.colorArray, colorArrayBuffer);
    }
    if (attributeMap.NORMAL !== void 0) {
        mesh.normalArray = new StructArrayLayout3f12();
        const normalAccessor = gltf.json.accessors[attributeMap.NORMAL];
        mesh.normalArray.resize(normalAccessor.count);
        const normalArrayBuffer = getBufferData(gltf, normalAccessor);
        setArrayData(gltf, normalAccessor, mesh.normalArray, normalArrayBuffer);
    }
    if (attributeMap.TEXCOORD_0 !== void 0 && textures.length > 0) {
        mesh.texcoordArray = new StructArrayLayout2f8();
        const texcoordAccessor = gltf.json.accessors[attributeMap.TEXCOORD_0];
        mesh.texcoordArray.resize(texcoordAccessor.count);
        const texcoordArrayBuffer = getBufferData(gltf, texcoordAccessor);
        setArrayData(gltf, texcoordAccessor, mesh.texcoordArray, texcoordArrayBuffer);
    }
    if (attributeMap._FEATURE_ID_RGBA4444 !== void 0) {
        const featureAccesor = gltf.json.accessors[attributeMap._FEATURE_ID_RGBA4444];
        if (gltf.json.extensionsUsed && gltf.json.extensionsUsed.includes('EXT_meshopt_compression')) {
            mesh.featureData = getBufferData(gltf, featureAccesor);
        }
    }
    if (attributeMap._FEATURE_RGBA4444 !== void 0) {
        const featureAccesor = gltf.json.accessors[attributeMap._FEATURE_RGBA4444];
        mesh.featureData = new Uint32Array(getBufferData(gltf, featureAccesor).buffer);
    }
    const materialIdx = primitive.material;
    const materialDesc = materialIdx !== void 0 ? gltf.json.materials[materialIdx] : { defined: false };
    mesh.material = convertMaterial(materialDesc, textures);
    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 || cjsExports.mat4.fromRotationTranslationScale([], rotation || [
        0,
        0,
        0,
        1
    ], translation || [
        0,
        0,
        0
    ], scale || [
        1,
        1,
        1
    ]);
    if (mesh !== void 0) {
        node.meshes = meshes[mesh];
        const anchor = node.anchor = [
            0,
            0
        ];
        for (const mesh2 of node.meshes) {
            const {min, max} = mesh2.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 grid = new TriangleGridIndex(mesh.vertices, mesh.indices, 8, 256);
    const [min, max] = [
        grid.min.clone(),
        grid.max.clone()
    ];
    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;
    }
    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(x, y));
    }
    if (vertices.length < 3) {
        return null;
    }
    if (vertices.length > 1 && vertices[vertices.length - 1].equals(vertices[0])) {
        vertices.pop();
    }
    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();
    }
    const indices = earcut(vertices.flatMap(v => [
        v.x,
        v.y
    ]), []);
    if (indices.length === 0) {
        return null;
    }
    return {
        vertices,
        indices
    };
}
function parseNodeFootprintMesh(meshes, matrix) {
    const vertices = [];
    const indices = [];
    let baseVertex = 0;
    const tempVertex = [];
    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++) {
            tempVertex[0] = vArray[i * 3 + 0];
            tempVertex[1] = vArray[i * 3 + 1];
            tempVertex[2] = vArray[i * 3 + 2];
            cjsExports.vec3.transformMat4(tempVertex, tempVertex, matrix);
            vertices.push(new Point(tempVertex[0], tempVertex[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) {
            [indices[i + 1], indices[i + 2]] = [
                indices[i + 2],
                indices[i + 1]
            ];
        }
    }
    return {
        vertices,
        indices
    };
}
function convertFootprints(convertedNodes, sceneNodes, modelNodes) {
    const nodeFootprintLookup = {};
    const footprintNodeIndices = /* @__PURE__ */
    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;
    }
    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;
        }
        let fpMesh = null;
        if (node.id in nodeFootprintLookup) {
            fpMesh = parseNodeFootprintMesh(convertedNodes[nodeFootprintLookup[node.id]].meshes, node.matrix);
        }
        if (!fpMesh) {
            fpMesh = parseLegacyFootprintMesh(gltfNode);
        }
        if (fpMesh) {
            node.footprint = convertFootprint(fpMesh);
        }
    }
    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);
    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) {
    mesh.heightmap = new Float32Array(HEIGHTMAP_DIM * HEIGHTMAP_DIM);
    mesh.heightmap.fill(-1);
    const vertices = mesh.vertexArray.float32;
    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;
    for (const light of lights) {
        const fallOff = Math.min(10, Math.max(4, 1.3 * light.height)) * zScale;
        const tangent = [
            -light.normal[1],
            light.normal[0],
            0
        ];
        const horizontalSpread = Math.min(0.29, 0.1 * light.width / light.depth);
        const width = light.width - 2 * light.depth * zScale * (horizontalSpread + 0.01);
        const v1 = cjsExports.vec3.scaleAndAdd([], light.pos, tangent, width / 2);
        const v2 = cjsExports.vec3.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 = cjsExports.vec3.scaleAndAdd([], light.normal, tangent, horizontalSpread);
        cjsExports.vec3.scale(v1extrusion, v1extrusion, fallOff);
        const v2extrusion = cjsExports.vec3.scaleAndAdd([], light.normal, tangent, -horizontalSpread);
        cjsExports.vec3.scale(v2extrusion, v2extrusion, fallOff);
        cjsExports.vec3.add(v1extrusion, v1, v1extrusion);
        cjsExports.vec3.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]);
        mesh.vertexArray.emplaceBack(v0[0], v0[1], v0[2]);
        mesh.vertexArray.emplaceBack(v3[0], v3[1], v3[2]);
        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]);
        const halfWidth = width / fallOff / 2;
        mesh.colorArray.emplaceBack(-halfWidth - horizontalSpread, -1, halfWidth, 0.8);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -1, halfWidth, 0.8);
        mesh.colorArray.emplaceBack(-halfWidth, 0, halfWidth, 1.3);
        mesh.colorArray.emplaceBack(halfWidth, 0, halfWidth, 1.3);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -0.8, halfWidth, 0.7);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -0.8, halfWidth, 0.7);
        mesh.colorArray.emplaceBack(0, 0, halfWidth, 1.3);
        mesh.colorArray.emplaceBack(0, 0, halfWidth, 1.3);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -1.2, halfWidth, 0.8);
        mesh.colorArray.emplaceBack(halfWidth + horizontalSpread, -1.2, halfWidth, 0.8);
        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;
    }
    const material = {};
    material.defined = true;
    material.emissiveFactor = [
        0,
        0,
        0
    ];
    const pbrMetallicRoughness = {};
    pbrMetallicRoughness.baseColorFactor = Color.white;
    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;
    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;
}

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];
    }
}

const customProps = [
    'id',
    '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;
    }
    clone() {
        const feature = new Feature(this._vectorTileFeature, this._z, this._x, this._y, this.id);
        if (this.state)
            feature.state = Object.assign({}, this.state);
        if (this.layer)
            feature.layer = Object.assign({}, this.layer);
        if (this.source)
            feature.source = this.source;
        if (this.sourceLayer)
            feature.sourceLayer = this.sourceLayer;
        return feature;
    }
    get geometry() {
        if (this._geometry === void 0) {
            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: void 0,
            geometry: this.geometry,
            properties: this.properties
        };
        for (const key of customProps) {
            if (this[key] !== void 0)
                json[key] = this[key];
        }
        return json;
    }
}
class TargetFeature extends Feature {
    /**
   * @private
   */
    constructor(feature, variant) {
        super(feature._vectorTileFeature, feature._z, feature._x, feature._y, feature.id);
        if (feature.state)
            this.state = Object.assign({}, feature.state);
        this.target = variant.target;
        this.namespace = variant.namespace;
        if (variant.properties)
            this.properties = variant.properties;
        if (this.target && ('featuresetId' in this.target && !this.target.importId || 'layerId' in this.target)) {
            this.source = feature.source;
            this.sourceLayer = feature.sourceLayer;
            this.layer = feature.layer;
        }
    }
    toJSON() {
        const json = super.toJSON();
        json.target = this.target;
        json.namespace = this.namespace;
        return json;
    }
}

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;
        this.is3DTile = false;
        this.serializedLayersCache = /* @__PURE__ */
        new Map();
    }
    insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, layoutVertexArrayOffset = 0, envelopePadding = 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 (envelopePadding !== 0) {
                bbox[0] -= envelopePadding;
                bbox[1] -= envelopePadding;
                bbox[2] += envelopePadding;
                bbox[3] += envelopePadding;
            }
            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 vectorTileExports.VectorTile(new Pbf$1(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(query, params) {
        const {tilespaceGeometry, transform, tileTransform, pixelPosMatrix, availableImages} = params;
        this.loadVTLayers();
        this.serializedLayersCache.clear();
        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];
            if (index === previousIndex)
                continue;
            previousIndex = index;
            const match = this.featureIndexArray.get(index);
            let featureGeometry = null;
            if (this.is3DTile) {
                this.loadMatchingModelFeature(result, match, query, tilespaceGeometry, transform);
                continue;
            }
            const intersectionTest = (feature, styleLayer, featureState, layoutVertexArrayOffset = 0) => {
                if (!featureGeometry) {
                    featureGeometry = loadGeometry(feature, this.tileID.canonical, tileTransform);
                }
                return styleLayer.queryIntersectsFeature(tilespaceGeometry, feature, featureState, featureGeometry, this.z, transform, pixelPosMatrix, elevationHelper, layoutVertexArrayOffset);
            };
            this.loadMatchingFeature(result, match, query, availableImages, intersectionTest);
        }
        return result;
    }
    loadMatchingFeature(result, featureIndexData, query, availableImages, intersectionTest) {
        const {featureIndex, bucketIndex, sourceLayerIndex, layoutVertexArrayOffset} = featureIndexData;
        const layerIDs = this.bucketLayerIDs[bucketIndex];
        const queryLayers = query.layers;
        const queryLayerIDs = Object.keys(queryLayers);
        if (queryLayerIDs.length && !arraysIntersect(queryLayerIDs, layerIDs)) {
            return;
        }
        const querySourceCache = query.sourceCache;
        const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);
        const sourceLayer = this.vtLayers[sourceLayerName];
        const feature = sourceLayer.feature(featureIndex);
        const id = this.getId(feature, sourceLayerName);
        for (let l = 0; l < layerIDs.length; l++) {
            const layerId = layerIDs[l];
            if (!queryLayers[layerId])
                continue;
            const {styleLayer, targets} = queryLayers[layerId];
            let featureState = {};
            if (id !== void 0) {
                featureState = querySourceCache.getFeatureState(styleLayer.sourceLayer, id);
            }
            const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState, layoutVertexArrayOffset);
            if (!intersectionZ) {
                continue;
            }
            const geojsonFeature = new Feature(feature, this.z, this.x, this.y, id);
            geojsonFeature.tile = this.tileID.canonical;
            geojsonFeature.state = featureState;
            let serializedLayer = this.serializedLayersCache.get(layerId);
            if (!serializedLayer) {
                serializedLayer = styleLayer.serialize();
                serializedLayer.id = layerId;
                this.serializedLayersCache.set(layerId, serializedLayer);
            }
            geojsonFeature.source = serializedLayer.source;
            geojsonFeature.sourceLayer = serializedLayer['source-layer'];
            geojsonFeature.layer = extend$1({}, serializedLayer);
            geojsonFeature.layer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages);
            geojsonFeature.layer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages);
            let shouldInclude = false;
            for (const target of targets) {
                this.updateFeatureProperties(geojsonFeature, target);
                const {filter} = target;
                if (filter) {
                    feature.properties = geojsonFeature.properties;
                    if (filter.needGeometry) {
                        const evaluationFeature = toEvaluationFeature(feature, true);
                        if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {
                            continue;
                        }
                    } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
                        continue;
                    }
                }
                shouldInclude = true;
                if (target.targetId) {
                    this.addFeatureVariant(geojsonFeature, target);
                }
            }
            if (shouldInclude) {
                this.appendToResult(result, layerId, featureIndex, geojsonFeature, intersectionZ);
            }
        }
    }
    loadMatchingModelFeature(result, featureIndexData, query, tilespaceGeometry, transform) {
        const layerId = this.bucketLayerIDs[0][0];
        const queryLayers = query.layers;
        if (!queryLayers[layerId])
            return;
        const {styleLayer, targets} = queryLayers[layerId];
        if (styleLayer.type !== 'model')
            return;
        const tile = tilespaceGeometry.tile;
        const featureIndex = featureIndexData.featureIndex;
        const bucket = tile.getBucket(styleLayer);
        if (!bucket || !(bucket instanceof Tiled3dModelBucket))
            return;
        const model = loadMatchingModelFeature(bucket, featureIndex, tilespaceGeometry, transform);
        if (!model)
            return;
        const {z, x, y} = tile.tileID.canonical;
        const {feature, intersectionZ, position} = model;
        let featureState = {};
        if (feature.id !== void 0) {
            featureState = query.sourceCache.getFeatureState(styleLayer.sourceLayer, feature.id);
        }
        const geojsonFeature = new Feature({}, z, x, y, feature.id);
        geojsonFeature.tile = this.tileID.canonical;
        geojsonFeature.state = featureState;
        geojsonFeature.properties = feature.properties;
        geojsonFeature.geometry = {
            type: 'Point',
            coordinates: [
                position.lng,
                position.lat
            ]
        };
        let serializedLayer = this.serializedLayersCache.get(layerId);
        if (!serializedLayer) {
            serializedLayer = styleLayer.serialize();
            serializedLayer.id = layerId;
            this.serializedLayersCache.set(layerId, serializedLayer);
        }
        geojsonFeature.source = serializedLayer.source;
        geojsonFeature.sourceLayer = serializedLayer['source-layer'];
        geojsonFeature.layer = extend$1({}, serializedLayer);
        let shouldInclude = false;
        for (const target of targets) {
            this.updateFeatureProperties(geojsonFeature, target);
            const {filter} = target;
            if (filter) {
                feature.properties = geojsonFeature.properties;
                if (filter.needGeometry) {
                    if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature, this.tileID.canonical)) {
                        continue;
                    }
                } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
                    continue;
                }
            }
            shouldInclude = true;
            if (target.targetId) {
                this.addFeatureVariant(geojsonFeature, target);
            }
        }
        if (shouldInclude) {
            this.appendToResult(result, layerId, featureIndex, geojsonFeature, intersectionZ);
        }
    }
    updateFeatureProperties(feature, target, availableImages) {
        if (target.properties) {
            const transformedProperties = {};
            for (const name in target.properties) {
                const expression = target.properties[name];
                const value = expression.evaluate({ zoom: this.z }, feature._vectorTileFeature, feature.state, feature.tile, availableImages);
                if (value != null)
                    transformedProperties[name] = value;
            }
            feature.properties = transformedProperties;
        }
    }
    /**
   * Create a feature variant for a query target and add it to the original feature.
   *
   * @param {Feature} feature The original feature.
   * @param {QrfTarget} target The target to derive the feature for.
   * @returns {Feature} The derived feature.
   */
    addFeatureVariant(feature, target, availableImages) {
        const variant = {
            target: target.target,
            namespace: target.namespace,
            uniqueFeatureID: target.uniqueFeatureID
        };
        if (target.properties) {
            variant.properties = feature.properties;
        }
        feature.variants = feature.variants || {};
        feature.variants[target.targetId] = feature.variants[target.targetId] || [];
        feature.variants[target.targetId].push(variant);
    }
    appendToResult(result, layerID, featureIndex, geojsonFeature, intersectionZ) {
        let layerResult = result[layerID];
        if (layerResult === void 0) {
            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, bucketIndex, sourceLayerIndex, query, availableImages) {
        const result = {};
        this.loadVTLayers();
        for (const symbolFeatureIndex of symbolFeatureIndexes) {
            const featureIndexData = {
                bucketIndex,
                sourceLayerIndex,
                featureIndex: symbolFeatureIndex,
                layoutVertexArrayOffset: 0
            };
            this.loadMatchingFeature(result, featureIndexData, query, availableImages);
        }
        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 = !Array.isArray(this.promoteId) && typeof this.promoteId === 'object' ? this.promoteId[sourceLayerId] : this.promoteId;
            if (propName != null) {
                if (Array.isArray(propName)) {
                    if (!this.promoteIdExpression) {
                        const expression = createExpression(propName);
                        if (expression.result === 'success') {
                            this.promoteIdExpression = expression.value;
                        } else {
                            const error = expression.value.map(err => `${ err.key }: ${ err.message }`).join(', ');
                            warnOnce(`Failed to create expression for promoteId: ${ error }`);
                            return void 0;
                        }
                    }
                    if (!this.promoteIdExpression._evaluator) {
                        this.promoteIdExpression._evaluator = new EvaluationContext();
                    }
                    id = this.promoteIdExpression.evaluate({ zoom: 0 }, feature);
                } else {
                    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;
}

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

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;
}

exports.$ = isExpressionFilter;
exports.A = ResolvedImage;
exports.B = PATTERN_PADDING;
exports.C = ImagePosition;
exports.D = Dispatcher;
exports.E = Evented;
exports.F = potpack;
exports.G = ValidationWarning;
exports.H = getType;
exports.I = ImageRasterizer;
exports.J = extend;
exports.K = unbundle;
exports.L = supportsInterpolation;
exports.M = supportsPropertyExpression;
exports.N = supportsZoomExpression;
exports.O = isExpression;
exports.P = Point;
exports.Q = deepUnbundle;
exports.R = ResourceType;
exports.S = createPropertyExpression;
exports.T = Texture;
exports.U = createExpression;
exports.V = ValidationError;
exports.W = isStateConstant;
exports.X = isGlobalPropertyConstant;
exports.Y = isFeatureConstant;
exports.Z = CompoundExpression;
exports._ = csscolorparserExports;
exports.a = isMapboxHTTPCDNURL;
exports.a$ = Feature;
exports.a0 = isFunction;
exports.a1 = supportsLightExpression;
exports.a2 = validateModel;
exports.a3 = spec;
exports.a4 = Transitionable;
exports.a5 = Properties;
exports.a6 = DataConstantProperty;
exports.a7 = PositionProperty;
exports.a8 = EvaluationParameters;
exports.a9 = ZoomDependentExpression;
exports.aA = mercatorYfromLat;
exports.aB = DedupedRequest;
exports.aC = makeFQID;
exports.aD = loadVectorTile;
exports.aE = cacheEntryPossiblyAdded;
exports.aF = prevPowerOfTwo;
exports.aG = OverscaledTileID;
exports.aH = RasterStyleLayer;
exports.aI = RasterParticleStyleLayer;
exports.aJ = ImageSource;
exports.aK = getVideo;
exports.aL = UserManagedTexture;
exports.aM = loadGLTF;
exports.aN = convertModel;
exports.aO = Model;
exports.aP = bindAll;
exports.aQ = tileTransform;
exports.aR = lngFromMercatorX;
exports.aS = latFromMercatorY;
exports.aT = StructArrayLayout4i8;
exports.aU = StructArrayLayout3ui6;
exports.aV = uniqueId;
exports.aW = CollisionBoxArray;
exports.aX = SymbolBucket;
exports.aY = lazyLoadRTLTextPlugin;
exports.aZ = createFilter;
exports.a_ = toEvaluationFeature;
exports.aa = MercatorCoordinate;
exports.ab = cjsExports;
exports.ac = smoothstep;
exports.ad = PossiblyEvaluated;
exports.ae = globeToMercatorTransition;
exports.af = number;
exports.ag = EXTENT;
exports.ah = array$1;
exports.ai = degToRad;
exports.aj = Color;
exports.ak = DirectionProperty;
exports.al = polygonizeBounds;
exports.am = bufferConvexPolygon;
exports.an = getTilePoint;
exports.ao = polygonIntersectsBox;
exports.ap = getTileVec3;
exports.aq = Ray;
exports.ar = pixelsToTileUnits;
exports.as = getBounds;
exports.at = mercatorXfromLng;
exports.au = polygonContainsPoint;
exports.av = resample$1;
exports.aw = clamp;
exports.ax = GLOBE_RADIUS;
exports.ay = pick;
exports.az = LngLatBounds;
exports.b = isMapboxHTTPFontsURL;
exports.b$ = getProjectionInterpolationT;
exports.b0 = parseCacheControl;
exports.b1 = LineBucket;
exports.b2 = FillBucket;
exports.b3 = loadGeometry;
exports.b4 = StructArrayLayout2i4;
exports.b5 = StructArrayLayout1ui2;
exports.b6 = posAttributes;
exports.b7 = SegmentVector;
exports.b8 = earcut;
exports.b9 = boundsAttributes;
exports.bA = pointInFootprint;
exports.bB = getAnchorJustification;
exports.bC = evaluateVariableOffset;
exports.bD = getAnchorAlignment;
exports.bE = KDBush;
exports.bF = wrap$1;
exports.bG = getColumn;
exports.bH = mercatorZfromAltitude;
exports.bI = setColumn;
exports.bJ = UniformMatrix4f;
exports.bK = Uniform2f;
exports.bL = Uniform3f;
exports.bM = Uniform1f;
exports.bN = Uniform1i;
exports.bO = LngLat;
exports.bP = getProjection;
exports.bQ = UnwrappedTileID;
exports.bR = Frustum;
exports.bS = getScaleAdjustment;
exports.bT = CanonicalTileID;
exports.bU = aabbForTileOnGlobe;
exports.bV = tileAABB;
exports.bW = getAABBPointSquareDist;
exports.bX = MAX_MERCATOR_LATITUDE;
exports.bY = GLOBE_ZOOM_THRESHOLD_MAX;
exports.bZ = polesInViewport;
exports.b_ = getPixelsToTileUnitsMatrix;
exports.ba = transitionTileAABBinECEF;
exports.bb = globeNormalizeECEF;
exports.bc = tileCoordToECEF;
exports.bd = interpolateVec3;
exports.be = StructArrayLayout3i6;
exports.bf = posAttributesGlobeExt;
exports.bg = MapboxRasterTile;
exports.bh = Pbf$1;
exports.bi = getArrayBuffer;
exports.bj = values;
exports.bk = keysDifference;
exports.bl = asyncAll;
exports.bm = refProperties;
exports.bn = deepEqual;
exports.bo = calculateGlobeLabelMatrix;
exports.bp = evaluateSizeForZoom;
exports.bq = WritingMode;
exports.br = evaluateSizeForFeature;
exports.bs = updateGlobeVertexNormal;
exports.bt = addDynamicAttributes;
exports.bu = clipLine;
exports.bv = polygonIntersectsPolygon;
exports.bw = ONE_EM;
exports.bx = skipClipping;
exports.by = LayerTypeMask;
exports.bz = transformPointToTile;
exports.c = isMapboxHTTPSpriteURL;
exports.c$ = linePatternUniformValues;
exports.c0 = getProjectionAdjustments;
exports.c1 = getProjectionAdjustmentInverted;
exports.c2 = FrustumCorners;
exports.c3 = calculateGlobeMatrix;
exports.c4 = radToDeg;
exports.c5 = calculateKey;
exports.c6 = GLOBE_ZOOM_THRESHOLD_MIN;
exports.c7 = furthestTileCorner;
exports.c8 = GLOBE_SCALE_MATCH_LATITUDE;
exports.c9 = circumferenceAtLatitude;
exports.cA = UniformMatrix3f;
exports.cB = easeCubicInOut;
exports.cC = globeUseCustomAntiAliasing;
exports.cD = calculateGlobeMercatorMatrix;
exports.cE = tileCornersToBounds;
exports.cF = getLatitudinalLod;
exports.cG = getGridMatrix;
exports.cH = globeTileBounds;
exports.cI = globePoleMatrixForTile;
exports.cJ = Elevation;
exports.cK = Float32Image;
exports.cL = globeMetersToEcef;
exports.cM = sRGBToLinearAndScale;
exports.cN = globePixelsToTileUnits;
exports.cO = saturationFactor;
exports.cP = contrastFactor;
exports.cQ = COLOR_RAMP_RES$1;
exports.cR = globeECEFOrigin;
exports.cS = circleUniforms;
exports.cT = lineUniforms;
exports.cU = linePatternUniforms;
exports.cV = StructArrayLayout2f1f2i16;
exports.cW = collisionCircleLayout;
exports.cX = symbolSize;
exports.cY = circleDefinesValues;
exports.cZ = circleUniformValues;
exports.c_ = lineDefinesValues;
exports.ca = Uniform4f;
exports.cb = cartesianPositionToSpherical;
exports.cc = tileToMeter;
exports.cd = Aabb;
exports.ce = sphericalPositionToCartesian;
exports.cf = linearVec3TosRGB;
exports.cg = readIconSet;
exports.ch = registerForPluginStateChange;
exports.ci = getGlobalWorkerPool;
exports.cj = GlyphManager;
exports.ck = LocalGlyphMode;
exports.cl = getReferrer;
exports.cm = triggerPluginCompletionEvent;
exports.cn = stripQueryParameters;
exports.co = murmur3;
exports.cp = clone;
exports.cq = getNameFromFQID;
exports.cr = isFQID;
exports.cs = getScopeFromFQID;
exports.ct = validateCustomStyleLayer;
exports.cu = createStyleLayer;
exports.cv = filterObject;
exports.cw = TargetFeature;
exports.cx = evented;
exports.cy = makeRequest;
exports.cz = UniformColor;
exports.d = isMapboxHTTPTileJSONURL;
exports.d$ = FeatureIndex;
exports.d0 = lineUniformValues;
exports.d1 = nextPowerOfTwo;
exports.d2 = renderColorRamp;
exports.d3 = fillExtrusionHeightLift;
exports.d4 = neighborCoord;
exports.d5 = FillExtrusionBucket;
exports.d6 = HIDDEN_BY_REPLACEMENT;
exports.d7 = ELEVATION_OFFSET;
exports.d8 = ELEVATION_SCALE;
exports.d9 = COLOR_MIX_FACTOR;
exports.dA = ease;
exports.dB = mercatorScale;
exports.dC = latLngToECEF;
exports.dD = ecefToLatLng;
exports.dE = getZoomAdjustment;
exports.dF = isSafariWithAntialiasingBug;
exports.dG = setCacheLimits;
exports.dH = isLngLatBehindGlobe;
exports.dI = globeTiltAtLngLat;
exports.dJ = globeCenterToScreenPoint;
exports.dK = setRTLTextPlugin;
exports.dL = getRTLTextPluginStatus;
exports.dM = prewarm;
exports.dN = clearPrewarmedResources;
exports.dO = WorkerPool;
exports.dP = clearTileCache;
exports.dQ = WorkerClass;
exports.dR = getDracoUrl;
exports.dS = setDracoUrl;
exports.dT = getMeshoptUrl;
exports.dU = setMeshoptUrl;
exports.dV = register;
exports.dW = AlphaImage;
exports.dX = SDF_SCALE;
exports.dY = vectorTileExports;
exports.dZ = Ray2D;
exports.d_ = DictionaryCoder;
exports.da = createLayout;
exports.db = StructArrayLayout1i2;
exports.dc = COLOR_RAMP_RES;
exports.dd = globeDenormalizeECEF;
exports.de = StructArrayLayout3f12;
exports.df = StructArrayLayout5f20;
exports.dg = StructArrayLayout7f28;
exports.dh = mapValue;
exports.di = mulberry32;
exports.dj = getMetersPerPixelAtLatitude;
exports.dk = Texture3D;
exports.dl = convertModelMatrixForGlobe;
exports.dm = DefaultModelScale;
exports.dn = DEMSampler;
exports.dp = ModelTraits;
exports.dq = StructArrayLayout2ui4;
exports.dr = StructArrayLayout2f8;
exports.ds = earthRadius;
exports.dt = StructArrayLayout9f36;
exports.du = StructArrayLayout11f44;
exports.dv = ReplacementSource;
exports.dw = GlobeSharedBuffers;
exports.dx = ReplacementOrderLandmark;
exports.dy = bezier;
exports.dz = isFullscreen;
exports.e = config;
exports.e0 = LineAtlas;
exports.e1 = mapObject;
exports.e2 = ImageIdWithOptions;
exports.e3 = ImageAtlas;
exports.e4 = performSymbolLayout;
exports.e5 = DEMData;
exports.e6 = requirePointGeometry;
exports.e7 = requireVectorTile;
exports.e8 = requirePbf;
exports.e9 = getDefaultExportFromCjs;
exports.ea = load3DTile;
exports.eb = process3DTile;
exports.ec = Tiled3dModelBucket;
exports.ed = Actor;
exports.ee = plugin;
exports.ef = enforceCacheSizeLimit;
exports.f = isMapboxURL;
exports.g = getData;
exports.h = isMapboxHTTPURL;
exports.i = isMapboxHTTPStyleURL;
exports.j = b64DecodeUnicode;
exports.k = b64EncodeUnicode;
exports.l = extend$1;
exports.m = exported;
exports.n = getJSON;
exports.o = getImage;
exports.p = postData;
exports.q = exported$1;
exports.r = RGBAImage;
exports.s = storageAvailable;
exports.t = offscreenCanvasSupported;
exports.u = uuid;
exports.v = validateUuid;
exports.w = warnOnce;
exports.x = getImageRasterizerWorkerPool;
exports.y = ErrorEvent;
exports.z = Event;

}));

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

function getPerformanceMeasurement(request) {
    const url = request ? request.url.toString() : void 0;
    if (!url) {
        return [];
    }
    return performance.getEntriesByName(url);
}

function stringify(obj) {
    if (typeof obj === 'number' || typeof obj === 'boolean' || typeof obj === 'string' || obj === void 0 || obj === null)
        return JSON.stringify(obj);
    if (Array.isArray(obj)) {
        let str2 = '[';
        for (const val of obj) {
            str2 += `${ stringify(val) },`;
        }
        return `${ str2 }]`;
    }
    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.bm) {
        if (layer.type === 'model' && (k === 'minzoom' || k === 'maxzoom')) {
            continue;
        } else {
            key += `/${ stringify(layer[k]) }`;
        }
    }
    return key;
}
function containsKey(obj, key) {
    function recursiveSearch(item) {
        if (typeof item === 'string' && item === key) {
            return true;
        }
        if (Array.isArray(item)) {
            return item.some(recursiveSearch);
        }
        if (item && typeof item === 'object') {
            return Object.values(item).some(recursiveSearch);
        }
        return false;
    }
    return recursiveSearch(obj);
}
function groupByLayout(layers, cachedKeys) {
    const groups = {};
    for (let i = 0; i < layers.length; i++) {
        const layer = layers[i];
        let k = cachedKeys && cachedKeys[layer.id];
        if (!k) {
            k = getKey(layer);
            if (layer.type === 'line' && layer['paint']) {
                const lineWidth = layer['paint']['line-width'];
                if (containsKey(lineWidth, 'line-progress')) {
                    k += `/${ stringify(layer['paint']['line-width']) }`;
                }
            }
        }
        if (cachedKeys)
            cachedKeys[layer.id] = k;
        let group = groups[k];
        if (!group) {
            group = groups[k] = [];
        }
        group.push(layer);
    }
    const result = [];
    for (const k in groups) {
        result.push(groups[k]);
    }
    return result;
}

class StyleLayerIndex {
    constructor(layerConfigs) {
        this.keyCache = {};
        this._layers = {};
        this._layerConfigs = {};
        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.cu(layerConfig, this.scope, null, this._options);
            layer.compileFilter(options);
            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.bj(this._layerConfigs), this.keyCache);
        for (const layerConfigs2 of groups) {
            const layers = layerConfigs2.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);
        }
    }
}

const glyphPadding = 1;
const localGlyphPadding = glyphPadding * index.dX;
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} = index.F(bins);
        const image = new index.dW({
            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;
                index.dW.copy(src.bitmap, image, {
                    x: 0,
                    y: 0
                }, {
                    x: bin.x + padding,
                    y: bin.y + padding
                }, src.bitmap);
            }
        }
        this.image = image;
        this.positions = positions;
    }
}
index.dV(GlyphAtlas, 'GlyphAtlas');

const PROPERTY_ELEVATION_ID = '3d_elevation_id';
const HD_ELEVATION_SOURCE_LAYER = 'hd_road_elevation';
const MARKUP_ELEVATION_BIAS = 0.05;

class PropertyParser {
    constructor() {
        this._valid = false;
    }
    reset(feature) {
        this.feature = feature;
        this._valid = true;
        this._geometry = feature.loadGeometry();
        if (this._geometry.length === 0 || this._geometry[0].length === 0) {
            this._valid = false;
        }
        return this;
    }
    geometry(setter, convert) {
        if (this._valid) {
            setter(convert(this._geometry));
        }
        return this;
    }
    require(name, setter, convert) {
        return this.get(name, true, setter, convert);
    }
    optional(name, setter, convert) {
        return this.get(name, false, setter, convert);
    }
    success() {
        return this._valid;
    }
    get(name, required, setter, convert) {
        const value = this.feature.properties.hasOwnProperty(name) ? +this.feature.properties[name] : void 0;
        if (this._valid && value !== void 0) {
            if (convert) {
                setter(convert(value));
            } else {
                setter(value);
            }
        } else if (required) {
            this._valid = false;
        }
        return this;
    }
}
class VersionSchema {
    constructor(feature, vertex) {
        this.featureFunc = feature;
        this.vertexFunc = vertex;
    }
    parseFeature(parser, feature, out) {
        return this.featureFunc(parser, feature, out);
    }
    parseVertex(parser, feature, out) {
        return this.vertexFunc(parser, feature, out);
    }
}
const schemaV100 = new VersionSchema((parser, feature, out) => {
    return parser.reset(feature).require(PROPERTY_ELEVATION_ID, value => {
        out.id = value;
    }).optional('fixed_height_relative', value => {
        out.constantHeight = value;
    }, ElevationFeatureParser.decodeRelativeHeight).geometry(value => {
        out.bounds = value;
    }, ElevationFeatureParser.computeBounds).success();
}, (parser, feature, out) => {
    return parser.reset(feature).require(PROPERTY_ELEVATION_ID, value => {
        out.id = value;
    }).require('elevation_idx', value => {
        out.idx = value;
    }).require('extent', value => {
        out.extent = value;
    }).require('height_relative', value => {
        out.height = value;
    }, ElevationFeatureParser.decodeRelativeHeight).geometry(value => {
        out.position = value;
    }, ElevationFeatureParser.getPoint).success();
});
const schemaV101 = new VersionSchema((parser, feature, out) => {
    return parser.reset(feature).require(PROPERTY_ELEVATION_ID, value => {
        out.id = value;
    }).optional('fixed_height', value => {
        out.constantHeight = value;
    }, ElevationFeatureParser.decodeMetricHeight).geometry(value => {
        out.bounds = value;
    }, ElevationFeatureParser.computeBounds).success();
}, (parser, feature, out) => {
    return parser.reset(feature).require(PROPERTY_ELEVATION_ID, value => {
        out.id = value;
    }).require('elevation_idx', value => {
        out.idx = value;
    }).require('extent', value => {
        out.extent = value;
    }).require('height', value => {
        out.height = value;
    }, ElevationFeatureParser.decodeMetricHeight).geometry(value => {
        out.position = value;
    }, ElevationFeatureParser.getPoint).success();
});
class ElevationFeatureParser {
    static computeBounds(points) {
        const min = new index.P(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
        const max = new index.P(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
        for (const point of points[0]) {
            if (min.x > point.x)
                min.x = point.x;
            if (min.y > point.y)
                min.y = point.y;
            if (max.x < point.x)
                max.x = point.x;
            if (max.y < point.y)
                max.y = point.y;
        }
        return {
            min,
            max
        };
    }
    static getPoint(points) {
        return index.ab.vec2.fromValues(points[0][0].x, points[0][0].y);
    }
    static decodeRelativeHeight(height) {
        const RELATIVE_ELEVATION_TO_METERS = 5;
        const scaler = 1 / 10000;
        return height * scaler * RELATIVE_ELEVATION_TO_METERS;
    }
    static decodeMetricHeight(height) {
        const scaler = 1 / 10000;
        return height * scaler;
    }
    static parse(data) {
        const vertices = [];
        const features = [];
        const featureCount = data.length;
        const parser = new PropertyParser();
        for (let index$1 = 0; index$1 < featureCount; index$1++) {
            const feature = data.feature(index$1);
            const version = feature.properties.hasOwnProperty('version') ? String(feature.properties['version']) : void 0;
            const getVersionSchema = version2 => {
                if (!version2) {
                    return schemaV100;
                }
                if (version2 === '1.0.1') {
                    return schemaV101;
                }
                return void 0;
            };
            const schema = getVersionSchema(version);
            if (schema === void 0) {
                index.w(`Unknown elevation feature version number ${ version || '(unknown)' }`);
                continue;
            }
            const type = feature.properties.hasOwnProperty('type') ? feature.properties['type'] : void 0;
            if (!type) {
                continue;
            }
            if (index.dY.VectorTileFeature.types[feature.type] === 'Point' && type === 'curve_point') {
                const out = {};
                if (schema.parseVertex(parser, feature, out)) {
                    vertices.push(out);
                }
            } else if (index.dY.VectorTileFeature.types[feature.type] === 'Polygon' && type === 'curve_meta') {
                const out = {};
                if (schema.parseFeature(parser, feature, out)) {
                    features.push(out);
                }
            }
        }
        return {
            vertices,
            features
        };
    }
}

class ElevationFeature {
    constructor(id, safeArea, constantHeight, vertices, edges, metersToTile) {
        this.vertices = new Array();
        this.vertexProps = new Array();
        this.edges = new Array();
        this.edgeProps = new Array();
        this.id = id;
        this.heightRange = {
            min: constantHeight,
            max: constantHeight
        };
        this.safeArea = safeArea;
        this.constantHeight = constantHeight;
        if (this.constantHeight != null || this.constantHeight == null && vertices.length === 0)
            return;
        this.vertices = vertices;
        this.edges = edges;
        this.edges = this.edges.filter(edge => edge.a < this.vertices.length && edge.b < this.vertices.length && !index.ab.vec2.exactEquals(this.vertices[edge.a].position, this.vertices[edge.b].position));
        this.heightRange = {
            min: Number.POSITIVE_INFINITY,
            max: Number.NEGATIVE_INFINITY
        };
        for (const vertex of this.vertices) {
            this.vertexProps.push({ dir: index.ab.vec2.fromValues(0, 0) });
            this.heightRange.min = Math.min(this.heightRange.min, vertex.height);
            this.heightRange.max = Math.max(this.heightRange.max, vertex.height);
        }
        for (const edge of this.edges) {
            const a = this.vertices[edge.a].position;
            const b = this.vertices[edge.b].position;
            const vec = index.ab.vec2.subtract(index.ab.vec2.create(), b, a);
            const len = index.ab.vec2.length(vec);
            const dir = index.ab.vec2.scale(index.ab.vec2.create(), vec, 1 / len);
            this.edgeProps.push({
                vec,
                dir,
                len
            });
            const dirA = this.vertexProps[edge.a].dir;
            const dirB = this.vertexProps[edge.b].dir;
            index.ab.vec2.add(dirA, dirA, dir);
            index.ab.vec2.add(dirB, dirB, dir);
        }
        for (const props of this.vertexProps) {
            if (props.dir[0] !== 0 || props.dir[1] !== 0) {
                index.ab.vec2.normalize(props.dir, props.dir);
            }
        }
        this.tessellate(metersToTile);
    }
    pointElevation(point) {
        if (this.constantHeight != null) {
            return this.constantHeight;
        }
        const closestEdge = this.getClosestEdge(point);
        if (closestEdge == null) {
            return 0;
        }
        const [idx, t] = closestEdge;
        const aIdx = this.edges[idx].a;
        const bIdx = this.edges[idx].b;
        const lerp = (x, y, t2) => {
            return (1 - t2) * x + t2 * y;
        };
        return lerp(this.vertices[aIdx].height, this.vertices[bIdx].height, t);
    }
    getClosestEdge(point) {
        if (this.edges.length === 0) {
            return void 0;
        }
        let closestIdx = 0;
        let closestDist = Number.POSITIVE_INFINITY;
        let closestT = 0;
        const pointVec = index.ab.vec2.fromValues(point.x, point.y);
        for (let i = 0; i < this.edges.length; i++) {
            const edge = this.edges[i];
            const edgeDir = this.edgeProps[i].dir;
            const ray = new index.dZ(pointVec, this.edgeProps[i].dir);
            const a = this.vertices[edge.a].position;
            const b = this.vertices[edge.b].position;
            const pa = index.ab.vec2.create();
            const pb = index.ab.vec2.create();
            const paResult = ray.intersectsPlane(a, this.vertexProps[edge.a].dir, pa);
            const pbResult = ray.intersectsPlane(b, this.vertexProps[edge.b].dir, pb);
            if (!paResult || !pbResult) {
                continue;
            }
            const papb = index.ab.vec2.subtract(index.ab.vec2.create(), pb, pa);
            const paPoint = index.ab.vec2.subtract(index.ab.vec2.create(), pointVec, pa);
            const papbLen = index.ab.vec2.dot(papb, papb);
            const t = papbLen > 0 ? index.ab.vec2.dot(paPoint, papb) / papbLen : 0;
            const clampedT = index.aw(t, 0, 1);
            const distAlongLine = Math.abs((t - clampedT) * this.edgeProps[i].len);
            const aPoint = index.ab.vec2.subtract(index.ab.vec2.create(), pointVec, a);
            const perpDist = Math.abs(index.ab.vec2.dot(aPoint, index.ab.vec2.fromValues(edgeDir[1], -edgeDir[0])));
            const dist = distAlongLine + perpDist;
            if (dist < closestDist) {
                closestIdx = i;
                closestDist = dist;
                closestT = clampedT;
            }
        }
        return [
            closestIdx,
            closestT
        ];
    }
    tessellate(metersToTile) {
        const splitDistanceThreshold = MARKUP_ELEVATION_BIAS;
        for (let i = this.edges.length - 1; i >= 0; --i) {
            const a = this.edges[i].a;
            const b = this.edges[i].b;
            const {
                position: aTilePos,
                height: aHeight,
                extent: aExtent
            } = this.vertices[a];
            const {
                position: bTilePos,
                height: bHeight,
                extent: bExtent
            } = this.vertices[b];
            const aDir = this.vertexProps[a].dir;
            const bDir = this.vertexProps[b].dir;
            const aPos = index.ab.vec3.fromValues(aTilePos[0] / metersToTile, aTilePos[1] / metersToTile, aHeight);
            const bPos = index.ab.vec3.fromValues(bTilePos[0] / metersToTile, bTilePos[1] / metersToTile, bHeight);
            const aPerp = index.ab.vec3.fromValues(aDir[1], -aDir[0], 0);
            index.ab.vec3.scale(aPerp, aPerp, aExtent);
            const bPerp = index.ab.vec3.fromValues(bDir[1], -bDir[0], 0);
            index.ab.vec3.scale(bPerp, bPerp, bExtent);
            const lineDistSq = this.distSqLines(index.ab.vec3.fromValues(aPos[0] + 0.5 * aPerp[0], aPos[1] + 0.5 * aPerp[1], aPos[2] + 0.5 * aPerp[2]), index.ab.vec3.fromValues(bPos[0] - 0.5 * bPerp[0], bPos[1] - 0.5 * bPerp[1], bPos[2] - 0.5 * bPerp[2]), index.ab.vec3.fromValues(aPos[0] - 0.5 * aPerp[0], aPos[1] - 0.5 * aPerp[1], aPos[2] - 0.5 * aPerp[2]), index.ab.vec3.fromValues(bPos[0] + 0.5 * bPerp[0], bPos[1] + 0.5 * bPerp[1], bPos[2] + 0.5 * bPerp[2]));
            if (lineDistSq <= splitDistanceThreshold * splitDistanceThreshold) {
                continue;
            }
            const mid = this.vertices.length;
            const pos = index.ab.vec2.add(index.ab.vec2.create(), aTilePos, bTilePos);
            this.vertices.push({
                position: index.ab.vec2.scale(pos, pos, 0.5),
                height: 0.5 * (aHeight + bHeight),
                extent: 0.5 * (aExtent + bExtent)
            });
            const dir = index.ab.vec2.add(index.ab.vec2.create(), aDir, bDir);
            this.vertexProps.push({ dir: index.ab.vec2.normalize(dir, dir) });
            this.edges.splice(i, 1);
            this.edgeProps.splice(i, 1);
            this.edges.push({
                a,
                b: mid
            });
            this.edges.push({
                a: mid,
                b
            });
            const edgeVec = index.ab.vec2.subtract(index.ab.vec2.create(), this.vertices[mid].position, aTilePos);
            const edgeLen = index.ab.vec2.length(edgeVec);
            const edgeDir = index.ab.vec2.scale(index.ab.vec2.create(), edgeVec, 1 / edgeLen);
            const props = {
                vec: edgeVec,
                dir: edgeDir,
                len: edgeLen
            };
            this.edgeProps.push(props);
            this.edgeProps.push(props);
        }
    }
    distSqLines(aStart, aEnd, bStart, bEnd) {
        const aVec = index.ab.vec3.subtract(index.ab.vec3.create(), aEnd, aStart);
        const bVec = index.ab.vec3.subtract(index.ab.vec3.create(), bEnd, bStart);
        const abVec = index.ab.vec3.subtract(index.ab.vec3.create(), aStart, bStart);
        const a = index.ab.vec3.dot(aVec, aVec);
        const b = index.ab.vec3.dot(aVec, bVec);
        const c = index.ab.vec3.dot(aVec, abVec);
        const d = index.ab.vec3.dot(bVec, bVec);
        const e = index.ab.vec3.dot(bVec, abVec);
        const det = a * d - b * b;
        if (det === 0) {
            const t2 = index.ab.vec3.dot(abVec, bVec) / index.ab.vec3.dot(bVec, bVec);
            const vec = index.ab.vec3.lerp(index.ab.vec3.create(), bStart, bEnd, t2);
            return index.ab.vec3.squaredDistance(vec, aStart);
        }
        const s = (b * e - c * d) / det;
        const t = (a * e - b * c) / det;
        const vecA = index.ab.vec3.lerp(index.ab.vec3.create(), aStart, aEnd, s);
        const vecB = index.ab.vec3.lerp(index.ab.vec3.create(), bStart, bEnd, t);
        return index.ab.vec3.squaredDistance(vecA, vecB);
    }
}
class ElevationFeatures {
    static parseFrom(data, tileID) {
        const parsedFeatures = ElevationFeatureParser.parse(data);
        if (!parsedFeatures) {
            return [];
        }
        let {vertices, features} = parsedFeatures;
        const metersToTile = 1 / index.cc(tileID);
        features.sort((a, b) => a.id - b.id);
        vertices.sort((a, b) => a.id - b.id || a.idx - b.idx);
        vertices = vertices.filter((value, index, self) => index === self.findIndex(t => t.id === value.id && t.idx === value.idx));
        const elevationFeatures = new Array();
        let vCurrent = 0;
        const vEnd = vertices.length;
        for (const feature of features) {
            if (feature.constantHeight) {
                elevationFeatures.push(new ElevationFeature(feature.id, feature.bounds, feature.constantHeight));
                continue;
            }
            while (vCurrent !== vEnd && vertices[vCurrent].id < feature.id) {
                vCurrent++;
            }
            if (vCurrent === vEnd || vertices[vCurrent].id !== feature.id) {
                continue;
            }
            const outVertices = new Array();
            const outEdges = new Array();
            const vFirst = vCurrent;
            while (vCurrent !== vEnd && vertices[vCurrent].id === feature.id) {
                const vertex = vertices[vCurrent];
                outVertices.push({
                    position: vertex.position,
                    height: vertex.height,
                    extent: vertex.extent
                });
                if (vCurrent !== vFirst && vertices[vCurrent - 1].idx === vertex.idx - 1) {
                    const idx = vCurrent - vFirst;
                    outEdges.push({
                        a: idx - 1,
                        b: idx
                    });
                }
                vCurrent++;
            }
            elevationFeatures.push(new ElevationFeature(feature.id, feature.bounds, void 0, outVertices, outEdges, metersToTile));
        }
        return elevationFeatures;
    }
}
index.dV(ElevationFeature, 'ElevationFeature');

class WorkerTile {
    constructor(params) {
        this.tileID = new index.aG(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.lut = params.lut;
        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.request ? params.request.collectResourceTiming : false;
        this.promoteId = params.promoteId;
        this.isSymbolTile = params.isSymbolTile;
        this.tileTransform = index.aQ(params.tileID.canonical, params.projection);
        this.projection = params.projection;
        this.worldview = params.worldview;
        this.localizableLayerIds = params.localizableLayerIds;
        this.brightness = params.brightness;
        this.extraShadowCaster = !!params.extraShadowCaster;
        this.tessellationStep = params.tessellationStep;
        this.scaleFactor = params.scaleFactor;
    }
    parse(data, layerIndex, availableImages, actor, callback) {
        this.status = 'parsing';
        this.data = data;
        this.collisionBoxArray = new index.aW();
        const sourceLayerCoder = new index.d_(Object.keys(data.layers).sort());
        const featureIndex = new index.d$(this.tileID, this.promoteId);
        featureIndex.bucketLayerIDs = [];
        const buckets = {};
        const lineAtlas = new index.e0(256, 256);
        const options = {
            featureIndex,
            iconDependencies: {},
            patternDependencies: {},
            glyphDependencies: {},
            lineAtlas,
            availableImages,
            brightness: this.brightness,
            scaleFactor: this.scaleFactor,
            elevationFeatures: void 0
        };
        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) {
                index.w(`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 = [];
            let elevationDependency = false;
            for (let index = 0, currentFeatureIndex = 0; index < sourceLayer.length; index++) {
                const feature = sourceLayer.feature(index);
                const id = featureIndex.getId(feature, sourceLayerId);
                if (this.localizableLayerIds && this.localizableLayerIds.has(sourceLayerId)) {
                    const worldview = feature.properties ? feature.properties.worldview : null;
                    if (this.worldview && typeof worldview === 'string') {
                        if (worldview === 'all') {
                            feature.properties['$localized'] = true;
                        } else if (worldview.split(',').includes(this.worldview)) {
                            feature.properties['$localized'] = true;
                            feature.properties['worldview'] = this.worldview;
                        } else {
                            continue;
                        }
                    }
                }
                if (!elevationDependency && feature.properties && feature.properties.hasOwnProperty(PROPERTY_ELEVATION_ID)) {
                    elevationDependency = true;
                }
                features.push({
                    feature,
                    id,
                    index: currentFeatureIndex,
                    sourceLayerIndex
                });
                currentFeatureIndex++;
            }
            if (elevationDependency && data.layers.hasOwnProperty(HD_ELEVATION_SOURCE_LAYER)) {
                options.elevationFeatures = ElevationFeatures.parseFrom(data.layers[HD_ELEVATION_SOURCE_LAYER], this.canonical);
            }
            for (const family of layerFamilies[sourceLayerId]) {
                const layer = family[0];
                if (this.extraShadowCaster && (!layer.is3D() || layer.type === 'model')) {
                    continue;
                }
                if (this.isSymbolTile !== void 0 && 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,
                    // @ts-expect-error - TS2322 - Type 'Family<TypedStyleLayer>' is not assignable to type 'ClipStyleLayer[] & ModelStyleLayer[] & SymbolStyleLayer[] & LineStyleLayer[] & HeatmapStyleLayer[] & FillExtrusionStyleLayer[] & FillStyleLayer[] & CircleStyleLayer[]'.
                    layers: family,
                    zoom: this.zoom,
                    lut: this.lut,
                    canonical: this.canonical,
                    pixelRatio: this.pixelRatio,
                    overscaling: this.overscaling,
                    collisionBoxArray: this.collisionBoxArray,
                    sourceLayerIndex,
                    sourceID: this.source,
                    projection: this.projection.spec,
                    tessellationStep: this.tessellationStep
                });
                bucket.populate(features, options, this.tileID.canonical, this.tileTransform);
                featureIndex.bucketLayerIDs.push(family.map(l => index.aC(l.id, l.scope)));
            }
        }
        lineAtlas.trim();
        let error;
        let glyphMap;
        let iconMap;
        let patternMap;
        const taskMetadata = {
            type: 'maybePrepare',
            isSymbolTile: this.isSymbolTile,
            zoom: this.zoom
        };
        const maybePrepare = () => {
            if (error) {
                this.status = 'done';
                return callback(error);
            } else if (this.extraShadowCaster) {
                this.status = 'done';
                callback(null, {
                    buckets: index.bj(buckets).filter(b => !b.isEmpty()),
                    featureIndex,
                    collisionBoxArray: null,
                    glyphAtlasImage: null,
                    lineAtlas: null,
                    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 index.e3(iconMap, patternMap, this.lut);
                for (const key in buckets) {
                    const bucket = buckets[key];
                    if (bucket instanceof index.aX) {
                        recalculateLayers(bucket.layers, this.zoom, options.brightness, availableImages);
                        index.e4(bucket, glyphMap, glyphAtlas.positions, iconMap, imageAtlas.iconPositions, this.showCollisionBoxes, availableImages, this.tileID.canonical, this.tileZoom, this.projection, this.scaleFactor, this.pixelRatio, this.brightness);
                    } else if (bucket.hasPattern && (bucket instanceof index.b1 || bucket instanceof index.b2 || bucket instanceof index.d5)) {
                        recalculateLayers(bucket.layers, this.zoom, options.brightness, availableImages);
                        const imagePositions = imageAtlas.patternPositions;
                        bucket.addFeatures(options, this.tileID.canonical, imagePositions, availableImages, this.tileTransform, this.brightness);
                    }
                }
                this.status = 'done';
                callback(null, {
                    buckets: index.bj(buckets).filter(b => !b.isEmpty()),
                    featureIndex,
                    collisionBoxArray: this.collisionBoxArray,
                    glyphAtlasImage: glyphAtlas.image,
                    lineAtlas,
                    imageAtlas,
                    brightness: options.brightness
                });
            }
        };
        if (!this.extraShadowCaster) {
            const stacks = index.e1(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();
                    }
                }, void 0, 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) {
                        return;
                    }
                    error = err;
                    const newIconMap = {};
                    const needRasterization = Object.values(result).some(image => image.usvg);
                    if (needRasterization) {
                        this.rasterize(actor, newIconMap, result, options.iconDependencies, () => {
                            iconMap = newIconMap;
                            maybePrepare();
                        });
                    } else {
                        this.fillImageMap(newIconMap, options.iconDependencies, result);
                        iconMap = newIconMap;
                        maybePrepare();
                    }
                }, void 0, 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;
                        const newPatternMap = {};
                        const needRasterization = Object.values(result).some(image => image.usvg);
                        if (needRasterization) {
                            this.rasterize(actor, newPatternMap, result, options.patternDependencies, () => {
                                patternMap = newPatternMap;
                                maybePrepare();
                            });
                        } else {
                            this.fillImageMap(newPatternMap, options.patternDependencies, result);
                            patternMap = newPatternMap;
                            maybePrepare();
                        }
                    }
                }, void 0, false, taskMetadata);
            } else {
                patternMap = {};
            }
        }
        maybePrepare();
    }
    fillImageMap(imageMap, imageDependencies, images) {
        for (const imageName in images) {
            const requiredImages = imageDependencies[imageName] || [];
            for (const image of requiredImages) {
                if (!images[image.id].usvg) {
                    imageMap[image.serialize()] = images[image.id];
                }
            }
        }
    }
    getImageTaskQueue(imageMap, images, imageDependencies) {
        const imageRasterizationTasks = {};
        for (const imageName in images) {
            const requiredImagesWithOptions = imageDependencies[imageName] || [];
            for (const imageIdWithOptions of requiredImagesWithOptions) {
                const imageSerialized = imageIdWithOptions.serialize();
                if (!images[imageIdWithOptions.id].usvg) {
                    imageMap[imageSerialized] = images[imageIdWithOptions.id];
                } else if (!imageRasterizationTasks[imageSerialized]) {
                    imageRasterizationTasks[imageSerialized] = imageIdWithOptions;
                }
            }
        }
        return imageRasterizationTasks;
    }
    rasterize(actor, imageMap, images, imageDependencies, callback) {
        const imageTasks = this.getImageTaskQueue(imageMap, images, imageDependencies);
        this.rasterizeTask = actor.send('rasterizeImages', {
            scope: this.scope,
            imageTasks
        }, (err, result) => {
            if (!err) {
                for (const imageIdWithOptionsSerialized in result) {
                    const {id} = index.e2.deserializeFromString(imageIdWithOptionsSerialized);
                    const image = result[imageIdWithOptionsSerialized];
                    imageMap[imageIdWithOptionsSerialized] = Object.assign({}, images[id], { data: image });
                }
            }
            callback();
        });
    }
    cancelRasterize() {
        if (this.rasterizeTask) {
            this.rasterizeTask.cancel();
        }
    }
}
function recalculateLayers(layers, zoom, brightness, availableImages) {
    const parameters = new index.a8(zoom, { brightness });
    for (const layer of layers) {
        layer.recalculate(parameters, availableImages);
    }
}

class VectorTileWorkerSource extends index.E {
    /**
   * @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 || index.aD;
        this.loading = {};
        this.loaded = {};
        this.deduped = new index.aB(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];
            workerTile.cancelRasterize();
            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;
            workerTile.vectorTile = response.vectorTile || new index.dY.VectorTile(new index.bh(rawTileData));
            const parseTile = () => {
                const workerTileCallback = (err2, result) => {
                    if (err2 || !result)
                        return callback(err2);
                    const resourceTiming = {};
                    if (perf) {
                        const resourceTimingData = getPerformanceMeasurement(requestParam);
                        if (resourceTimingData.length > 0) {
                            resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));
                        }
                    }
                    callback(null, index.l({ 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;
        if (loaded && loaded[uid]) {
            const workerTile = loaded[uid];
            workerTile.scaleFactor = params.scaleFactor;
            workerTile.showCollisionBoxes = params.showCollisionBoxes;
            workerTile.projection = params.projection;
            workerTile.brightness = params.brightness;
            workerTile.tileTransform = index.aQ(params.tileID.canonical, params.projection);
            workerTile.extraShadowCaster = params.extraShadowCaster;
            workerTile.lut = params.lut;
            const done = (err, data) => {
                const reloadCallback = workerTile.reloadCallback;
                if (reloadCallback) {
                    delete workerTile.reloadCallback;
                    workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, reloadCallback);
                }
                callback(err, data);
            };
            if (workerTile.status === 'parsing') {
                workerTile.reloadCallback = done;
            } else if (workerTile.status === 'done') {
                if (workerTile.vectorTile) {
                    workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done);
                } else {
                    done();
                }
            }
        } else {
            callback(null, void 0);
        }
    }
    /**
   * 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();
    }
}

class RasterDEMTileWorkerSource {
    loadTile(params, callback) {
        const {uid, encoding, rawImageData, padding} = params;
        const imagePixels = ImageBitmap && rawImageData instanceof ImageBitmap ? this.getImageData(rawImageData, padding) : rawImageData;
        const dem = new index.e5(uid, imagePixels, encoding, padding < 1);
        callback(null, dem);
    }
    getImageData(imgBitmap, padding) {
        if (!this.offscreenCanvas || !this.offscreenCanvasContext) {
            this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height);
            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);
        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;
    }
}

index.bg.setPbf(index.bh);
class RasterArrayTileWorkerSource {
    decodeRasterArray({task, buffer}, callback) {
        index.bg.performDecoding(buffer, task).then(result => {
            callback(null, result);
        }, error => {
            callback(error);
        });
    }
}

const toGeoJSON = index.dY.VectorTileFeature.prototype.toGeoJSON;
class FeatureWrapper {
    constructor(feature) {
        this._feature = feature;
        this.extent = index.ag;
        this.type = feature.type;
        this.properties = feature.tags;
        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);
    }
}
class GeoJSONWrapper {
    constructor(features) {
        this.layers = { '_geojsonTileLayer': this };
        this.name = '_geojsonTileLayer';
        this.extent = index.ag;
        this.length = features.length;
        this._features = features;
    }
    feature(i) {
        return new FeatureWrapper(this._features[i]);
    }
}

const PAD = 64 / 4096;
const PAD_PX = 128;
class GeoJSONRT {
    constructor() {
        this.features = /* @__PURE__ */
        new Map();
    }
    clear() {
        this.features.clear();
    }
    load(features = [], cache) {
        for (const feature of features) {
            const id = feature.id;
            if (id == null)
                continue;
            let updated = this.features.get(id);
            if (updated)
                this.updateCache(updated, cache);
            if (!feature.geometry) {
                this.features.delete(id);
            } else {
                updated = convertFeature$1(feature);
                this.updateCache(updated, cache);
                this.features.set(id, updated);
            }
            this.updateCache(updated, cache);
        }
    }
    // clear all tiles that contain a given feature from the tile cache
    updateCache(feature, cache) {
        for (const {canonical, uid} of Object.values(cache)) {
            const {z, x, y} = canonical;
            const z2 = Math.pow(2, z);
            if (intersectsTile(feature, z2, x, y)) {
                delete cache[uid];
            }
        }
    }
    // return all features that fit in the tile (plus a small padding) by bbox; since dynamic mode is
    // for "small data, frequently updated" case, linear loop through all features should be fast enough
    getTile(z, tx, ty) {
        const z2 = Math.pow(2, z);
        const features = [];
        for (const feature of this.features.values()) {
            if (intersectsTile(feature, z2, tx, ty)) {
                features.push(outputFeature(feature, z2, tx, ty));
            }
        }
        return { features };
    }
    getFeatures() {
        return [...this.features.values()];
    }
}
function intersectsTile({minX, minY, maxX, maxY}, z2, tx, ty) {
    const x0 = (tx - PAD) / z2;
    const y0 = (ty - PAD) / z2;
    const x1 = (tx + 1 + PAD) / z2;
    const y1 = (ty + 1 + PAD) / z2;
    return minX < x1 && minY < y1 && maxX > x0 && maxY > y0;
}
function convertFeature$1(originalFeature) {
    const {id, geometry, properties} = originalFeature;
    if (!geometry)
        return;
    if (geometry.type === 'GeometryCollection') {
        throw new Error('GeometryCollection not supported in dynamic mode.');
    }
    const {type, coordinates} = geometry;
    const feature = {
        id,
        type: 1,
        geometry: [],
        tags: properties,
        minX: Infinity,
        minY: Infinity,
        maxX: -Infinity,
        maxY: -Infinity
    };
    const geom = feature.geometry;
    if (type === 'Point') {
        convertPoint$1(coordinates, geom, feature);
    } else if (type === 'MultiPoint') {
        for (const p of coordinates) {
            convertPoint$1(p, geom, feature);
        }
    } else if (type === 'LineString') {
        feature.type = 2;
        convertLine$1(coordinates, geom, feature);
    } else if (type === 'MultiLineString') {
        feature.type = 2;
        convertLines$1(coordinates, geom, feature);
    } else if (type === 'Polygon') {
        feature.type = 3;
        convertLines$1(coordinates, geom, feature, true);
    } else if (type === 'MultiPolygon') {
        feature.type = 3;
        for (const polygon of coordinates) {
            convertLines$1(polygon, geom, feature, true);
        }
    } else {
        throw new Error('Input data is not a valid GeoJSON object.');
    }
    return feature;
}
function convertPoint$1([lng, lat], out, bbox) {
    const x = index.at(lng);
    let y = index.aA(lat);
    y = y < 0 ? 0 : y > 1 ? 1 : y;
    out.push(x, y);
    bbox.minX = Math.min(bbox.minX, x);
    bbox.minY = Math.min(bbox.minY, y);
    bbox.maxX = Math.max(bbox.maxX, x);
    bbox.maxY = Math.max(bbox.maxY, y);
}
function convertLine$1(ring, out, bbox, isPolygon = false, isOuter = false) {
    const newLine = [];
    for (const p of ring) {
        convertPoint$1(p, newLine, bbox);
    }
    out.push(newLine);
    if (isPolygon)
        rewind$1(newLine, isOuter);
}
function convertLines$1(lines, out, bbox, isPolygon = false) {
    for (let i = 0; i < lines.length; i++) {
        convertLine$1(lines[i], out, bbox, isPolygon, i === 0);
    }
}
function outputFeature(feature, z2, tx, ty) {
    const {id, type, geometry, tags} = feature;
    const tileGeom = [];
    if (type === 1) {
        transformPoints(geometry, z2, tx, ty, tileGeom);
    } else {
        for (const ring of geometry) {
            transformAndClipLine(ring, z2, tx, ty, tileGeom);
        }
    }
    return {
        id,
        type,
        geometry: tileGeom,
        tags
    };
}
function transformPoints(line, z2, tx, ty, out) {
    for (let i = 0; i < line.length; i += 2) {
        const ox = Math.round(index.ag * (line[i + 0] * z2 - tx));
        const oy = Math.round(index.ag * (line[i + 1] * z2 - ty));
        out.push([
            ox,
            oy
        ]);
    }
}
function transformAndClipLine(line, z2, tx, ty, out) {
    const min = -PAD_PX;
    const max = index.ag + PAD_PX;
    let part;
    for (let i = 0; i < line.length - 2; i += 2) {
        let x0 = Math.round(index.ag * (line[i + 0] * z2 - tx));
        let y0 = Math.round(index.ag * (line[i + 1] * z2 - ty));
        let x1 = Math.round(index.ag * (line[i + 2] * z2 - tx));
        let y1 = Math.round(index.ag * (line[i + 3] * z2 - ty));
        const dx = x1 - x0;
        const dy = y1 - y0;
        if (x0 < min && x1 < min) {
            continue;
        } else if (x0 < min) {
            y0 = y0 + Math.round(dy * ((min - x0) / dx));
            x0 = min;
        } else if (x1 < min) {
            y1 = y0 + Math.round(dy * ((min - x0) / dx));
            x1 = min;
        }
        if (y0 < min && y1 < min) {
            continue;
        } else if (y0 < min) {
            x0 = x0 + Math.round(dx * ((min - y0) / dy));
            y0 = min;
        } else if (y1 < min) {
            x1 = x0 + Math.round(dx * ((min - y0) / dy));
            y1 = min;
        }
        if (x0 >= max && x1 >= max) {
            continue;
        } else if (x0 >= max) {
            y0 = y0 + Math.round(dy * ((max - x0) / dx));
            x0 = max;
        } else if (x1 >= max) {
            y1 = y0 + Math.round(dy * ((max - x0) / dx));
            x1 = max;
        }
        if (y0 >= max && y1 >= max) {
            continue;
        } else if (y0 >= max) {
            x0 = x0 + Math.round(dx * ((max - y0) / dy));
            y0 = max;
        } else if (y1 >= max) {
            x1 = x0 + Math.round(dx * ((max - y0) / dy));
            y1 = max;
        }
        if (!part || x0 !== part[part.length - 1][0] || y0 !== part[part.length - 1][1]) {
            part = [[
                    x0,
                    y0
                ]];
            out.push(part);
        }
        part.push([
            x1,
            y1
        ]);
    }
}
function rewind$1(ring, clockwise) {
    let area = 0;
    for (let 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 (let i = 0, len = ring.length; i < len / 2; i += 2) {
            const x = ring[i];
            const 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;
        }
    }
}

var vtPbf = {exports: {}};

var geojson_wrapper;
var hasRequiredGeojson_wrapper;

function requireGeojson_wrapper () {
	if (hasRequiredGeojson_wrapper) return geojson_wrapper;
	hasRequiredGeojson_wrapper = 1;
	var Point = index.e6();
	var VectorTileFeature = index.e7().VectorTileFeature;
	geojson_wrapper = GeoJSONWrapper;
	// conform to vectortile api
	function GeoJSONWrapper(features, options) {
	    this.options = options || {};
	    this.features = features;
	    this.length = features.length;
	}
	GeoJSONWrapper.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;
	return geojson_wrapper;
}

var hasRequiredVtPbf;

function requireVtPbf () {
	if (hasRequiredVtPbf) return vtPbf.exports;
	hasRequiredVtPbf = 1;
	var Pbf = index.e8();
	var GeoJSONWrapper = requireGeojson_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);
	        }
	    }
	}
	return vtPbf.exports;
}

var vtPbfExports = requireVtPbf();
var vtpbf = /*@__PURE__*/index.e9(vtPbfExports);

const defaultOptions$1 = {
    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$1), 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.bE(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;
}

// calculate simplification data using optimized Douglas-Peucker algorithm
function simplify(coords, first, last, sqTolerance) {
    let maxSqDist = sqTolerance;
    const mid = first + (last - first >> 1);
    let minPosToMid = last - first;
    let index;
    const ax = coords[first];
    const ay = coords[first + 1];
    const bx = coords[last];
    const by = coords[last + 1];
    for (let i = first + 3; i < last; i += 3) {
        const 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
            const 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) {
    let dx = bx - x;
    let dy = by - y;
    if (dx !== 0 || dy !== 0) {
        const 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) {
    const feature = {
        id: id == null ? null : id,
        type,
        geometry: geom,
        tags,
        minX: Infinity,
        minY: Infinity,
        maxX: -Infinity,
        maxY: -Infinity
    };
    if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
        calcLineBBox(feature, geom);
    } else if (type === 'Polygon') {
        // the outer ring (ie [0]) contains all inner rings
        calcLineBBox(feature, geom[0]);
    } else if (type === 'MultiLineString') {
        for (const line of geom) {
            calcLineBBox(feature, line);
        }
    } else if (type === 'MultiPolygon') {
        for (const polygon of geom) {
            // the outer ring (ie [0]) contains all inner rings
            calcLineBBox(feature, polygon[0]);
        }
    }
    return feature;
}
function calcLineBBox(feature, geom) {
    for (let 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) {
    const features = [];
    if (data.type === 'FeatureCollection') {
        for (let 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;
    const coords = geojson.geometry.coordinates;
    if (coords && coords.length === 0)
        return;
    const type = geojson.geometry.type;
    const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
    let geometry = [];
    let 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 (const p of coords) {
            convertPoint(p, 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 (const line of coords) {
                geometry = [];
                convertLine(line, 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 (const polygon of coords) {
            const newPolygon = [];
            convertLines(polygon, newPolygon, tolerance, true);
            geometry.push(newPolygon);
        }
    } else if (type === 'GeometryCollection') {
        for (const singleGeometry of geojson.geometry.geometries) {
            convertFeature(features, {
                id,
                geometry: singleGeometry,
                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]), projectY(coords[1]), 0);
}
function convertLine(ring, out, tolerance, isPolygon) {
    let x0, y0;
    let size = 0;
    for (let j = 0; j < ring.length; j++) {
        const x = projectX(ring[j][0]);
        const y = projectY(ring[j][1]);
        out.push(x, y, 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;
    }
    const 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 (let i = 0; i < rings.length; i++) {
        const geom = [];
        convertLine(rings[i], geom, tolerance, isPolygon);
        out.push(geom);
    }
}
function projectX(x) {
    return x / 360 + 0.5;
}
function projectY(y) {
    const sin = Math.sin(y * Math.PI / 180);
    const 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 vertical or horizontal axis-parallel lines:
 *     |        |
 *  ___|___     |     /
 * /   |   \____|____/
 *     |        |
 *
 * k1 and k2 are the line coordinates
 * axis: 0 for x, 1 for y
 * minAll and maxAll: minimum and maximum coordinate value for all features
 */
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
    const clipped = [];
    for (const feature of features) {
        const geometry = feature.geometry;
        let type = feature.type;
        const min = axis === 0 ? feature.minX : feature.minY;
        const 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;
        }
        let 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 (const polygon of geometry) {
                const newPolygon = [];
                clipLines(polygon, newPolygon, k1, k2, axis, true);
                if (newPolygon.length) {
                    newGeometry.push(newPolygon);
                }
            }
        }
        if (newGeometry.length) {
            if (options.lineMetrics && type === 'LineString') {
                for (const line of newGeometry) {
                    clipped.push(createFeature(feature.id, type, line, 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 (let i = 0; i < geom.length; i += 3) {
        const a = geom[i + axis];
        if (a >= k1 && a <= k2) {
            addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);
        }
    }
}
function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {
    let slice = newSlice(geom);
    const intersect = axis === 0 ? intersectX : intersectY;
    let len = geom.start;
    let segLen, t;
    for (let i = 0; i < geom.length - 3; i += 3) {
        const ax = geom[i];
        const ay = geom[i + 1];
        const az = geom[i + 2];
        const bx = geom[i + 3];
        const by = geom[i + 4];
        const a = axis === 0 ? ax : ay;
        const b = axis === 0 ? bx : by;
        let 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
    let last = geom.length - 3;
    const ax = geom[last];
    const ay = geom[last + 1];
    const az = geom[last + 2];
    const 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) {
    const slice = [];
    slice.size = line.size;
    slice.start = line.start;
    slice.end = line.end;
    return slice;
}
function clipLines(geom, newGeom, k1, k2, axis, isPolygon) {
    for (const line of geom) {
        clipLine(line, newGeom, k1, k2, axis, isPolygon, false);
    }
}
function addPoint(out, x, y, z) {
    out.push(x, y, z);
}
function intersectX(out, ax, ay, bx, by, x) {
    const t = (x - ax) / (bx - ax);
    addPoint(out, x, ay + (by - ay) * t, 1);
    return t;
}
function intersectY(out, ax, ay, bx, by, y) {
    const t = (y - ay) / (by - ay);
    addPoint(out, ax + (bx - ax) * t, y, 1);
    return t;
}

function wrap(features, options) {
    const buffer = options.buffer / options.extent;
    let merged = features;
    const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options);
    // left world copy
    const 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) {
    const newFeatures = [];
    for (let i = 0; i < features.length; i++) {
        const feature = features[i];
        const type = feature.type;
        let newGeometry;
        if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
            newGeometry = shiftCoords(feature.geometry, offset);
        } else if (type === 'MultiLineString' || type === 'Polygon') {
            newGeometry = [];
            for (const line of feature.geometry) {
                newGeometry.push(shiftCoords(line, offset));
            }
        } else if (type === 'MultiPolygon') {
            newGeometry = [];
            for (const polygon of feature.geometry) {
                const newPolygon = [];
                for (const line of polygon) {
                    newPolygon.push(shiftCoords(line, offset));
                }
                newGeometry.push(newPolygon);
            }
        }
        newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));
    }
    return newFeatures;
}
function shiftCoords(points, offset) {
    const newPoints = [];
    newPoints.size = points.size;
    if (points.start !== undefined) {
        newPoints.start = points.start;
        newPoints.end = points.end;
    }
    for (let 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;
    const z2 = 1 << tile.z;
    const tx = tile.x;
    const ty = tile.y;
    for (const feature of tile.features) {
        const geom = feature.geometry;
        const type = feature.type;
        feature.geometry = [];
        if (type === 1) {
            for (let j = 0; j < geom.length; j += 2) {
                feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));
            }
        } else {
            for (let j = 0; j < geom.length; j++) {
                const ring = [];
                for (let 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) {
    const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
    const tile = {
        features: [],
        numPoints: 0,
        numSimplified: 0,
        numFeatures: features.length,
        source: null,
        x: tx,
        y: ty,
        z,
        transformed: false,
        minX: 2,
        minY: 1,
        maxX: -1,
        maxY: 0
    };
    for (const feature of features) {
        addFeature(tile, feature, tolerance, options);
    }
    return tile;
}
function addFeature(tile, feature, tolerance, options) {
    const geom = feature.geometry;
    const type = feature.type;
    const simplified = [];
    tile.minX = Math.min(tile.minX, feature.minX);
    tile.minY = Math.min(tile.minY, feature.minY);
    tile.maxX = Math.max(tile.maxX, feature.maxX);
    tile.maxY = Math.max(tile.maxY, feature.maxY);
    if (type === 'Point' || type === 'MultiPoint') {
        for (let i = 0; i < geom.length; i += 3) {
            simplified.push(geom[i], 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 (let i = 0; i < geom.length; i++) {
            addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0);
        }
    } else if (type === 'MultiPolygon') {
        for (let k = 0; k < geom.length; k++) {
            const polygon = geom[k];
            for (let i = 0; i < polygon.length; i++) {
                addLine(simplified, polygon[i], tile, tolerance, true, i === 0);
            }
        }
    }
    if (simplified.length) {
        let tags = feature.tags || null;
        if (type === 'LineString' && options.lineMetrics) {
            tags = {};
            for (const 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;
        }
        const tileFeature = {
            geometry: simplified,
            type: type === 'Polygon' || type === 'MultiPolygon' ? 3 : type === 'LineString' || type === 'MultiLineString' ? 2 : 1,
            tags
        };
        if (feature.id !== null) {
            tileFeature.id = feature.id;
        }
        tile.features.push(tileFeature);
    }
}
function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
    const sqTolerance = tolerance * tolerance;
    if (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) {
        tile.numPoints += geom.length / 3;
        return;
    }
    const ring = [];
    for (let i = 0; i < geom.length; i += 3) {
        if (tolerance === 0 || geom[i + 2] > sqTolerance) {
            tile.numSimplified++;
            ring.push(geom[i], geom[i + 1]);
        }
        tile.numPoints++;
    }
    if (isPolygon)
        rewind(ring, isOuter);
    result.push(ring);
}
function rewind(ring, clockwise) {
    let area = 0;
    for (let 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 (let i = 0, len = ring.length; i < len / 2; i += 2) {
            const x = ring[i];
            const 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;
        }
    }
}

// final simplified tile generation
const defaultOptions = {
    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)
};
class GeoJSONVT {
    constructor(data, options) {
        options = this.options = extend(Object.create(defaultOptions), options);
        const 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.');
        // projects and adds simplification info
        let features = convert(data, options);
        // tiles and tileCoords are part of the public API
        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;
        }
        // wraps features (ie extreme west and extreme east)
        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));
        }
    }
    // splits features from a parent tile to sub-tiles.
    // z, x, and y are the coordinates of the parent tile
    // cz, cx, and cy are the coordinates of the target tile
    //
    // If no target tile is specified, splitting stops when we reach the maximum
    // zoom or the number of points is low as specified in the options.
    splitTile(features, z, x, y, cz, cx, cy) {
        const stack = [
            features,
            z,
            x,
            y
        ];
        const options = this.options;
        const 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();
            const z2 = 1 << z;
            const id = toID(z, x, y);
            let 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,
                    x,
                    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');
                    }
                    const 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 == null) {
                // 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 if (z === options.maxZoom || z === cz) {
                // stop tiling if we reached base zoom or our target tile zoom
                continue;
            } else if (cz != null) {
                // stop tiling if it's not an ancestor of the target tile
                const zoomSteps = cz - z;
                if (x !== cx >> zoomSteps || y !== cy >> zoomSteps)
                    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
            const k1 = 0.5 * options.buffer / options.extent;
            const k2 = 0.5 - k1;
            const k3 = 0.5 + k1;
            const k4 = 1 + k1;
            let tl = null;
            let bl = null;
            let tr = null;
            let br = null;
            let left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
            let 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);
        }
    }
    getTile(z, x, y) {
        z = +z;
        x = +x;
        y = +y;
        const options = this.options;
        const {extent, debug} = options;
        if (z < 0 || z > 24)
            return null;
        const z2 = 1 << z;
        x = x + z2 & z2 - 1;
        // wrap tile x coordinate
        const 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);
        let z0 = z;
        let x0 = x;
        let y0 = y;
        let parent;
        while (!parent && z0 > 0) {
            z0--;
            x0 = x0 >> 1;
            y0 = y0 >> 1;
            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);
            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 (const i in src)
        dest[i] = src[i];
    return dest;
}
function geojsonvt(data, options) {
    return new GeoJSONVT(data, options);
}

function loadGeoJSONTile(params, callback) {
    const canonical = params.tileID.canonical;
    if (!this._geoJSONIndex) {
        callback(null, null);
        return;
    }
    const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);
    if (!geoJSONTile) {
        callback(null, null);
        return;
    }
    const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features);
    let pbf = vtpbf(geojsonWrapper);
    if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {
        pbf = new Uint8Array(pbf);
    }
    callback(null, {
        vectorTile: geojsonWrapper,
        rawData: pbf.buffer
    });
}
class GeoJSONWorkerSource extends VectorTileWorkerSource {
    /**
   * @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;
        }
        this._dynamicIndex = new GeoJSONRT();
    }
    /**
   * 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 {
                try {
                    if (params.filter) {
                        const compiled = index.U(params.filter, {
                            type: 'boolean',
                            'property-type': 'data-driven',
                            overridable: false,
                            transition: false
                        });
                        if (compiled.result === 'error')
                            throw new Error(compiled.value.map(err2 => `${ err2.key }: ${ err2.message }`).join(', '));
                        data.features = data.features.filter(feature => compiled.value.evaluate({ zoom: 0 }, feature));
                    }
                    if (params.dynamic) {
                        if (data.type === 'Feature')
                            data = {
                                type: 'FeatureCollection',
                                features: [data]
                            };
                        if (!params.append) {
                            this._dynamicIndex.clear();
                            this.loaded = {};
                        }
                        this._dynamicIndex.load(data.features, this.loaded);
                        if (params.cluster)
                            data.features = this._dynamicIndex.getFeatures();
                    } else {
                        this.loaded = {};
                    }
                    this._geoJSONIndex = params.cluster ? new Supercluster(getSuperclusterOptions(params)).load(data.features) : params.dynamic ? this._dynamicIndex : geojsonvt(data, params.geojsonVtOptions);
                } catch (err2) {
                    return callback(err2);
                }
                const result = {};
                if (perf) {
                    const resourceTimingData = getPerformanceMeasurement(requestParam);
                    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]) {
            if (params.partial) {
                return callback(null, void 0);
            }
            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
   */
    loadGeoJSON(params, callback) {
        if (params.request) {
            index.n(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.U(mapExpression);
        const reduceExpressionParsed = index.U(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, clusterProperties2) => {
        feature.properties = clusterProperties2;
        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.aG(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.aG(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.d$(tileID, params.promoteId);
        featureIndex.bucketLayerIDs = [];
        featureIndex.is3DTile = true;
        return index.ea(data).then(gltf => {
            if (!gltf)
                return callback(new Error('Could not parse tile'));
            const nodes = index.eb(gltf, 1 / index.cc(params.tileID.canonical));
            const hasMapboxMeshFeatures = gltf.json.extensionsUsed && gltf.json.extensionsUsed.includes('MAPBOX_mesh_features') || gltf.json.asset.extras && gltf.json.asset.extras['MAPBOX_mesh_features'];
            const hasMeshoptCompression = gltf.json.extensionsUsed && gltf.json.extensionsUsed.includes('EXT_meshopt_compression');
            const parameters = new index.a8(this.zoom, { brightness: this.brightness });
            for (const sourceLayerId in layerFamilies) {
                for (const family of layerFamilies[sourceLayerId]) {
                    const layer = family[0];
                    featureIndex.bucketLayerIDs.push(family.map(l => index.aC(l.id, l.scope)));
                    layer.recalculate(parameters, []);
                    const bucket = new index.ec(family, nodes, tileID, hasMapboxMeshFeatures, hasMeshoptCompression, this.brightness, featureIndex);
                    if (!hasMapboxMeshFeatures)
                        bucket.needsUpload = true;
                    buckets.push(bucket);
                    bucket.evaluate(layer);
                }
            }
            this.status = 'done';
            callback(null, {
                buckets,
                featureIndex,
                collisionBoxArray: null,
                glyphAtlasImage: null,
                lineAtlas: null,
                imageAtlas: null,
                brightness: null
            });
        }).catch(err => callback(new Error(err.message)));
    }
}
class Tiled3dModelWorkerSource {
    constructor(actor, layerIndex, availableImages, isSpriteLoaded, loadVectorData, brightness) {
        this.actor = actor;
        this.layerIndex = layerIndex;
        this.availableImages = availableImages;
        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.bi(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 = (err2, result) => {
                workerTile.status = 'done';
                this.loaded = this.loaded || {};
                this.loaded[uid] = workerTile;
                if (err2 || !result)
                    callback(err2);
                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') {
                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();
    }
}

class MapWorker {
    constructor(self2) {
        this.self = self2;
        this.actor = new index.ed(self2, this);
        this.layerIndexes = {};
        this.availableImages = {};
        this.isSpriteLoaded = {};
        this.imageRasterizer = new index.I();
        this.projections = {};
        this.defaultProjection = index.bP({ name: 'mercator' });
        this.workerSourceTypes = {
            vector: VectorTileWorkerSource,
            geojson: GeoJSONWorkerSource,
            'batched-model': Tiled3dModelWorkerSource
        };
        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.self.registerRTLTextPlugin = rtlTextPlugin => {
            if (index.ee.isParsed()) {
                throw new Error('RTL text plugin already registered.');
            }
            index.ee['applyArabicShaping'] = rtlTextPlugin.applyArabicShaping;
            index.ee['processBidirectionalText'] = rtlTextPlugin.processBidirectionalText;
            index.ee['processStyledBidirectionalText'] = rtlTextPlugin.processStyledBidirectionalText;
        };
    }
    clearCaches(mapId, unused, callback) {
        delete this.layerIndexes[mapId];
        delete this.availableImages[mapId];
        delete this.workerSources[mapId];
        delete this.demWorkerSources[mapId];
        delete this.rasterArrayWorkerSource;
        callback();
    }
    checkIfReady(mapID, unused, callback) {
        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) {
                const workerSource2 = ws[source];
                if (workerSource2 instanceof VectorTileWorkerSource) {
                    workerSource2.isSpriteLoaded = isLoaded;
                    workerSource2.fire(new index.z('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.bP(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);
    }
    decodeRasterArray(mapId, params, callback) {
        this.getRasterArrayWorkerSource().decodeRasterArray(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 !== void 0) {
            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.ee.setState(state);
            const pluginURL = index.ee.getPluginURL();
            if (index.ee.isLoaded() && !index.ee.isParsed() && pluginURL != null) {
                this.self.importScripts(pluginURL);
                const complete = index.ee.isParsed();
                const error = complete ? void 0 : 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]) {
            const actor = {
                send: (type2, data, callback, _, mustQueue, metadata) => {
                    this.actor.send(type2, 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], void 0, this.brightness);
        }
        return this.workerSources[mapId][scope][type][source];
    }
    rasterizeImages(mapId, input, callback) {
        const {imageTasks, scope} = input;
        const images = {};
        for (const id in imageTasks) {
            const {image, imageIdWithOptions} = imageTasks[id];
            images[id] = this.imageRasterizer.rasterize(imageIdWithOptions, image, scope, mapId);
        }
        callback(void 0, images);
    }
    removeRasterizedImages(mapId, input, callback) {
        const {imageIds, scope} = input;
        this.imageRasterizer.removeImagesFromCacheByIds(imageIds, scope, mapId);
        callback();
    }
    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];
    }
    getRasterArrayWorkerSource() {
        if (!this.rasterArrayWorkerSource) {
            this.rasterArrayWorkerSource = new RasterArrayTileWorkerSource();
        }
        return this.rasterArrayWorkerSource;
    }
    enforceCacheSizeLimit(mapId, limit) {
        index.ef(limit);
    }
    getWorkerPerformanceMetrics(mapId, params, callback) {
        callback(void 0, void 0);
    }
}
if (typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && // @ts-expect-error - TS2304
    self instanceof WorkerGlobalScope) {
    self.worker = new MapWorker(self);
}

return MapWorker;

}));

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

var version = "3.10.0";

const LivePerformanceMarkers = {
    create: 'create',
    load: 'load',
    fullLoad: 'fullLoad'
};
const LivePerformanceUtils = {
    mark(marker) {
        performance.mark(marker);
    },
    measure(name, begin, end) {
        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] === void 0) {
                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`;
                    obj[min] = Math.min(obj[min] || Infinity, timer.startTime);
                    obj[max] = Math.max(obj[max] || -Infinity, timer.responseEnd);
                    const increment = key => {
                        if (obj[key] === void 0) {
                            obj[key] = 0;
                        }
                        ++obj[key];
                    };
                    const transferSizeSupported = timer.transferSize !== void 0;
                    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 (index.a(url) && url.includes('mapbox-gl.js'))
        return 'javascript';
    if (index.a(url) && url.includes('mapbox-gl.css'))
        return 'css';
    if (index.b(url))
        return 'fontRange';
    if (index.c(url))
        return 'sprite';
    if (index.i(url))
        return 'style';
    if (index.d(url))
        return 'tilejson';
    return 'other';
}
function getStyle(resourceTimers) {
    if (resourceTimers) {
        for (const timer of resourceTimers) {
            const url = timer.name.split('?')[0];
            if (index.i(url)) {
                const split = url.split('/').slice(-2);
                if (split.length === 2) {
                    return `mapbox://styles/${ split[0] }/${ split[1] }`;
                }
            }
        }
    }
}
function getLivePerformanceMetrics(data) {
    const resourceTimers = performance.getEntriesByType('resource');
    const markerTimers = performance.getEntriesByType('mark');
    const resourcesByType = categorize(resourceTimers, getResourceCategory);
    const counters = getCountersPerResourceType(resourcesByType);
    const devicePixelRatio = window.devicePixelRatio;
    const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    const effectiveType = connection ? connection.effectiveType : void 0;
    const metrics = {
        counters: [],
        metadata: [],
        attributes: []
    };
    const addMetric = (arr, name, value) => {
        if (value !== void 0 && 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(LivePerformanceMarkers)) {
            const markerName = LivePerformanceMarkers[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', effectiveType);
    addMetric(metrics.metadata, 'navigatorUserAgent', navigator.userAgent);
    addMetric(metrics.metadata, 'screenWidth', window.screen.width);
    addMetric(metrics.metadata, 'screenHeight', window.screen.height);
    addMetric(metrics.metadata, 'windowWidth', window.innerWidth);
    addMetric(metrics.metadata, 'windowHeight', window.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;
}

var mapboxGlSupported = {};

var hasRequiredMapboxGlSupported;

function requireMapboxGlSupported () {
	if (hasRequiredMapboxGlSupported) return mapboxGlSupported;
	hasRequiredMapboxGlSupported = 1;
	mapboxGlSupported.supported = isSupported;
	mapboxGlSupported.notSupportedReason = notSupportedReason;
	/**
	 * 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 (!isWorkerSupported())
	        return 'insufficient worker support';
	    if (!isCanvasGetImageDataSupported())
	        return 'insufficient Canvas/getImageData support';
	    if (!isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat))
	        return 'insufficient WebGL2 support';
	    if (!isNotIE())
	        return 'insufficient ECMAScript 6 support';
	}
	function isBrowser() {
	    return typeof window !== 'undefined' && typeof document !== 'undefined';
	}
	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;
	}
	// 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('webgl2', 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;
	}
	return mapboxGlSupported;
}

var mapboxGlSupportedExports = requireMapboxGlSupported();

function create$1(tagName, className, container) {
    const el = document.createElement(tagName);
    if (className !== void 0 && className !== null)
        el.className = className;
    if (container)
        container.appendChild(el);
    return el;
}
function createSVG(tagName, attributes, container) {
    const el = document.createElementNS('http://www.w3.org/2000/svg', tagName);
    for (const name of Object.keys(attributes)) {
        el.setAttributeNS(null, name, String(attributes[name]));
    }
    if (container)
        container.appendChild(el);
    return el;
}
const docStyle = typeof document !== 'undefined' ? document.documentElement && document.documentElement.style : null;
const selectProp = docStyle && docStyle.userSelect !== void 0 ? 'userSelect' : 'WebkitUserSelect';
let userSelect;
function disableDrag() {
    if (docStyle && selectProp) {
        userSelect = docStyle[selectProp];
        docStyle[selectProp] = 'none';
    }
}
function enableDrag() {
    if (docStyle && selectProp) {
        docStyle[selectProp] = userSelect;
    }
}
function suppressClickListener(e) {
    e.preventDefault();
    e.stopPropagation();
    window.removeEventListener('click', suppressClickListener, true);
}
function suppressClick() {
    window.addEventListener('click', suppressClickListener, true);
    window.setTimeout(() => {
        window.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 (/firefox/i.test(navigator.userAgent) && /macintosh/i.test(navigator.userAgent) && e.button === 2 && e.ctrlKey) {
        return 0;
    }
    return e.button;
}
function getScaledPoint(el, rect, e) {
    const scaling = el.offsetWidth === rect.width ? 1 : el.offsetWidth / rect.width;
    return new index.P((e.clientX - rect.left) * scaling, (e.clientY - rect.top) * scaling);
}

const SKU_ID = '01';
function createSkuToken() {
    const TOKEN_VERSION = '1';
    const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let sessionRandomizer = '';
    for (let i = 0; i < 10; i++) {
        sessionRandomizer += base62chars[Math.floor(Math.random() * 62)];
    }
    const expiration = 12 * 60 * 60 * 1000;
    const token = [
        TOKEN_VERSION,
        SKU_ID,
        sessionRandomizer
    ].join('');
    const tokenExpiresAt = Date.now() + expiration;
    return {
        token,
        tokenExpiresAt
    };
}

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 (!index.f(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 (!index.f(url))
            return url;
        const urlObject = parseUrl(url);
        urlObject.path = `/fonts/v1${ urlObject.path }`;
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeModelURL(url, accessToken) {
        if (!index.f(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 (!index.f(url))
            return url;
        const urlObject = parseUrl(url);
        urlObject.path = `/v4/${ urlObject.authority }.json`;
        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);
    }
    normalizeIconsetURL(url, accessToken) {
        const urlObject = parseUrl(url);
        if (!index.f(url)) {
            return formatUrl(urlObject);
        }
        urlObject.path = `/styles/v1${ urlObject.path }/iconset.pbf`;
        return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
    }
    normalizeSpriteURL(url, format, extension, accessToken) {
        const urlObject = parseUrl(url);
        if (!index.f(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 && !index.f(tileURL))
            return tileURL;
        const urlObject = parseUrl(tileURL);
        const imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/;
        const extension = index.m.supported ? '.webp' : '$1';
        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 = `/${ index.e.RASTER_URL_PREFIX }${ urlObject.path }`;
        } else if (urlObject.authority === 'rasterarrays') {
            urlObject.path = `/${ index.e.RASTERARRAYS_URL_PREFIX }${ urlObject.path }`;
        } else if (urlObject.authority === '3dtiles') {
            urlObject.path = `/${ index.e.TILES3D_URL_PREFIX }${ urlObject.path }`;
        } else {
            const tileURLAPIPrefixRe = /^.+\/v4\//;
            urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');
            urlObject.path = `/${ index.e.TILE_URL_VERSION }${ urlObject.path }`;
        }
        const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || index.e.ACCESS_TOKEN;
        if (index.e.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) {
            urlObject.params.push(`sku=${ this._skuToken }`);
        }
        return this._makeAPIURL(urlObject, accessToken);
    }
    canonicalizeTileURL(url, removeAccessToken) {
        const extensionRe = /\.[\w]+$/;
        const urlObject = parseUrl(url);
        if (!urlObject.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/) || !urlObject.path.match(extensionRe)) {
            return url;
        }
        let result = 'mapbox://';
        if (urlObject.path.match(/^\/raster\/v1\//)) {
            const rasterPrefix = `/${ index.e.RASTER_URL_PREFIX }/`;
            result += `raster/${ urlObject.path.replace(rasterPrefix, '') }`;
        } else if (urlObject.path.match(/^\/rasterarrays\/v1\//)) {
            const rasterPrefix = `/${ index.e.RASTERARRAYS_URL_PREFIX }/`;
            result += `rasterarrays/${ urlObject.path.replace(rasterPrefix, '') }`;
        } else {
            const tilesPrefix = `/${ index.e.TILE_URL_VERSION }/`;
            result += `tiles/${ urlObject.path.replace(tilesPrefix, '') }`;
        }
        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 ? index.f(sourceURL) : false;
        const canonical = [];
        for (const url of tileJSON.tiles || []) {
            if (index.h(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(index.e.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 (!index.e.REQUIRE_ACCESS_TOKEN)
            return formatUrl(urlObject);
        accessToken = accessToken || index.e.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 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(index.j(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(index.e.ACCESS_TOKEN);
        let u = '';
        if (tokenData && tokenData['u']) {
            u = index.k(tokenData['u']);
        } else {
            u = index.e.ACCESS_TOKEN || '';
        }
        return domain ? `${ telemEventKey }.${ domain }:${ u }` : `${ telemEventKey }:${ u }`;
    }
    fetchEventData() {
        const isLocalStorageAvailable = index.s('localStorage');
        const storageKey = this.getStorageKey();
        const uuidKey = this.getStorageKey('uuid');
        if (isLocalStorageAvailable) {
            try {
                const data = localStorage.getItem(storageKey);
                if (data) {
                    this.eventData = JSON.parse(data);
                }
                const uuid2 = localStorage.getItem(uuidKey);
                if (uuid2)
                    this.anonId = uuid2;
            } catch (e) {
                index.w('Unable to read from LocalStorage');
            }
        }
    }
    saveEventData() {
        const isLocalStorageAvailable = index.s('localStorage');
        const storageKey = this.getStorageKey();
        const uuidKey = this.getStorageKey('uuid');
        const anonId = this.anonId;
        if (isLocalStorageAvailable && anonId) {
            try {
                localStorage.setItem(uuidKey, anonId);
                if (Object.keys(this.eventData).length >= 1) {
                    localStorage.setItem(storageKey, JSON.stringify(this.eventData));
                }
            } catch (e) {
                index.w('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 (!index.e.EVENTS_URL)
            return;
        const eventsUrlObject = parseUrl(index.e.EVENTS_URL);
        eventsUrlObject.params.push(`access_token=${ customAccessToken || index.e.ACCESS_TOKEN || '' }`);
        const payload = {
            event: this.type,
            created: new Date(timestamp).toISOString()
        };
        const finalPayload = additionalPayload ? index.l(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 = index.p(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 (index.e.EVENTS_URL) {
            if (customAccessToken || index.e.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);
        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 (index.e.EVENTS_URL) {
            if (customAccessToken || index.e.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();
        if (id && this.success[id])
            return;
        if (!this.anonId) {
            this.fetchEventData();
        }
        if (!index.v(this.anonId)) {
            this.anonId = index.u();
        }
        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);
    }
    remove() {
        this.errorCb = null;
    }
}
class StyleLoadEvent extends TelemetryEvent {
    constructor() {
        super('style.load');
        this.eventIdPerMapInstanceMap = /* @__PURE__ */
        new Map();
        this.mapInstanceIdMap = /* @__PURE__ */
        new WeakMap();
    }
    getMapInstanceId(map) {
        let instanceId = this.mapInstanceIdMap.get(map);
        if (!instanceId) {
            instanceId = index.u();
            this.mapInstanceIdMap.set(map, instanceId);
        }
        return instanceId;
    }
    getEventId(mapInstanceId) {
        const eventId = this.eventIdPerMapInstanceMap.get(mapInstanceId) || 0;
        this.eventIdPerMapInstanceMap.set(mapInstanceId, eventId + 1);
        return eventId;
    }
    postStyleLoadEvent(customAccessToken, input) {
        const {map, style, importedStyles} = input;
        if (!index.e.EVENTS_URL || !(customAccessToken || index.e.ACCESS_TOKEN)) {
            return;
        }
        const mapInstanceId = this.getMapInstanceId(map);
        const payload = {
            mapInstanceId,
            eventId: this.getEventId(mapInstanceId),
            style
        };
        if (importedStyles.length) {
            payload.importedStyles = importedStyles;
        }
        this.queueRequest({
            timestamp: Date.now(),
            payload
        }, customAccessToken);
    }
    processRequests(customAccessToken) {
        if (this.pendingRequest || this.queue.length === 0) {
            return;
        }
        const {timestamp, payload} = this.queue.shift();
        this.postEvent(timestamp, payload, () => {
        }, customAccessToken);
    }
}
class MapSessionAPI extends TelemetryEvent {
    constructor() {
        super('map.auth');
        this.success = {};
        this.skuToken = '';
    }
    getSession(timestamp, token, callback, customAccessToken) {
        if (!index.e.API_URL || !index.e.SESSION_PATH)
            return;
        const authUrlObject = parseUrl(index.e.API_URL + index.e.SESSION_PATH);
        authUrlObject.params.push(`sku=${ token || '' }`);
        authUrlObject.params.push(`access_token=${ customAccessToken || index.e.ACCESS_TOKEN || '' }`);
        const request = {
            url: formatUrl(authUrlObject),
            headers: {
                'Content-Type': 'text/plain'    //Skip the pre-flight OPTIONS request
            }
        };
        this.pendingRequest = index.g(request, error => {
            this.pendingRequest = null;
            callback(error);
            this.saveEventData();
            this.processRequests(customAccessToken);
        });
    }
    getSessionAPI(mapId, skuToken, customAccessToken, callback) {
        this.skuToken = skuToken;
        this.errorCb = callback;
        if (index.e.SESSION_PATH && index.e.API_URL) {
            if (customAccessToken || index.e.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();
        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);
    }
    remove() {
        this.errorCb = null;
    }
}
class TurnstileEvent extends TelemetryEvent {
    constructor(customAccessToken) {
        super('appUserTurnstile');
        this._customAccessToken = customAccessToken;
    }
    postTurnstileEvent(tileUrls, customAccessToken) {
        if (index.e.EVENTS_URL && index.e.ACCESS_TOKEN && Array.isArray(tileUrls) && tileUrls.some(url => index.f(url) || index.h(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) {
            this.fetchEventData();
        }
        const tokenData = parseAccessToken(index.e.ACCESS_TOKEN);
        const tokenU = tokenData ? tokenData['u'] : index.e.ACCESS_TOKEN;
        let dueForEvent = tokenU !== this.eventData.tokenU;
        if (!index.v(this.anonId)) {
            this.anonId = index.u();
            dueForEvent = true;
        }
        const nextUpdate = this.queue.shift();
        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();
const postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);
const mapLoadEvent = new MapLoadEvent();
const postMapLoadEvent = mapLoadEvent.postMapLoadEvent.bind(mapLoadEvent);
const styleLoadEvent = new StyleLoadEvent();
const postStyleLoadEvent = styleLoadEvent.postStyleLoadEvent.bind(styleLoadEvent);
const performanceEvent_ = new PerformanceEvent();
const postPerformanceEvent = performanceEvent_.postPerformanceEvent.bind(performanceEvent_);
const mapSessionAPI = new MapSessionAPI();
const getMapSessionAPI = mapSessionAPI.getSessionAPI.bind(mapSessionAPI);
const authenticatedMaps = /* @__PURE__ */
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);
}

class StyleChanges {
    constructor() {
        this._changed = false;
        this._updatedLayers = {};
        this._removedLayers = {};
        this._updatedSourceCaches = {};
        this._updatedPaintProps = /* @__PURE__ */
        new Set();
        this._updatedImages = /* @__PURE__ */
        new Set();
    }
    isDirty() {
        return this._changed;
    }
    /**
   * Mark changes as dirty.
   */
    setDirty() {
        this._changed = true;
    }
    getUpdatedSourceCaches() {
        return this._updatedSourceCaches;
    }
    /**
   * Mark that a source cache needs to be cleared or reloaded.
   * @param {string} id
   * @param {'clear' | 'reload'} action
   */
    updateSourceCache(id, action) {
        this._updatedSourceCaches[id] = action;
        this.setDirty();
    }
    /**
   * Discards updates to the source cache with the given id.
   * @param {string} id
   */
    discardSourceCacheUpdate(id) {
        delete this._updatedSourceCaches[id];
    }
    /**
   * 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] || /* @__PURE__ */
        new Set();
        this._updatedLayers[scope].add(layer.id);
        this.setDirty();
    }
    /**
   * 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] || /* @__PURE__ */
        new Set();
        this._removedLayers[scope][layer.id] = layer;
        this._updatedLayers[scope].delete(layer.id);
        this._updatedPaintProps.delete(layer.fqid);
        this.setDirty();
    }
    /**
   * 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;
    }
    getUpdatedPaintProperties() {
        return this._updatedPaintProps;
    }
    /**
   * Mark a layer as having a changed paint properties.
   * @param {StyleLayer} layer
   */
    updatePaintProperties(layer) {
        this._updatedPaintProps.add(layer.fqid);
        this.setDirty();
    }
    getUpdatedImages() {
        return Array.from(this._updatedImages.values());
    }
    /**
   * Mark an image as having changes.
   * @param {string} id
   */
    updateImage(id) {
        this._updatedImages.add(id);
        this.setDirty();
    }
    resetUpdatedImages() {
        this._updatedImages.clear();
    }
    /**
   * Reset all style changes.
   */
    reset() {
        this._changed = false;
        this._updatedLayers = {};
        this._removedLayers = {};
        this._updatedSourceCaches = {};
        this._updatedPaintProps.clear();
        this._updatedImages.clear();
    }
}

function loadSprite (baseURL, requestManager, callback) {
    let json, image, error;
    const format = index.q.devicePixelRatio > 1 ? '@2x' : '';
    let jsonRequest = index.n(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), index.R.SpriteJSON), (err, data) => {
        jsonRequest = null;
        if (!error) {
            error = err;
            json = data;
            maybeComplete();
        }
    });
    let imageRequest = index.o(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), index.R.SpriteImage), (err, img) => {
        imageRequest = null;
        if (!error) {
            error = err;
            image = img;
            maybeComplete();
        }
    });
    function maybeComplete() {
        if (error) {
            callback(error);
        } else if (json && image) {
            const imageData = index.q.getImageData(image);
            const result = {};
            for (const id in json) {
                const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content} = json[id];
                const data = new index.r({
                    width,
                    height
                });
                index.r.copy(imageData, data, {
                    x,
                    y
                }, {
                    x: 0,
                    y: 0
                }, {
                    width,
                    height
                }, null);
                result[id] = {
                    data,
                    pixelRatio,
                    sdf,
                    stretchX,
                    stretchY,
                    content,
                    usvg: false
                };
            }
            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;
}

const IMAGE_RASTERIZER_WORKER_POOL_COUNT = 1;
class ImageManager extends index.E {
    constructor(spriteFormat) {
        super();
        this.images = {};
        this.updatedImages = {};
        this.callbackDispatchedThisFrame = {};
        this.loaded = {};
        this.requestors = [];
        this.patterns = {};
        this.atlasImage = {};
        this.atlasTexture = {};
        this.dirty = true;
        this.spriteFormat = spriteFormat;
        if (spriteFormat !== 'raster' && index.t()) {
            this.imageRasterizerDispatcher = new index.D(index.x(), this, 'Image Rasterizer Worker', IMAGE_RASTERIZER_WORKER_POOL_COUNT);
        }
    }
    get imageRasterizer() {
        if (!this._imageRasterizer) {
            this._imageRasterizer = new index.I();
        }
        return this._imageRasterizer;
    }
    createScope(scope) {
        this.images[scope] = {};
        this.loaded[scope] = false;
        this.updatedImages[scope] = {};
        this.patterns[scope] = {};
        this.callbackDispatchedThisFrame[scope] = {};
        this.atlasImage[scope] = new index.r({
            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 index.y(new Error(`Image "${ id }" has invalid "stretchX" value`)));
            valid = false;
        }
        if (!this._validateStretch(image.stretchY, image.data && image.data.height)) {
            this.fire(new index.y(new Error(`Image "${ id }" has invalid "stretchY" value`)));
            valid = false;
        }
        if (!this._validateContent(image.content, image)) {
            this.fire(new index.y(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 (!image.usvg) {
            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;
        this.removeFromImageRasterizerCache(id, scope);
    }
    removeFromImageRasterizerCache(id, scope) {
        if (this.spriteFormat === 'raster') {
            return;
        }
        if (index.t()) {
            this.imageRasterizerDispatcher.getActor().send('removeRasterizedImages', {
                imageIds: [id],
                scope
            });
        } else {
            this.imageRasterizer.removeImagesFromCacheByIds([id], scope);
        }
    }
    removeImage(id, scope) {
        const image = this.images[scope][id];
        delete this.images[scope][id];
        delete this.patterns[scope][id];
        this.removeFromImageRasterizerCache(id, scope);
        if (image.userImage && image.userImage.onRemove) {
            image.userImage.onRemove();
        }
    }
    listImages(scope) {
        return Object.keys(this.images[scope]);
    }
    getImages(ids, scope, callback) {
        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
            });
        }
    }
    rasterizeImages({scope, imageTasks}, callback) {
        const imageWorkerTasks = {};
        for (const id in imageTasks) {
            const imageIdWithOptions = imageTasks[id];
            const image = this.getImage(imageIdWithOptions.id, scope);
            if (image) {
                imageWorkerTasks[id] = {
                    image,
                    imageIdWithOptions
                };
            }
        }
        if (!index.t()) {
            this.rasterizeImagesInMainThread({
                imageTasks: imageWorkerTasks,
                scope
            }, callback);
        } else {
            this.imageRasterizerDispatcher.getActor().send('rasterizeImages', {
                imageTasks: imageWorkerTasks,
                scope
            }, callback);
        }
    }
    rasterizeImagesInMainThread(input, callback) {
        const {imageTasks, scope} = input;
        const images = {};
        for (const id in imageTasks) {
            const {image, imageIdWithOptions} = imageTasks[id];
            images[id] = this.imageRasterizer.rasterize(imageIdWithOptions, image, scope, '');
        }
        callback(void 0, images);
    }
    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 index.z('styleimagemissing', { id }));
            }
            const image = this.images[scope][id];
            if (image) {
                response[id] = {
                    // Vector images will be rasterized on the worker thread
                    data: image.usvg ? null : image.data.clone(),
                    pixelRatio: image.pixelRatio,
                    sdf: image.sdf,
                    usvg: image.usvg,
                    version: image.version,
                    stretchX: image.stretchX,
                    stretchY: image.stretchY,
                    content: image.content,
                    hasRenderCallback: Boolean(image.userImage && image.userImage.render)
                };
            } else {
                index.w(`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, lut) {
        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) {
            if (image.usvg && !image.data) {
                image.data = this.imageRasterizer.rasterize(index.A.from(id).getPrimary(), image, scope, '');
            }
            const w = image.data.width + index.B * 2;
            const h = image.data.height + index.B * 2;
            const bin = {
                w,
                h,
                x: 0,
                y: 0
            };
            const position = new index.C(bin, image, index.B);
            this.patterns[scope][id] = {
                bin,
                position
            };
        } else {
            pattern.position.version = image.version;
        }
        this._updatePatternAtlas(scope, lut);
        return this.patterns[scope][id].position;
    }
    bind(context, scope) {
        const gl = context.gl;
        let atlasTexture = this.atlasTexture[scope];
        if (!atlasTexture) {
            atlasTexture = new index.T(context, this.atlasImage[scope], gl.RGBA8);
            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, lut) {
        const bins = [];
        for (const id in this.patterns[scope]) {
            bins.push(this.patterns[scope][id].bin);
        }
        const {w, h} = index.F(bins);
        const dst = this.atlasImage[scope];
        dst.resize({
            width: w || 1,
            height: h || 1
        });
        for (const id in this.patterns[scope]) {
            const {bin, position} = this.patterns[scope][id];
            let padding = position.padding;
            const x = bin.x + padding;
            const y = bin.y + padding;
            const src = this.images[scope][id].data;
            const w2 = src.width;
            const h2 = src.height;
            padding = padding > 1 ? padding - 1 : padding;
            index.r.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x,
                y
            }, {
                width: w2,
                height: h2
            }, lut);
            index.r.copy(src, dst, {
                x: 0,
                y: h2 - padding
            }, {
                x,
                y: y - padding
            }, {
                width: w2,
                height: padding
            }, lut);
            index.r.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x,
                y: y + h2
            }, {
                width: w2,
                height: padding
            }, lut);
            index.r.copy(src, dst, {
                x: w2 - padding,
                y: 0
            }, {
                x: x - padding,
                y
            }, {
                width: padding,
                height: h2
            }, lut);
            index.r.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x: x + w2,
                y
            }, {
                width: padding,
                height: h2
            }, lut);
            index.r.copy(src, dst, {
                x: w2 - padding,
                y: h2 - padding
            }, {
                x: x - padding,
                y: y - padding
            }, {
                width: padding,
                height: padding
            }, lut);
            index.r.copy(src, dst, {
                x: 0,
                y: h2 - padding
            }, {
                x: x + w2,
                y: y - padding
            }, {
                width: padding,
                height: padding
            }, lut);
            index.r.copy(src, dst, {
                x: 0,
                y: 0
            }, {
                x: x + w2,
                y: y + h2
            }, {
                width: padding,
                height: padding
            }, lut);
            index.r.copy(src, dst, {
                x: w2 - padding,
                y: 0
            }, {
                x: x - padding,
                y: y + h2
            }, {
                width: padding,
                height: padding
            }, lut);
        }
        this.dirty = true;
    }
    beginFrame() {
        for (const scope in this.images) {
            this.callbackDispatchedThisFrame[scope] = {};
        }
    }
    dispatchRenderCallbacks(ids, scope) {
        for (const id of ids) {
            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);
            }
        }
    }
}

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 = index.H(object);
    if (type !== 'object') {
        return [new index.V(key, object, `object expected, ${ type } found`)];
    }
    for (const objectKey in object) {
        const elementSpecKey = objectKey.split('.')[0];
        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 index.G(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
        }, object));
    }
    for (const elementSpecKey in elementSpecs) {
        if (elementValidators[elementSpecKey]) {
            continue;
        }
        if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === void 0 && object[elementSpecKey] === void 0) {
            errors.push(new index.V(key, object, `missing required property "${ elementSpecKey }"`));
        }
    }
    return errors;
}

function validateImport(options) {
    const {value, styleSpec} = options;
    const {data, ...importSpec} = value;
    Object.defineProperty(importSpec, '__line__', {
        value: value.__line__,
        enumerable: false
    });
    let errors = validateObject(index.J({}, options, {
        value: importSpec,
        valueSpec: styleSpec.import
    }));
    if (index.K(importSpec.id) === '') {
        const key = `${ options.key }.id`;
        errors.push(new index.V(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 (index.H(array) !== 'array') {
        return [new index.V(key, array, `array expected, ${ index.H(array) } found`)];
    }
    if (arraySpec.length && array.length !== arraySpec.length) {
        return [new index.V(key, array, `array length ${ arraySpec.length } expected, length ${ array.length } found`)];
    }
    if (arraySpec['min-length'] && array.length < arraySpec['min-length']) {
        return [new index.V(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: void 0
    };
    if (styleSpec.$version < 7) {
        arrayElementSpec.function = arraySpec.function;
    }
    if (index.H(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 = index.H(value);
    if (type === 'number' && value !== value) {
        type = 'NaN';
    }
    if (type !== 'number') {
        return [new index.V(key, value, `number expected, ${ type } found`)];
    }
    if ('minimum' in valueSpec) {
        let specMin = valueSpec.minimum;
        if (index.H(valueSpec.minimum) === 'array') {
            const i = options.arrayIndex;
            specMin = valueSpec.minimum[i];
        }
        if (value < specMin) {
            return [new index.V(key, value, `${ value } is less than the minimum value ${ specMin }`)];
        }
    }
    if ('maximum' in valueSpec) {
        let specMax = valueSpec.maximum;
        if (index.H(valueSpec.maximum) === 'array') {
            const i = options.arrayIndex;
            specMax = valueSpec.maximum[i];
        }
        if (value > specMax) {
            return [new index.V(key, value, `${ value } is greater than the maximum value ${ specMax }`)];
        }
    }
    return [];
}

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

function validateExpression(options) {
    const expression = (options.expressionContext === 'property' ? index.S : index.U)(index.Q(options.value), options.valueSpec);
    if (expression.result === 'error') {
        return expression.value.map(error => {
            return new index.V(`${ 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 index.V(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' && !index.W(expressionObj)) {
        return [new index.V(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 (!index.X(expressionObj, [
                'zoom',
                'feature-state'
            ])) {
            return [new index.V(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')];
        }
        if (options.expressionContext === 'cluster-initial' && !index.Y(expressionObj)) {
            return [new index.V(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')];
        }
    }
    return [];
}
function disallowedFilterParameters(e, options) {
    const disallowedParameters = /* @__PURE__ */
    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 index.Z) {
        if (disallowedParameters.has(e.name)) {
            return [new index.V(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 = index.H(value);
    if (type !== 'boolean') {
        return [new index.V(key, value, `boolean expected, ${ type } found`)];
    }
    return [];
}

function validateColor(options) {
    const key = options.key;
    const value = options.value;
    const type = index.H(value);
    if (type !== 'string') {
        return [new index.V(key, value, `color expected, ${ type } found`)];
    }
    if (index._.parseCSSColor(value) === null) {
        return [new index.V(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)) {
        if (valueSpec.values.indexOf(index.K(value)) === -1) {
            errors.push(new index.V(key, value, `expected one of [${ valueSpec.values.join(', ') }], ${ JSON.stringify(value) } found`));
        }
    } else {
        if (Object.keys(valueSpec.values).indexOf(index.K(value)) === -1) {
            errors.push(new index.V(key, value, `expected one of [${ Object.keys(valueSpec.values).join(', ') }], ${ JSON.stringify(value) } found`));
        }
    }
    return errors;
}

function validateFilter$1(options) {
    if (index.$(index.Q(options.value))) {
        const layerType = options.layerType || 'fill';
        return validateExpression(index.J({}, options, {
            expressionContext: 'filter',
            valueSpec: options.styleSpec[`filter_${ layerType }`]
        }));
    } else {
        return validateNonExpressionFilter(options);
    }
}
function validateNonExpressionFilter(options) {
    const value = options.value;
    const key = options.key;
    if (index.H(value) !== 'array') {
        return [new index.V(key, value, `array expected, ${ index.H(value) } found`)];
    }
    const styleSpec = options.styleSpec;
    let type;
    let errors = [];
    if (value.length < 1) {
        return [new index.V(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 (index.K(value[0])) {
    case '<':
    case '<=':
    case '>':
    // @ts-expect-error - falls through
    case '>=':
        if (value.length >= 2 && index.K(value[1]) === '$type') {
            errors.push(new index.V(key, value, `"$type" cannot be use with operator "${ value[0] }"`));
        }
    /* falls through */
    case '==':
    // @ts-expect-error - falls through
    case '!=':
        if (value.length !== 3) {
            errors.push(new index.V(key, value, `filter array for operator "${ value[0] }" must have 3 elements`));
        }
    /* falls through */
    case 'in':
    case '!in':
        if (value.length >= 2) {
            type = index.H(value[1]);
            if (type !== 'string') {
                errors.push(new index.V(`${ key }[1]`, value[1], `string expected, ${ type } found`));
            }
        }
        for (let i = 2; i < value.length; i++) {
            type = index.H(value[i]);
            if (index.K(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 index.V(`${ 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 = index.H(value[1]);
        if (value.length !== 2) {
            errors.push(new index.V(key, value, `filter array for "${ value[0] }" operator must have 2 elements`));
        } else if (type !== 'string') {
            errors.push(new index.V(`${ 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 useThemeMatch = propertyKey.match(/^(.*)-use-theme$/);
    if (propertyType === 'paint' && useThemeMatch && layerSpec[useThemeMatch[1]]) {
        if (index.O(value)) {
            const errors2 = [];
            return errors2.concat(validate({
                key: options.key,
                value,
                valueSpec: {
                    'type': 'string',
                    'expression': {
                        'interpolated': false,
                        'parameters': [
                            'zoom',
                            'feature'
                        ]
                    },
                    'property-type': 'data-driven'
                },
                style,
                styleSpec,
                // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'expressionContext' does not exist in type 'ValidationOptions'.
                expressionContext: 'property',
                propertyType,
                propertyKey
            }));
        }
        return validate({
            key,
            value,
            valueSpec: { type: 'string' },
            style,
            styleSpec
        });
    }
    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 index.G(key, value, `unknown property "${ propertyKey }"`)];
    }
    let tokenMatch;
    if (index.H(value) === 'string' && index.M(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {
        const example = `\`{ "type": "identity", "property": ${ tokenMatch ? JSON.stringify(tokenMatch[1]) : '"_"' } }\``;
        return [new index.V(key, value, `"${ propertyKey }" does not support interpolation syntax
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 index.V(key, value, 'use of "text-field" requires a style "glyphs" property'));
        }
        if (propertyKey === 'text-font' && index.a0(index.Q(value)) && index.K(value.type) === 'identity') {
            errors.push(new index.V(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 (index.M(valueSpec) && (index.a1(valueSpec) || index.N(valueSpec))) {
            const expression = index.S(index.Q(value), valueSpec);
            const expressionObj = expression.value.expression || expression.value._styleExpression.expression;
            if (expressionObj && !index.X(expressionObj, ['measure-light'])) {
                if (propertyKey !== 'model-emissive-strength' || (!index.Y(expressionObj) || !index.W(expressionObj))) {
                    errors.push(new index.V(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,
        // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'expressionContext' does not exist in type 'ValidationOptions'.
        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 index.V(key, layer, 'either "type" or "ref" is required'));
    }
    let type = index.K(layer.type);
    const ref = index.K(layer.ref);
    if (layer.id) {
        const layerId = index.K(layer.id);
        for (let i = 0; i < options.arrayIndex; i++) {
            const otherLayer = style.layers[i];
            if (index.K(otherLayer.id) === layerId) {
                errors.push(new index.V(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 index.V(key, layer[p], `"${ p }" is prohibited for ref layers`));
            }
        });
        let parent;
        style.layers.forEach(layer2 => {
            if (index.K(layer2.id) === ref)
                parent = layer2;
        });
        if (!parent) {
            if (typeof ref === 'string')
                errors.push(new index.V(key, layer.ref, `ref layer "${ ref }" not found`));
        } else if (parent.ref) {
            errors.push(new index.V(key, layer.ref, 'ref cannot reference another ref layer'));
        } else {
            type = index.K(parent.type);
        }
    } else if (!(type === 'background' || type === 'sky' || type === 'slot')) {
        if (!layer.source) {
            errors.push(new index.V(key, layer, 'missing required property "source"'));
        } else {
            const source = style.sources && style.sources[layer.source];
            const sourceType = source && index.K(source.type);
            if (!source) {
                errors.push(new index.V(key, layer.source, `source "${ layer.source }" not found`));
            } else if (sourceType === 'vector' && type === 'raster') {
                errors.push(new index.V(key, layer.source, `layer "${ layer.id }" requires a raster source`));
            } else if (sourceType === 'raster' && type !== 'raster') {
                errors.push(new index.V(key, layer.source, `layer "${ layer.id }" requires a vector source`));
            } else if (sourceType === 'vector' && !layer['source-layer']) {
                errors.push(new index.V(key, layer, `layer "${ layer.id }" must specify a "source-layer"`));
            } else if (sourceType === 'raster-dem' && type !== 'hillshade') {
                errors.push(new index.V(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.'));
            } else if (sourceType === 'raster-array' && ![
                    'raster',
                    'raster-particle'
                ].includes(type)) {
                errors.push(new index.V(key, layer.source, `raster-array source can only be used with layer type 'raster'.`));
            } else if (type === 'line' && layer.paint && (layer.paint['line-gradient'] || layer.paint['line-trim-offset']) && (sourceType !== 'geojson' || !source.lineMetrics)) {
                errors.push(new index.V(key, layer, `layer "${ layer.id }" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`));
            } else if (type === 'raster-particle' && sourceType !== 'raster-array') {
                errors.push(new index.V(key, layer.source, `layer "${ layer.id }" requires a 'raster-array' source.`));
            }
        }
    }
    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,
                    // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'object' does not exist in type 'ValidationOptions'.
                    object: layer,
                    objectKey: 'type'
                });
            },
            filter(options2) {
                return validateFilter$1(index.J({ layerType: type }, options2));
            },
            layout(options2) {
                return validateObject({
                    // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'layer' does not exist in type 'Options'.
                    layer,
                    key: options2.key,
                    value: options2.value,
                    valueSpec: {},
                    style: options2.style,
                    styleSpec: options2.styleSpec,
                    objectElementValidators: {
                        '*'(options3) {
                            return validateLayoutProperty$1(index.J({ layerType: type }, options3));
                        }
                    }
                });
            },
            paint(options2) {
                return validateObject({
                    // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'layer' does not exist in type 'Options'.
                    layer,
                    key: options2.key,
                    value: options2.value,
                    valueSpec: {},
                    style: options2.style,
                    styleSpec: options2.styleSpec,
                    objectElementValidators: {
                        '*'(options3) {
                            return validatePaintProperty$1(index.J({
                                layerType: type,
                                layer
                            }, options3));
                        }
                    }
                });
            }
        }
    }));
    return errors;
}

function validateString(options) {
    const value = options.value;
    const key = options.key;
    const type = index.H(value);
    if (type !== 'string') {
        return [new index.V(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 index.V(key, value, '"type" is required')];
    }
    const type = index.K(value.type);
    let errors = [];
    if ([
            'vector',
            'raster',
            'raster-dem',
            'raster-array'
        ].includes(type)) {
        if (!value.url && !value.tiles) {
            errors.push(new index.G(key, value, 'Either "url" or "tiles" is required.'));
        }
    }
    switch (type) {
    case 'vector':
    case 'raster':
    case 'raster-dem':
    case 'raster-array':
        errors = errors.concat(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 index.V(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 (index.H(value) === 'string') {
        return validateString({
            key,
            value
        });
    } else if (Array.isArray(value)) {
        const errors = [];
        const unbundledValue = index.Q(value);
        const expression = index.U(unbundledValue);
        if (expression.result === 'error') {
            expression.value.forEach(err => {
                errors.push(new index.V(`${ key }${ err.key }`, null, `${ err.message }`));
            });
        }
        const parsed = expression.value.expression;
        const onlyFeatureDependent = index.X(parsed, [
            'zoom',
            'heatmap-density',
            'line-progress',
            'raster-value',
            'sky-radial-progress',
            'accumulated',
            'is-supported-script',
            'pitch',
            'distance-from-center',
            'measure-light',
            'raster-particle-speed'
        ]);
        if (!onlyFeatureDependent) {
            errors.push(new index.V(`${ key }`, null, 'promoteId expression should be only feature dependent'));
        }
        return errors;
    } else {
        const errors = [];
        for (const prop in value) {
            errors.push(...validatePromoteId({
                key: `${ key }.${ prop }`,
                value: value[prop]
            }));
        }
        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 = index.H(light);
    if (light === void 0) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new index.V('light', light, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in light) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        const useThemeMatch = key.match(/^(.*)-use-theme$/);
        if (useThemeMatch && lightSpec[useThemeMatch[1]]) {
            errors = errors.concat(validate({
                key,
                value: light[key],
                valueSpec: { type: 'string' },
                style,
                styleSpec
            }));
        } else 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 index.V(key, light[key], `unknown property "${ key }"`)]);
        }
    }
    return errors;
}

function validateLights$1(options) {
    const light = options.value;
    let errors = [];
    if (!light) {
        return errors;
    }
    const type = index.H(light);
    if (type !== 'object') {
        errors = errors.concat([new index.V('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 key2 of [
            'type',
            'id'
        ]) {
        if (!(key2 in light)) {
            errors = errors.concat([new index.V('light-3d', light, `missing property ${ key2 } on light`)]);
            return errors;
        }
    }
    if (light.type && lights) {
        for (let i = 0; i < options.arrayIndex; i++) {
            const lightType2 = index.K(light.type);
            const otherLight = lights[i];
            if (index.K(otherLight.type) === lightType2) {
                errors.push(new index.V(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 index.V('light-3d', light, `Invalid light type ${ light['type'] }`)]);
        return errors;
    }
    const lightPropertySpec = styleSpec[lightType];
    for (const key2 in light) {
        if (key2 === 'properties') {
            const properties = light[key2];
            const propertiesType = index.H(properties);
            if (propertiesType !== 'object') {
                errors = errors.concat([new index.V('properties', properties, `object expected, ${ propertiesType } found`)]);
                return errors;
            }
            for (const propertyKey in properties) {
                if (!lightPropertySpec[propertyKey]) {
                    errors = errors.concat([new index.G(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 = key2.match(/^(.*)-transition$/);
            const useThemeMatch = key2.match(/^(.*)-use-theme$/);
            if (useThemeMatch && lightSpec[useThemeMatch[1]]) {
                errors = errors.concat(validate({
                    key: key2,
                    value: light[key2],
                    valueSpec: { type: 'string' },
                    style,
                    styleSpec
                }));
            } else if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {
                errors = errors.concat(validate({
                    key: key2,
                    value: light[key2],
                    valueSpec: styleSpec.transition,
                    style,
                    styleSpec
                }));
            } else if (lightSpec[key2]) {
                errors = errors.concat(validate({
                    key: key2,
                    value: light[key2],
                    valueSpec: lightSpec[key2],
                    style,
                    styleSpec
                }));
            } else {
                errors = errors.concat([new index.G(key2, light[key2], `unknown property "${ key2 }"`)]);
            }
        }
    }
    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 = index.H(terrain);
    if (terrain === void 0) {
        return errors;
    } else if (rootType === 'null') {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new index.V('terrain', terrain, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key2 in terrain) {
        const transitionMatch = key2.match(/^(.*)-transition$/);
        const useThemeMatch = key2.match(/^(.*)-use-theme$/);
        if (useThemeMatch && terrainSpec[useThemeMatch[1]]) {
            errors = errors.concat(validate({
                key: key2,
                value: terrain[key2],
                valueSpec: { type: 'string' },
                style,
                styleSpec
            }));
        } else if (transitionMatch && terrainSpec[transitionMatch[1]] && terrainSpec[transitionMatch[1]].transition) {
            errors = errors.concat(validate({
                key: key2,
                value: terrain[key2],
                valueSpec: styleSpec.transition,
                style,
                styleSpec
            }));
        } else if (terrainSpec[key2]) {
            errors = errors.concat(validate({
                key: key2,
                value: terrain[key2],
                valueSpec: terrainSpec[key2],
                style,
                styleSpec
            }));
        } else {
            errors = errors.concat([new index.G(key2, terrain[key2], `unknown property "${ key2 }"`)]);
        }
    }
    if (!terrain.source) {
        errors.push(new index.V(key, terrain, `terrain is missing required property "source"`));
    } else {
        const source = style.sources && style.sources[terrain.source];
        const sourceType = source && index.K(source.type);
        if (!source) {
            errors.push(new index.V(key, terrain.source, `source "${ terrain.source }" not found`));
        } else if (sourceType !== 'raster-dem') {
            errors.push(new index.V(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 = index.H(fog);
    if (fog === void 0) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new index.V('fog', fog, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in fog) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        const useThemeMatch = key.match(/^(.*)-use-theme$/);
        if (useThemeMatch && fogSpec[useThemeMatch[1]]) {
            errors = errors.concat(validate({
                key,
                value: fog[key],
                valueSpec: { type: 'string' },
                style,
                styleSpec
            }));
        } else 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 index.G(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 = index.H(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 index.V('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': index.a2,
    'light': validateLight$1,
    'light-3d': validateLights$1,
    'terrain': validateTerrain$1,
    'fog': validateFog$1,
    'string': validateString,
    'formatted': validateFormatted,
    'resolvedImage': validateImage,
    'projection': validateProjection,
    'import': validateImport
};
function validate(options, arrayAsExpression = false) {
    const value = options.value;
    const valueSpec = options.valueSpec;
    const styleSpec = options.styleSpec;
    if (valueSpec.expression && index.a0(index.K(value))) {
        return validateFunction(options);
    } else if (valueSpec.expression && index.O(index.Q(value))) {
        return validateExpression(options);
    } else if (valueSpec.type && VALIDATORS[valueSpec.type]) {
        const valid = VALIDATORS[valueSpec.type](options);
        if (arrayAsExpression === true && valid.length > 0 && index.H(options.value) === 'array') {
            return validateExpression(options);
        } else {
            return valid;
        }
    } else {
        const valid = validateObject(index.J({}, 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 index.V(key, value, '"glyphs" url must include a "{fontstack}" token'));
    }
    if (value.indexOf('{range}') === -1) {
        errors.push(new index.V(key, value, '"glyphs" url must include a "{range}" token'));
    }
    return errors;
}

function validateStyle$1(style, styleSpec = index.a3, options = {}) {
    const errors = validate({
        key: options.key || '',
        value: style,
        valueSpec: styleSpec.$root,
        styleSpec,
        style,
        // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'objectElementValidators' does not exist in type 'ValidationOptions'.
        objectElementValidators: {
            glyphs: validateGlyphsURL,
            '*': () => []
        }
    });
    return errors;
}

function validateSnow$1(options) {
    const snow = options.value;
    const style = options.style;
    const styleSpec = options.styleSpec;
    const snowSpec = styleSpec.snow;
    let errors = [];
    const rootType = index.H(snow);
    if (snow === void 0) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new index.V('snow', snow, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in snow) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        if (transitionMatch && snowSpec[transitionMatch[1]] && snowSpec[transitionMatch[1]].transition) {
            errors = errors.concat(validate({
                key,
                value: snow[key],
                valueSpec: styleSpec.transition,
                style,
                styleSpec
            }));
        } else if (snowSpec[key]) {
            errors = errors.concat(validate({
                key,
                value: snow[key],
                valueSpec: snowSpec[key],
                style,
                styleSpec
            }));
        } else {
            errors = errors.concat([new index.G(key, snow[key], `unknown property "${ key }"`)]);
        }
    }
    return errors;
}

function validateRain$1(options) {
    const rain = options.value;
    const style = options.style;
    const styleSpec = options.styleSpec;
    const rainSpec = styleSpec.rain;
    let errors = [];
    const rootType = index.H(rain);
    if (rain === void 0) {
        return errors;
    } else if (rootType !== 'object') {
        errors = errors.concat([new index.V('rain', rain, `object expected, ${ rootType } found`)]);
        return errors;
    }
    for (const key in rain) {
        const transitionMatch = key.match(/^(.*)-transition$/);
        if (transitionMatch && rainSpec[transitionMatch[1]] && rainSpec[transitionMatch[1]].transition) {
            errors = errors.concat(validate({
                key,
                value: rain[key],
                valueSpec: styleSpec.transition,
                style,
                styleSpec
            }));
        } else if (rainSpec[key]) {
            errors = errors.concat(validate({
                key,
                value: rain[key],
                valueSpec: rainSpec[key],
                style,
                styleSpec
            }));
        } else {
            errors = errors.concat([new index.G(key, rain[key], `unknown property "${ key }"`)]);
        }
    }
    return errors;
}

function validateStyle(style, styleSpec = index.a3) {
    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 validateSnow = opts => sortErrors(validateSnow$1(opts));
const validateRain = opts => sortErrors(validateRain$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(index.a2(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) {
            if (error instanceof index.G) {
                index.w(error.message);
            } else {
                emitter.fire(new index.y(new Error(error.message)));
                hasErrors = true;
            }
        }
    }
    return hasErrors;
}

let properties$4;
const getProperties$4 = () => properties$4 || (properties$4 = new index.a5({
    'anchor': new index.a6(index.a3.light.anchor),
    'position': new index.a7(index.a3.light.position),
    'color': new index.a6(index.a3.light.color),
    'intensity': new index.a6(index.a3.light.intensity)
}));
class Light extends index.E {
    constructor(lightOptions, id = 'flat') {
        super();
        this._transitionable = new index.a4(getProperties$4());
        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, index.l({
            value,
            // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407
            style: {
                glyphs: true,
                sprite: true
            },
            styleSpec: index.a3
        })));
    }
}

const DrapeRenderMode = {
    deferred: 0,
    elevated: 1
};
let Terrain$1 = class Terrain extends index.E {
    constructor(terrainOptions, drapeRenderMode, scope, configOptions) {
        super();
        this.scope = scope;
        this._transitionable = new index.a4(new index.a5({
            'source': new index.a6(index.a3.terrain.source),
            'exaggeration': new index.a6(index.a3.terrain.exaggeration)
        }), scope, configOptions);
        this._transitionable.setTransitionOrValue(terrainOptions, configOptions);
        this._transitioning = this._transitionable.untransitioned();
        this.drapeRenderMode = drapeRenderMode;
    }
    get() {
        return this._transitionable.serialize();
    }
    set(terrain, configOptions) {
        this._transitionable.setTransitionOrValue(terrain, configOptions);
    }
    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 index.a8(atZoom)).get('exaggeration');
    }
    // For dynamic terrain, this is the zoom range when the terrain flattening (disabling) starts
    // and ends. At zoom above attenuationRange->max, terrain exaggeration is evaluated to 0.
    // The exaggeration used in terrain is smoothened from this value, and as terrain gets disabled
    // using smoothened curve, it effectivelly gets disabled at some value above attenuationRange->max
    // but that value is capped at ceil(attenuationRange->max).
    getAttenuationRange() {
        if (!this.isZoomDependent()) {
            return null;
        }
        const exaggeration = this._transitionable._values['exaggeration'];
        if (!exaggeration) {
            return null;
        }
        const expression = exaggeration.value.expression;
        if (!expression) {
            return null;
        }
        let zoomBeforeDrop = -1;
        let fullyDisabledZoom = -1;
        let theLastExaggeration = 1;
        const zeroExaggerationCutoff = 0.01;
        for (const zoom of expression.zoomStops) {
            theLastExaggeration = expression.evaluate(new index.a8(zoom));
            if (theLastExaggeration > zeroExaggerationCutoff) {
                zoomBeforeDrop = zoom;
                fullyDisabledZoom = -1;
            } else {
                fullyDisabledZoom = zoom;
            }
        }
        if (theLastExaggeration < zeroExaggerationCutoff && zoomBeforeDrop > 0 && fullyDisabledZoom > zoomBeforeDrop) {
            return [
                zoomBeforeDrop,
                fullyDisabledZoom
            ];
        }
        return null;
    }
    isZoomDependent() {
        const exaggeration = this._transitionable._values['exaggeration'];
        return exaggeration != null && exaggeration.value != null && exaggeration.value.expression != null && exaggeration.value.expression instanceof index.a9;
    }
};

const FOG_PITCH_START = 45;
const FOG_PITCH_END = 65;
const FOG_SYMBOL_CLIPPING_THRESHOLD = 0.9;
const FOG_OPACITY_THRESHOLD = 0.05;
function getFogOpacity(state, depth, pitch, fov) {
    const fogPitchOpacity = index.ac(FOG_PITCH_START, FOG_PITCH_END, pitch);
    const [start, end] = getFovAdjustedFogRange(state, fov);
    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) {
    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
    ];
    index.ab.vec3.transformMat4(pos, pos, mat);
    return getFogOpacity(state, index.ab.vec3.length(pos), transform.pitch, transform._fov);
}
function getFogOpacityAtLngLat(state, lngLat, transform) {
    const meters = index.aa.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 = index.ab.vec3.transformMat4([], [
        x,
        y,
        elevation
    ], transform.mercatorFogMatrix);
    return getFogOpacity(state, index.ab.vec3.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 = index.ab.vec3.transformMat4([], point, matrix);
        const distance = index.ab.vec3.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)
    ];
}

class Fog extends index.E {
    constructor(fogOptions, transform, scope, configOptions) {
        super();
        const fogProperties = new index.a5({
            'range': new index.a6(index.a3.fog.range),
            'color': new index.a6(index.a3.fog.color),
            'color-use-theme': new index.a6({
                'type': 'string',
                'property-type': 'data-constant',
                'default': 'default'
            }),
            'high-color': new index.a6(index.a3.fog['high-color']),
            'high-color-use-theme': new index.a6({
                'type': 'string',
                'property-type': 'data-constant',
                'default': 'default'
            }),
            'space-color': new index.a6(index.a3.fog['space-color']),
            'space-color-use-theme': new index.a6({
                'type': 'string',
                'property-type': 'data-constant',
                'default': 'default'
            }),
            'horizon-blend': new index.a6(index.a3.fog['horizon-blend']),
            'star-intensity': new index.a6(index.a3.fog['star-intensity']),
            'vertical-range': new index.a6(index.a3.fog['vertical-range'])
        });
        this._transitionable = new index.a4(fogProperties, scope, new Map(configOptions));
        this.set(fogOptions, configOptions);
        this._transitioning = this._transitionable.untransitioned();
        this._transform = transform;
        this.properties = new index.ad(fogProperties);
        this.scope = scope;
    }
    get state() {
        const tr = this._transform;
        const isGlobe = tr.projection.name === 'globe';
        const transitionT = index.ae(tr.zoom);
        const range = this.properties.get('range');
        const globeFixedFogRange = [
            0.5,
            3
        ];
        return {
            range: isGlobe ? [
                index.af(globeFixedFogRange[0], range[0], transitionT),
                index.af(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, configOptions, options = {}) {
        if (this._validate(validateFog, fog, options)) {
            return;
        }
        const properties = index.l({}, fog);
        for (const name of Object.keys(index.a3.fog)) {
            if (properties[name] === void 0) {
                properties[name] = index.a3.fog[name].default;
            }
        }
        this._options = properties;
        this._transitionable.setTransitionOrValue(this._options, configOptions);
    }
    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 : index.ac(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, index.ag, index.ag, 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) {
        if (!this._transform.projection.supportsFog)
            return [
                0,
                1
            ];
        return getFovAdjustedFogRange(this.state, fov);
    }
    isVisibleOnFrustum(frustum) {
        if (!this._transform.projection.supportsFog)
            return false;
        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 = index.ah(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;
    }
    updateConfig(configOptions) {
        this._transitionable.setTransitionOrValue(this._options, 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);
    }
    _validate(validate, value, options) {
        if (options && options.validate === false) {
            return false;
        }
        return emitValidationErrors$1(this, validate.call(validateStyle, index.l({
            value,
            style: {
                glyphs: true,
                sprite: true
            },
            styleSpec: index.a3
        })));
    }
}

let properties$3;
const getProperties$3 = () => properties$3 || (properties$3 = new index.a5({
    'density': new index.a6(index.a3['snow']['density']),
    'intensity': new index.a6(index.a3['snow']['intensity']),
    'color': new index.a6(index.a3['snow']['color']),
    'opacity': new index.a6(index.a3['snow']['opacity']),
    'vignette': new index.a6(index.a3['snow']['vignette']),
    'vignette-color': new index.a6(index.a3['snow']['vignette-color']),
    'center-thinning': new index.a6(index.a3['snow']['center-thinning']),
    'direction': new index.a6(index.a3['snow']['direction']),
    'flake-size': new index.a6(index.a3['snow']['flake-size'])
}));

let Snow$1 = class Snow extends index.E {
    constructor(snowOptions, transform, scope, configOptions) {
        super();
        const snowProperties = getProperties$3();
        this._transitionable = new index.a4(snowProperties, scope, new Map(configOptions));
        this.set(snowOptions, configOptions);
        this._transitioning = this._transitionable.untransitioned();
        this.properties = new index.ad(snowProperties);
        this.scope = scope;
    }
    get state() {
        const opacity = this.properties.get('opacity');
        const color = this.properties.get('color');
        const directionAngles = this.properties.get('direction');
        const heading = index.ai(directionAngles[0]);
        const pitch = -Math.max(index.ai(directionAngles[1]), 0.01);
        const direction = [
            Math.cos(heading) * Math.cos(pitch),
            Math.sin(heading) * Math.cos(pitch),
            Math.sin(pitch)
        ];
        const vignetteIntensity = this.properties.get('vignette');
        const vignetteColor = this.properties.get('vignette-color');
        vignetteColor.a = vignetteIntensity;
        return {
            density: this.properties.get('density'),
            intensity: this.properties.get('intensity'),
            color: new index.aj(color.r, color.g, color.b, color.a * opacity),
            direction,
            centerThinning: this.properties.get('center-thinning'),
            flakeSize: this.properties.get('flake-size'),
            vignetteColor
        };
    }
    get() {
        return this._transitionable.serialize();
    }
    set(snow, configOptions, options = {}) {
        if (this._validate(validateSnow, snow, options)) {
            return;
        }
        const properties = index.l({}, snow);
        for (const name of Object.keys(index.a3.snow)) {
            if (properties[name] === void 0) {
                properties[name] = index.a3.snow[name].default;
            }
        }
        this._options = properties;
        this._transitionable.setTransitionOrValue(this._options, configOptions);
    }
    updateConfig(configOptions) {
        this._transitionable.setTransitionOrValue(this._options, 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);
    }
    _validate(validate, value, options) {
        if (options && options.validate === false) {
            return false;
        }
        return emitValidationErrors$1(this, validate.call(validateStyle, index.l({
            value,
            style: {
                glyphs: true,
                sprite: true
            },
            styleSpec: index.a3
        })));
    }
};

let properties$2;
const getProperties$2 = () => properties$2 || (properties$2 = new index.a5({
    'density': new index.a6(index.a3['rain']['density']),
    'intensity': new index.a6(index.a3['rain']['intensity']),
    'color': new index.a6(index.a3['rain']['color']),
    'opacity': new index.a6(index.a3['rain']['opacity']),
    'vignette': new index.a6(index.a3['rain']['vignette']),
    'vignette-color': new index.a6(index.a3['rain']['vignette-color']),
    'center-thinning': new index.a6(index.a3['rain']['center-thinning']),
    'direction': new index.a6(index.a3['rain']['direction']),
    'droplet-size': new index.a6(index.a3['rain']['droplet-size']),
    'distortion-strength': new index.a6(index.a3['rain']['distortion-strength'])
}));

let Rain$1 = class Rain extends index.E {
    constructor(rainOptions, transform, scope, configOptions) {
        super();
        const rainProperties = getProperties$2();
        this._transitionable = new index.a4(rainProperties, scope, new Map(configOptions));
        this.set(rainOptions, configOptions);
        this._transitioning = this._transitionable.untransitioned();
        this.properties = new index.ad(rainProperties);
        this.scope = scope;
    }
    get state() {
        const opacity = this.properties.get('opacity');
        const color = this.properties.get('color');
        const directionAngles = this.properties.get('direction');
        const heading = index.ai(directionAngles[0]);
        const pitch = -Math.max(index.ai(directionAngles[1]), 0.01);
        const direction = [
            Math.cos(heading) * Math.cos(pitch),
            Math.sin(heading) * Math.cos(pitch),
            Math.sin(pitch)
        ];
        const vignetteColor = this.properties.get('vignette-color');
        vignetteColor.a = this.properties.get('vignette');
        return {
            density: this.properties.get('density'),
            intensity: this.properties.get('intensity'),
            color: new index.aj(color.r, color.g, color.b, color.a * opacity),
            direction,
            centerThinning: this.properties.get('center-thinning'),
            dropletSize: this.properties.get('droplet-size'),
            distortionStrength: this.properties.get('distortion-strength'),
            vignetteColor
        };
    }
    get() {
        return this._transitionable.serialize();
    }
    set(rain, configOptions, options = {}) {
        if (this._validate(validateRain, rain, options)) {
            return;
        }
        const properties = index.l({}, rain);
        for (const name of Object.keys(index.a3.rain)) {
            if (properties[name] === void 0) {
                properties[name] = index.a3.rain[name].default;
            }
        }
        this._options = properties;
        this._transitionable.setTransitionOrValue(this._options, configOptions);
    }
    updateConfig(configOptions) {
        this._transitionable.setTransitionOrValue(this._options, 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);
    }
    _validate(validate, value, options) {
        if (options && options.validate === false) {
            return false;
        }
        return emitValidationErrors$1(this, validate.call(validateStyle, index.l({
            value,
            style: {
                glyphs: true,
                sprite: true
            },
            styleSpec: index.a3
        })));
    }
};

class Lights extends index.E {
    constructor(options, properties, scope, configOptions) {
        super();
        this.scope = scope;
        this._options = options;
        this.properties = new index.ad(properties);
        this._transitionable = new index.a4(properties, scope, 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;
    }
}

let properties$1;
const getProperties$1 = () => properties$1 || (properties$1 = new index.a5({
    'color': new index.a6(index.a3['properties_light_ambient']['color']),
    'color-use-theme': new index.a6({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-constant'
    }),
    'intensity': new index.a6(index.a3['properties_light_ambient']['intensity'])
}));

let properties;
const getProperties = () => properties || (properties = new index.a5({
    'direction': new index.ak(index.a3['properties_light_directional']['direction']),
    'color': new index.a6(index.a3['properties_light_directional']['color']),
    'color-use-theme': new index.a6({
        'type': 'string',
        'default': 'default',
        'property-type': 'data-constant'
    }),
    'intensity': new index.a6(index.a3['properties_light_directional']['intensity']),
    'cast-shadows': new index.a6(index.a3['properties_light_directional']['cast-shadows']),
    'shadow-quality': new index.a6(index.a3['properties_light_directional']['shadow-quality']),
    'shadow-intensity': new index.a6(index.a3['properties_light_directional']['shadow-intensity'])
}));

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;
        if (geometry instanceof index.P || typeof geometry[0] === 'number') {
            const pt = index.P.convert(geometry);
            screenGeometry = [pt];
            aboveHorizon = transform.isPointAboveHorizon(pt);
        } else {
            const tl = index.P.convert(geometry[0]);
            const br = index.P.convert(geometry[1]);
            screenGeometry = [
                tl,
                br
            ];
            aboveHorizon = index.al(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 index.al(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 index.P(1, 1)) : this.screenBounds[1];
        const cameraPolygon = index.al(min, max, 0, false);
        if (this.cameraPoint.y > max.y) {
            if (this.cameraPoint.x > min.x && this.cameraPoint.x < max.x) {
                cameraPolygon.splice(3, 0, this.cameraPoint);
            } else if (this.cameraPoint.x >= max.x) {
                cameraPolygon[2] = this.cameraPoint;
            } else if (this.cameraPoint.x <= min.x) {
                cameraPolygon[3] = this.cameraPoint;
            }
        }
        return index.am(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 index.P(1, 1)) : this.screenBounds[1];
        const cameraPolygon = index.al(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:
            cameraPolygon[0] = camPos;
            cameraPolygon[4] = camPos.clone();
            break;
        case 1:
            cameraPolygon.splice(1, 0, camPos);
            break;
        case 2:
            cameraPolygon[1] = camPos;
            break;
        case 3:
            cameraPolygon.splice(4, 0, camPos);
            break;
        case 5:
            cameraPolygon.splice(2, 0, camPos);
            break;
        case 6:
            cameraPolygon[3] = camPos;
            break;
        case 7:
            cameraPolygon.splice(3, 0, camPos);
            break;
        case 8:
            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) {
        const bias = 1;
        const padding = tile.queryPadding / transform._pixelsPerMercatorPixel + bias;
        const cachedQuery = use3D ? this._bufferedCameraMercator(padding, transform) : this._bufferedScreenMercator(padding, transform);
        let wrap2 = tile.tileID.wrap + (cachedQuery.unwrapped ? cameraWrap : 0);
        const geometryForTileCheck = cachedQuery.polygon.map(p => index.an(tile.tileTransform, p, wrap2));
        if (!index.ao(geometryForTileCheck, 0, 0, index.ag, index.ag)) {
            return void 0;
        }
        wrap2 = tile.tileID.wrap + (this.screenGeometryMercator.unwrapped ? cameraWrap : 0);
        const tilespaceVec3s = this.screenGeometryMercator.polygon.map(p => index.ap(tile.tileTransform, p, wrap2));
        const tilespaceGeometry = tilespaceVec3s.map(v => new index.P(v[0], v[1]));
        const cameraMercator = transform.getFreeCameraOptions().position || new index.aa(0, 0, 0);
        const tilespaceCameraPosition = index.ap(tile.tileTransform, cameraMercator, wrap2);
        const tilespaceRays = tilespaceVec3s.map(tileVec => {
            const dir = index.ab.vec3.sub(tileVec, tileVec, tilespaceCameraPosition);
            index.ab.vec3.normalize(dir, dir);
            return new index.aq(tilespaceCameraPosition, dir);
        });
        const pixelToTileUnitsFactor = index.ar(tile, 1, transform.zoom) * transform._pixelsPerMercatorPixel;
        return {
            queryGeometry: this,
            tilespaceGeometry,
            tilespaceRays,
            bufferedTilespaceGeometry: geometryForTileCheck,
            bufferedTilespaceBounds: clampBoundsToTileExtents(index.as(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) {
        const polePolygon = projectPolygonCoveringPoles(polygon, transform);
        if (polePolygon) {
            return polePolygon;
        }
        const resampled = unwrapQueryPolygon(resamplePolygon(polygon, transform).map(p => new index.P(wrap(p.x), p.y)), transform);
        return {
            polygon: resampled.polygon.map(p => new index.aa(p.x, p.y)),
            unwrapped: resampled.unwrapped
        };
    }
}
function unwrapQueryPolygon(polygon, tr) {
    let unwrapped = false;
    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) {
            if (a.x < b.x) {
                a.x += 1;
                if (edge === 0) {
                    polygon[polygon.length - 1].x += 1;
                }
            } else {
                b.x += 1;
                if (edge + 1 === polygon.length - 1) {
                    polygon[0].x += 1;
                }
            }
            unwrapped = true;
        }
    }
    const cameraX = index.at(tr.center.lng);
    if (unwrapped && cameraX < Math.abs(cameraX - 1)) {
        polygon.forEach(p => {
            p.x -= 1;
        });
    }
    return {
        polygon,
        unwrapped
    };
}
function projectPolygonCoveringPoles(polygon, tr) {
    const matrix = index.ab.mat4.multiply([], tr.pixelMatrix, tr.globeMatrix);
    const northPole = [
        0,
        -index.ax,
        0,
        1
    ];
    const southPole = [
        0,
        index.ax,
        0,
        1
    ];
    const center = [
        0,
        0,
        0,
        1
    ];
    index.ab.vec4.transformMat4(northPole, northPole, matrix);
    index.ab.vec4.transformMat4(southPole, southPole, matrix);
    index.ab.vec4.transformMat4(center, center, matrix);
    const screenNp = new index.P(northPole[0] / northPole[3], northPole[1] / northPole[3]);
    const screenSp = new index.P(southPole[0] / southPole[3], southPole[1] / southPole[3]);
    const containsNp = index.au(polygon, screenNp) && northPole[3] < center[3];
    const containsSp = index.au(polygon, screenSp) && southPole[3] < center[3];
    if (!containsNp && !containsSp) {
        return null;
    }
    const result = findEdgeCrossingAntimeridian(polygon, tr, containsNp ? -1 : 1);
    if (!result) {
        return null;
    }
    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 index.P(wrap(p.x), p.y));
    partB = partB.map(p => new index.P(wrap(p.x), p.y));
    const resampled = [...partA];
    if (resampled.length === 0) {
        resampled.push(partB[partB.length - 1]);
    }
    const a = resampled[resampled.length - 1];
    const b = partB.length === 0 ? partA[0] : partB[0];
    const intersectionY = index.af(a.y, b.y, t);
    let mid;
    if (containsNp) {
        mid = [
            new index.P(0, intersectionY),
            new index.P(0, 0),
            new index.P(1, 0),
            new index.P(1, intersectionY)
        ];
    } else {
        mid = [
            new index.P(1, intersectionY),
            new index.P(1, 1),
            new index.P(0, 1),
            new index.P(0, intersectionY)
        ];
    }
    resampled.push(...mid);
    if (partB.length === 0) {
        resampled.push(partA[0]);
    } else {
        resampled.push(...partB);
    }
    return {
        polygon: resampled.map(p => new index.aa(p.x, p.y)),
        unwrapped: false
    };
}
function resamplePolygon(polygon, transform) {
    const tolerance = 1 / 256;
    return index.av(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);
        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;
}
function cacheKey(padding) {
    return padding * 100 | 0;
}
function clampBoundsToTileExtents(bounds) {
    bounds.min.x = index.aw(bounds.min.x, 0, index.ag);
    bounds.min.y = index.aw(bounds.min.y, 0, index.ag);
    bounds.max.x = index.aw(bounds.max.x, 0, index.ag);
    bounds.max.y = index.aw(bounds.max.y, 0, index.ag);
    return bounds;
}

function getInlinedTileJSON(data, language, worldview) {
    if (!data) {
        return null;
    }
    if (!language && !worldview) {
        return data;
    }
    worldview = worldview || data.worldview_default;
    const tileJSONLanguages = Object.values(data.language || {});
    if (tileJSONLanguages.length === 0) {
        return null;
    }
    const tileJSONWorldviews = Object.values(data.worldview || {});
    if (tileJSONWorldviews.length === 0) {
        return null;
    }
    const isLanguageMatched = tileJSONLanguages.every(lang => lang === language);
    const isWorldviewMatched = tileJSONWorldviews.every(vw => vw === worldview);
    if (isLanguageMatched && isWorldviewMatched) {
        return data;
    }
    if (!(language in (data.language_options || {})) && !(worldview in (data.worldview_options || {}))) {
        if (!data.language_options || !data.worldview_options) {
            return null;
        }
        return data;
    }
    return null;
}
function loadTileJSON (options, requestManager, language, worldview, callback) {
    const loaded = function (err, tileJSON) {
        if (err) {
            return callback(err);
        } else if (tileJSON) {
            if (options.url && tileJSON.tiles && options.tiles)
                delete options.tiles;
            if (tileJSON.variants) {
                if (!Array.isArray(tileJSON.variants)) {
                    return callback(new Error('variants must be an array'));
                }
                for (const variant of tileJSON.variants) {
                    if (variant == null || typeof variant !== 'object' || variant.constructor !== Object) {
                        return callback(new Error('variant must be an object'));
                    }
                    if (!Array.isArray(variant.capabilities)) {
                        return callback(new Error('capabilities must be an array'));
                    }
                    if (variant.capabilities.length === 1 && variant.capabilities[0] === 'meshopt') {
                        tileJSON = index.l(tileJSON, variant);
                        break;
                    }
                }
            }
            const result = index.ay(// explicit source options take precedence over TileJSON
            index.l({}, tileJSON, options), [
                'tilejson',
                'tiles',
                'minzoom',
                'maxzoom',
                'attribution',
                'mapbox_logo',
                'bounds',
                'scheme',
                'tileSize',
                'encoding',
                'vector_layers',
                'raster_layers',
                'worldview_options',
                'worldview_default',
                'worldview'
            ]);
            result.tiles = requestManager.canonicalizeTileset(result, options.url);
            callback(null, result);
        }
    };
    const inlinedTileJSON = getInlinedTileJSON(options.data, language, worldview);
    if (inlinedTileJSON) {
        return index.q.frame(() => loaded(null, inlinedTileJSON));
    }
    if (options.url) {
        return index.n(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url, null, language, worldview), index.R.Source), loaded);
    } else {
        return index.q.frame(() => {
            const {data, ...tileJSON} = options;
            loaded(null, tileJSON);
        });
    }
}

class TileBounds {
    constructor(bounds, minzoom, maxzoom) {
        this.bounds = index.az.convert(this.validateBounds(bounds));
        this.minzoom = minzoom || 0;
        this.maxzoom = maxzoom || 24;
    }
    validateBounds(bounds) {
        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(index.at(this.bounds.getWest()) * worldSize),
            minY: Math.floor(index.aA(this.bounds.getNorth()) * worldSize),
            maxX: Math.ceil(index.at(this.bounds.getEast()) * worldSize),
            maxY: Math.ceil(index.aA(this.bounds.getSouth()) * worldSize)
        };
        const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
        return hit;
    }
}

class VectorTileSource extends index.E {
    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;
        index.l(this, index.ay(options, [
            'url',
            'scheme',
            'tileSize',
            'promoteId'
        ]));
        this._options = index.l({ 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 index.aB();
    }
    load(callback) {
        this._loaded = false;
        this.fire(new index.z('dataloading', { dataType: 'source' }));
        const language = Array.isArray(this.map._language) ? this.map._language.join() : this.map._language;
        const worldview = this.map.getWorldview();
        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)
                    console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${ worldview }`);
                this.fire(new index.y(err));
            } else if (tileJSON) {
                index.l(this, tileJSON);
                this.hasWorldviews = !!tileJSON.worldview_options;
                if (tileJSON.worldview_default) {
                    this.worldviewDefault = tileJSON.worldview_default;
                }
                if (tileJSON.vector_layers) {
                    this.vectorLayers = tileJSON.vector_layers;
                    this.vectorLayerIds = [];
                    this.localizableLayerIds = /* @__PURE__ */
                    new Set();
                    for (const layer of tileJSON.vector_layers) {
                        this.vectorLayerIds.push(layer.id);
                        if (tileJSON.worldview && tileJSON.worldview[layer.source]) {
                            this.localizableLayerIds.add(layer.id);
                        }
                    }
                }
                if (tileJSON.bounds)
                    this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
                postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);
                this.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'metadata'
                }));
                this.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'content'
                }));
            }
            if (callback)
                callback(err);
        });
    }
    loaded() {
        return this._loaded;
    }
    hasTile(tileID) {
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    onAdd(map) {
        this.map = map;
        this.load();
    }
    /**
   * Reloads the source data and re-renders the map.
   *
   * @example
   * map.getSource('source-id').reload();
   */
    reload() {
        this.cancelTileJSONRequest();
        const fqid = index.aC(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;
    }
    onRemove(_) {
        this.cancelTileJSONRequest();
    }
    serialize() {
        return index.l({}, this._options);
    }
    loadTile(tile, callback) {
        const tileUrl = tile.tileID.canonical.url(this.tiles, this.scheme);
        const url = this.map._requestManager.normalizeTileURL(tileUrl);
        const request = this.map._requestManager.transformRequest(url, index.R.Tile);
        const lutForScope = this.map.style ? this.map.style.getLut(this.scope) : null;
        const lut = lutForScope ? { image: lutForScope.image.clone() } : null;
        const params = {
            request,
            data: void 0,
            uid: tile.uid,
            tileID: tile.tileID,
            tileZoom: tile.tileZoom,
            zoom: tile.tileID.overscaledZ,
            maxZoom: this.maxzoom,
            lut,
            tileSize: this.tileSize * tile.tileID.overscaleFactor(),
            type: this.type,
            source: this.id,
            scope: this.scope,
            pixelRatio: index.q.devicePixelRatio,
            showCollisionBoxes: this.map.showCollisionBoxes,
            promoteId: this.promoteId,
            isSymbolTile: tile.isSymbolTile,
            brightness: this.map.style ? this.map.style.getBrightness() || 0 : 0,
            extraShadowCaster: tile.isExtraShadowCaster,
            tessellationStep: this.map._tessellationStep,
            scaleFactor: this.map.getScaleFactor()
        };
        if (this.hasWorldviews && index.f(tileUrl)) {
            params.worldview = this.map.getWorldview() || this.worldviewDefault;
            params.localizableLayerIds = this.localizableLayerIds;
        }
        params.request.collectResourceTiming = this._collectResourceTiming;
        if (!tile.actor || tile.state === 'expired') {
            tile.actor = this._tileWorkers[url] = this._tileWorkers[url] || this.dispatcher.getActor();
            if (!this.dispatcher.ready) {
                const cancel = index.aD.call({ deduped: this._deduped }, params, (err, data) => {
                    if (err || !data) {
                        done.call(this, err);
                    } else {
                        params.data = {
                            cacheControl: data.cacheControl,
                            expires: data.expires,
                            rawData: data.rawData.slice(0)
                        };
                        if (tile.actor)
                            tile.actor.send('loadTile', params, done.bind(this), void 0, true);
                    }
                }, true);
                tile.request = { cancel };
            } else {
                tile.request = tile.actor.send('loadTile', params, done.bind(this), void 0, true);
            }
        } else if (tile.state === 'loading') {
            tile.reloadCallback = callback;
        } else {
            tile.request = tile.actor.send('reloadTile', params, done.bind(this));
        }
        function done(err, data) {
            delete tile.request;
            if (tile.aborted)
                return callback(null);
            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);
            index.aE(this.dispatcher);
            callback(null);
            if (tile.reloadCallback) {
                this.loadTile(tile, tile.reloadCallback);
                tile.reloadCallback = null;
            }
        }
    }
    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
            });
        }
    }
    unloadTile(tile, _) {
        if (tile.actor) {
            tile.actor.send('removeTile', {
                uid: tile.uid,
                type: this.type,
                source: this.id,
                scope: this.scope
            });
        }
        tile.destroy();
    }
    hasTransition() {
        return false;
    }
    afterUpdate() {
        this._tileWorkers = {};
    }
    cancelTileJSONRequest() {
        if (!this._tileJSONRequest)
            return;
        this._tileJSONRequest.cancel();
        this._tileJSONRequest = null;
    }
}

class RasterTileSource extends index.E {
    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 = index.l({ type: 'raster' }, options);
        index.l(this, index.ay(options, [
            'url',
            'scheme',
            'tileSize'
        ]));
    }
    load(callback) {
        this._loaded = false;
        this.fire(new index.z('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 index.y(err));
            } else if (tileJSON) {
                index.l(this, tileJSON);
                if (tileJSON.raster_layers) {
                    this.rasterLayers = tileJSON.raster_layers;
                    this.rasterLayerIds = this.rasterLayers.map(layer => layer.id);
                }
                if (tileJSON.bounds)
                    this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
                postTurnstileEvent(tileJSON.tiles);
                this.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'metadata'
                }));
                this.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'content'
                }));
            }
            if (callback)
                callback(err);
        });
    }
    loaded() {
        return this._loaded;
    }
    onAdd(map) {
        this.map = map;
        this.load();
    }
    /**
   * Reloads the source data and re-renders the map.
   *
   * @example
   * map.getSource('source-id').reload();
   */
    reload() {
        this.cancelTileJSONRequest();
        const fqid = index.aC(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;
    }
    onRemove(_) {
        this.cancelTileJSONRequest();
    }
    serialize() {
        return index.l({}, this._options);
    }
    hasTile(tileID) {
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    loadTile(tile, callback) {
        const use2x = index.q.devicePixelRatio >= 2;
        const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), use2x, this.tileSize);
        tile.request = index.o(this.map._requestManager.transformRequest(url, index.R.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';
            index.aE(this.dispatcher);
            callback(null);
        });
    }
    abortTile(tile, callback) {
        if (tile.request) {
            tile.request.cancel();
            delete tile.request;
        }
        if (callback)
            callback();
    }
    unloadTile(tile, callback) {
        if (tile.texture && tile.texture instanceof index.T) {
            tile.destroy(true);
            if (tile.texture && tile.texture instanceof index.T) {
                this.map.painter.saveTileTexture(tile.texture);
            }
        } else {
            tile.destroy();
        }
        if (callback)
            callback();
    }
    hasTransition() {
        return false;
    }
    cancelTileJSONRequest() {
        if (!this._tileJSONRequest)
            return;
        this._tileJSONRequest.cancel();
        this._tileJSONRequest = null;
    }
}

class RasterDEMTileSource extends RasterTileSource {
    constructor(id, options, dispatcher, eventedParent) {
        super(id, options, dispatcher, eventedParent);
        this.type = 'raster-dem';
        this.maxzoom = 22;
        this._options = index.l({ 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 = index.o(this.map._requestManager.transformRequest(url, index.R.Tile), imageLoaded.bind(this));
        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 = ImageBitmap && img instanceof ImageBitmap && index.t();
                const buffer = (img.width - index.aF(img.width)) / 2;
                const padding = 1 - buffer;
                const borderReady = padding < 1;
                if (!borderReady && !tile.neighboringTiles) {
                    tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);
                }
                const rawImageData = transfer ? img : index.q.getImageData(img, padding);
                const params = {
                    uid: tile.uid,
                    coord: tile.tileID,
                    source: this.id,
                    scope: this.scope,
                    rawImageData,
                    encoding: this.encoding,
                    padding
                };
                if (!tile.actor || tile.state === 'expired') {
                    tile.actor = this.dispatcher.getActor();
                    tile.actor.send('loadDEMTile', params, done.bind(this), void 0, true);
                }
            }
        }
        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 = {};
        neighboringTiles[new index.aG(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false };
        neighboringTiles[new index.aG(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false };
        if (canonical.y > 0) {
            neighboringTiles[new index.aG(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false };
            neighboringTiles[new index.aG(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false };
            neighboringTiles[new index.aG(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false };
        }
        if (canonical.y + 1 < dim) {
            neighboringTiles[new index.aG(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false };
            neighboringTiles[new index.aG(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false };
            neighboringTiles[new index.aG(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false };
        }
        return neighboringTiles;
    }
}

class RasterArrayTileSource extends RasterTileSource {
    constructor(id, options, dispatcher, eventedParent) {
        super(id, options, dispatcher, eventedParent);
        this.type = 'raster-array';
        this.maxzoom = 22;
        this._options = index.l({ type: 'raster-array' }, options);
    }
    triggerRepaint(tile) {
        const terrain = this.map.painter._terrain;
        const sourceCache = this.map.style.getSourceCache(this.id);
        if (terrain && terrain.enabled && sourceCache) {
            terrain._clearRenderCacheForTile(sourceCache.id, tile.tileID);
        }
        this.map.triggerRepaint();
    }
    loadTile(tile, callback) {
        tile = tile;
        const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), false, this.tileSize);
        const requestParams = this.map._requestManager.transformRequest(url, index.R.Tile);
        tile.requestParams = requestParams;
        if (!tile.actor)
            tile.actor = this.dispatcher.getActor();
        tile.request = tile.fetchHeader(void 0, (error, dataBuffer, cacheControl, expires) => {
            delete tile.request;
            if (tile.aborted) {
                tile.state = 'unloaded';
                return callback(null);
            }
            if (error) {
                if (error.code === 20)
                    return;
                tile.state = 'errored';
                return callback(error);
            }
            if (this.map._refreshExpiredTiles)
                tile.setExpiryData({
                    cacheControl,
                    expires
                });
            tile.state = 'empty';
            callback(null);
        });
    }
    unloadTile(tile, _) {
        tile = tile;
        const texture = tile.texture;
        if (texture && texture instanceof index.T) {
            tile.destroy(true);
            this.map.painter.saveTileTexture(texture);
        } else {
            tile.destroy();
            tile.flushQueues();
            tile._isHeaderLoaded = false;
            delete tile._mrt;
            delete tile.textureDescriptor;
        }
        if (tile.fbo) {
            tile.fbo.destroy();
            delete tile.fbo;
        }
        delete tile.request;
        delete tile.requestParams;
        delete tile.neighboringTiles;
        tile.state = 'unloaded';
    }
    /**
   * Prepare RasterArrayTile for the rendering. If tile doesn't have data
   * for the requested band, fetch and repaint once it's acquired.
   * @private
   */
    prepareTile(tile, sourceLayer, band) {
        if (!tile._isHeaderLoaded)
            return;
        if (tile.state !== 'empty')
            tile.state = 'reloading';
        tile.fetchBand(sourceLayer, band, (error, data) => {
            if (error) {
                tile.state = 'errored';
                this.fire(new index.y(error));
                this.triggerRepaint(tile);
                return;
            }
            if (data) {
                tile.setTexture(data, this.map.painter);
                tile.state = 'loaded';
                this.triggerRepaint(tile);
            }
        });
    }
    /**
   * Get the initial band for a source layer.
   * @private
   */
    getInitialBand(sourceLayer) {
        if (!this.rasterLayers)
            return 0;
        const rasterLayer = this.rasterLayers.find(({id}) => id === sourceLayer);
        const fields = rasterLayer && rasterLayer.fields;
        const bands = fields && fields.bands && fields.bands;
        return bands ? bands[0] : 0;
    }
    /**
   * Get a texture descriptor for a source layer and a band.
   * @private
   * @param {RasterArrayTile} tile
   * @param {RasterStyleLayer} layer
   * @param {boolean} fallbackToPrevious If true, return previous texture even if update is needed
   * @returns {TextureDescriptor} Texture descriptor with texture if available
   */
    getTextureDescriptor(tile, layer, fallbackToPrevious) {
        if (!tile)
            return;
        const sourceLayer = layer.sourceLayer || this.rasterLayerIds && this.rasterLayerIds[0];
        if (!sourceLayer)
            return;
        let layerBand = null;
        if (layer instanceof index.aH) {
            layerBand = layer.paint.get('raster-array-band');
        } else if (layer instanceof index.aI) {
            layerBand = layer.paint.get('raster-particle-array-band');
        }
        const band = layerBand || this.getInitialBand(sourceLayer);
        if (band == null)
            return;
        if (!tile.textureDescriptor) {
            this.prepareTile(tile, sourceLayer, band);
            return;
        }
        if (tile.updateNeeded(sourceLayer, band) && !fallbackToPrevious)
            return;
        return Object.assign({}, tile.textureDescriptor, { texture: tile.texture });
    }
}

class GeoJSONSource extends index.E {
    /**
   * @private
   */
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.id = id;
        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 = index.l({}, options);
        this._collectResourceTiming = options.collectResourceTiming;
        if (options.maxzoom !== void 0)
            this.maxzoom = options.maxzoom;
        if (options.minzoom !== void 0)
            this.minzoom = options.minzoom;
        if (options.type)
            this.type = options.type;
        if (options.attribution)
            this.attribution = options.attribution;
        this.promoteId = options.promoteId;
        const scale = index.ag / this.tileSize;
        this.workerOptions = index.l({
            source: this.id,
            scope: this.scope,
            cluster: options.cluster || false,
            geojsonVtOptions: {
                buffer: (options.buffer !== void 0 ? options.buffer : 128) * scale,
                tolerance: (options.tolerance !== void 0 ? options.tolerance : 0.375) * scale,
                extent: index.ag,
                maxZoom: this.maxzoom,
                lineMetrics: options.lineMetrics || false,
                generateId: options.generateId || false
            },
            superclusterOptions: {
                maxZoom: options.clusterMaxZoom !== void 0 ? options.clusterMaxZoom : this.maxzoom - 1,
                minPoints: Math.max(2, options.clusterMinPoints || 2),
                extent: index.ag,
                radius: (options.clusterRadius !== void 0 ? options.clusterRadius : 50) * scale,
                log: false,
                generateId: options.generateId || false
            },
            clusterProperties: options.clusterProperties,
            filter: options.filter,
            dynamic: options.dynamic
        }, options.workerOptions);
    }
    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;
    }
    /**
   * Updates the existing GeoJSON data with new features and re-renders the map.
   * Can only be used on sources with `dynamic: true` in options.
   * Updates features by their IDs:
   *
   * - If there's a feature with the same ID, overwrite it.
   * - If there's a feature with the same ID but the new one's geometry is `null`, remove it
   * - If there's no such ID in existing data, add it as a new feature.
   *
   * @param {Object | string} data A GeoJSON data object or a URL to one.
   * @returns {GeoJSONSource} Returns itself to allow for method chaining.
   * @example
   * // Update the feature with ID=123 in the existing GeoJSON source
   * map.getSource('source_id').updateData({
   *     "type": "FeatureCollection",
   *     "features": [{
   *         "id": 123,
   *         "type": "Feature",
   *         "properties": {"name": "Null Island"},
   *         "geometry": {
   *             "type": "Point",
   *             "coordinates": [ 0, 0 ]
   *         }
   *     }]
   * });
   */
    updateData(data) {
        if (!this._options.dynamic) {
            return this.fire(new index.y(new Error('Can\'t call updateData on a GeoJSON source with dynamic set to false.')));
        }
        if (typeof data !== 'string') {
            if (data.type === 'Feature') {
                data = {
                    type: 'FeatureCollection',
                    features: [data]
                };
            }
            if (data.type !== 'FeatureCollection') {
                return this.fire(new index.y(new Error('Data to update should be a feature or a feature collection.')));
            }
        }
        if (this._coalesce && typeof data !== 'string' && typeof this._data !== 'string' && this._data.type === 'FeatureCollection') {
            const featuresById = /* @__PURE__ */
            new Map();
            for (const feature of this._data.features)
                featuresById.set(feature.id, feature);
            for (const feature of data.features)
                featuresById.set(feature.id, feature);
            this._data.features = [...featuresById.values()];
        } else {
            this._data = data;
        }
        this._updateWorkerData(true);
        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(append = false) {
        if (this._pendingLoad) {
            this._coalesce = true;
            return;
        }
        this.fire(new index.z('dataloading', { dataType: 'source' }));
        this._loaded = false;
        const options = index.l({ append }, this.workerOptions);
        options.scope = this.scope;
        const data = this._data;
        if (typeof data === 'string') {
            options.request = this.map._requestManager.transformRequest(index.q.resolveURL(data), index.R.Source);
            options.request.collectResourceTiming = this._collectResourceTiming;
        } else {
            options.data = JSON.stringify(data);
        }
        this._pendingLoad = this.actor.send(`${ this.type }.loadData`, options, (err, result) => {
            this._loaded = true;
            this._pendingLoad = null;
            if (err) {
                this.fire(new index.y(err));
            } else {
                const data2 = {
                    dataType: 'source',
                    sourceDataType: this._metadataFired ? 'content' : 'metadata'
                };
                if (this._collectResourceTiming && result && result.resourceTiming && result.resourceTiming[this.id]) {
                    data2.resourceTiming = result.resourceTiming[this.id];
                }
                if (append)
                    this._partialReload = true;
                this.fire(new index.z('data', data2));
                this._partialReload = false;
                this._metadataFired = true;
            }
            if (this._coalesce) {
                this._updateWorkerData(append);
                this._coalesce = false;
            }
        });
    }
    loaded() {
        return this._loaded;
    }
    reload() {
        const fqid = index.aC(this.id, this.scope);
        this.map.style.clearSource(fqid);
        this._updateWorkerData();
    }
    loadTile(tile, callback) {
        const message = !tile.actor ? 'loadTile' : 'reloadTile';
        tile.actor = this.actor;
        const lutForScope = this.map.style ? this.map.style.getLut(this.scope) : null;
        const lut = lutForScope ? { image: lutForScope.image.clone() } : null;
        const partial = this._partialReload;
        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,
            lut,
            scope: this.scope,
            pixelRatio: index.q.devicePixelRatio,
            showCollisionBoxes: this.map.showCollisionBoxes,
            promoteId: this.promoteId,
            brightness: this.map.style ? this.map.style.getBrightness() || 0 : 0,
            scaleFactor: this.map.getScaleFactor(),
            partial
        };
        tile.request = this.actor.send(message, params, (err, data) => {
            if (partial && !data) {
                tile.state = 'loaded';
                return callback(null);
            }
            delete tile.request;
            tile.destroy();
            if (tile.aborted) {
                return callback(null);
            }
            if (err) {
                return callback(err);
            }
            tile.loadVectorData(data, this.map.painter, message === 'reloadTile');
            return callback(null);
        }, void 0, message === 'loadTile');
    }
    abortTile(tile) {
        if (tile.request) {
            tile.request.cancel();
            delete tile.request;
        }
        tile.aborted = true;
    }
    unloadTile(tile, _) {
        this.actor.send('removeTile', {
            uid: tile.uid,
            type: this.type,
            source: this.id,
            scope: this.scope
        });
        tile.destroy();
    }
    onRemove(_) {
        if (this._pendingLoad) {
            this._pendingLoad.cancel();
        }
    }
    serialize() {
        return index.l({}, this._options, {
            type: this.type,
            data: this._data
        });
    }
    hasTransition() {
        return false;
    }
}

class VideoSource extends index.aJ {
    /**
   * @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, index.R.Source).url);
        }
        index.aK(this.urls, (err, video) => {
            this._loaded = true;
            if (err) {
                this.fire(new index.y(err));
            } else if (video) {
                this.video = video;
                this.video.loop = true;
                this.video.setAttribute('playsinline', '');
                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 index.y(new index.V(`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;
        }
        const context = this.map.painter.context;
        const gl = context.gl;
        if (!this.texture) {
            this.texture = new index.T(context, this.video, gl.RGBA8);
            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;
    }
}

class CanvasSource extends index.aJ {
    /**
   * @private
   */
    constructor(id, options, dispatcher, eventedParent) {
        super(id, options, dispatcher, eventedParent);
        if (!options.coordinates) {
            this.fire(new index.y(new index.V(`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 index.y(new index.V(`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 index.y(new index.V(`sources.${ id }`, null, 'optional "animate" property must be a boolean value')));
        }
        if (!options.canvas) {
            this.fire(new index.y(new index.V(`sources.${ id }`, null, 'missing required property "canvas"')));
        } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) {
            this.fire(new index.y(new index.V(`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 !== void 0 ? 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 HTMLCanvasElement ? this.options.canvas : document.getElementById(this.options.canvas);
        }
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        if (this._hasInvalidDimensions()) {
            this.fire(new index.y(new Error('Canvas dimensions cannot be less than or equal to zero.')));
            return;
        }
        this.play = function () {
            this._playing = true;
            this.map.triggerRepaint();
        };
        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;
    }
    onAdd(map) {
        this.map = map;
        this.load();
        if (this.canvas) {
            if (this.animate)
                this.play();
        }
    }
    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
    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;
        const context = this.map.painter.context;
        if (!this.texture) {
            this.texture = new index.T(context, this.canvas, context.gl.RGBA8, { premultiply: true });
        } else if ((resize || this._playing) && !(this.texture instanceof index.aL)) {
            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 ImageData || data instanceof HTMLCanvasElement || data instanceof ImageBitmap || data instanceof HTMLImageElement;
}
class CustomSource extends index.E {
    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 index.y(new Error(`Missing implementation for ${ this.id } custom source`)));
        }
        if (!this._implementation.loadTile) {
            this.fire(new index.y(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);
        }
        implementation.update = this._update.bind(this);
        implementation.clearTiles = this._clearTiles.bind(this);
        implementation.coveringTiles = this._coveringTiles.bind(this);
        index.l(this, index.ay(implementation, [
            'dataType',
            'scheme',
            'minzoom',
            'maxzoom',
            'tileSize',
            'attribution',
            'minTileCacheSize',
            'maxTileCacheSize'
        ]));
    }
    serialize() {
        return index.ay(this, [
            'type',
            'scheme',
            'minzoom',
            'maxzoom',
            'tileSize',
            'attribution'
        ]);
    }
    load() {
        this._loaded = true;
        this.fire(new index.z('data', {
            dataType: 'source',
            sourceDataType: 'metadata'
        }));
        this.fire(new index.z('data', {
            dataType: 'source',
            sourceDataType: 'content'
        }));
    }
    loaded() {
        return this._loaded;
    }
    onAdd(map) {
        this.map = map;
        this._loaded = false;
        this.fire(new index.z('dataloading', { dataType: 'source' }));
        if (this._implementation.onAdd)
            this._implementation.onAdd(map);
        this.load();
    }
    onRemove(map) {
        if (this._implementation.onRemove) {
            this._implementation.onRemove(map);
        }
    }
    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 AbortController();
        const signal = controller.signal;
        tile.request = Promise.resolve(this._implementation.loadTile({
            x,
            y,
            z
        }, { signal })).then(tileLoaded.bind(this)).catch(error => {
            if (error.code === 20)
                return;
            tile.state = 'errored';
            callback(error);
        });
        tile.request.cancel = () => controller.abort();
        function tileLoaded(data) {
            delete tile.request;
            if (tile.aborted) {
                tile.state = 'unloaded';
                return callback(null);
            }
            if (data === void 0) {
                tile.state = 'errored';
                return callback(null);
            }
            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) {
        tile.setTexture(data, this.map.painter);
    }
    unloadTile(tile, callback) {
        if (tile.texture && tile.texture instanceof index.T) {
            tile.destroy(true);
            if (tile.texture && tile.texture instanceof index.T) {
                this.map.painter.saveTileTexture(tile.texture);
            }
        } else {
            tile.destroy();
        }
        if (this._implementation.unloadTile) {
            const {x, y, z} = tile.tileID.canonical;
            this._implementation.unloadTile({
                x,
                y,
                z
            });
        }
        if (callback)
            callback();
    }
    abortTile(tile, callback) {
        if (tile.request && tile.request.cancel) {
            tile.request.cancel();
            delete tile.request;
        }
        if (callback)
            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 = index.aC(this.id, this.scope);
        this.map.style.clearSource(fqid);
    }
    _update() {
        this.fire(new index.z('data', {
            dataType: 'source',
            sourceDataType: 'content'
        }));
    }
}

class ModelSource extends index.E {
    /**
   * @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 = [];
        for (const modelId in this._options.models) {
            const modelSpec = this._options.models[modelId];
            const modelPromise = index.aM(this.map._requestManager.transformRequest(modelSpec.uri, index.R.Model).url).then(gltf => {
                if (!gltf)
                    return;
                const nodes = index.aN(gltf);
                const model = new index.aO(modelId, modelSpec.position, modelSpec.orientation, nodes);
                model.computeBoundsAndApplyParent();
                this.models.push(model);
            }).catch(err => {
                this.fire(new index.y(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 index.z('data', {
                dataType: 'source',
                sourceDataType: 'metadata'
            }));
        }).catch(err => {
            this.fire(new index.y(new Error(`Could not load models: ${ err.message }`)));
        });
    }
    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 index.E {
    /**
   * @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);
    }
    onAdd(map) {
        this.map = map;
        this.load();
    }
    reload() {
        this.cancelTileJSONRequest();
        const fqid = index.aC(this.id, this.scope);
        this.load(() => this.map.style.clearSource(fqid));
    }
    cancelTileJSONRequest() {
        if (!this._tileJSONRequest)
            return;
        this._tileJSONRequest.cancel();
        this._tileJSONRequest = null;
    }
    load(callback) {
        this._loaded = false;
        this.fire(new index.z('dataloading', { dataType: 'source' }));
        const language = Array.isArray(this.map._language) ? this.map._language.join() : this.map._language;
        const worldview = this.map.getWorldview();
        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 index.y(err));
            } else if (tileJSON) {
                index.l(this, tileJSON);
                if (tileJSON.bounds)
                    this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
                postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);
                this.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'metadata'
                }));
                this.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'content'
                }));
            }
            if (callback)
                callback(err);
        });
    }
    hasTransition() {
        return false;
    }
    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, index.R.Tile);
        const params = {
            request,
            data: void 0,
            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,
            // Not supported in 3D models
            lut: null,
            maxZoom: null,
            promoteId: null,
            pixelRatio: null,
            scaleFactor: null
        };
        if (!tile.actor || tile.state === 'expired') {
            tile.actor = this.dispatcher.getActor();
            tile.request = tile.actor.send('loadTile', params, done.bind(this), void 0, true);
        } else if (tile.state === 'loading') {
            tile.reloadCallback = callback;
        } else {
            if (tile.buckets) {
                const buckets = Object.values(tile.buckets);
                for (const bucket of buckets) {
                    bucket.dirty = true;
                }
                tile.state = 'loaded';
                return;
            }
            tile.request = tile.actor.send('reloadTile', params, done.bind(this));
        }
        function done(err, data) {
            if (tile.aborted)
                return callback(null);
            if (err && err.status !== 404) {
                return callback(err);
            }
            if (this.map._refreshExpiredTiles && data)
                tile.setExpiryData(data);
            tile.loadModelData(data, this.map.painter);
            tile.state = 'loaded';
            callback(null);
        }
    }
    serialize() {
        return index.l({}, this._options);
    }
}

const sourceTypes = {
    vector: VectorTileSource,
    raster: RasterTileSource,
    'raster-dem': RasterDEMTileSource,
    'raster-array': RasterArrayTileSource,
    geojson: GeoJSONSource,
    video: VideoSource,
    image: index.aJ,
    model: ModelSource,
    'batched-model': Tiled3DModelSource,
    canvas: CanvasSource,
    custom: CustomSource
};
const create = function (id, specification, dispatcher, eventedParent) {
    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 }`);
    }
    index.aP([
        'load',
        'abort',
        'unload',
        'serialize',
        'prepare'
    ], source);
    return source;
};
const getType = function (name) {
    return sourceTypes[name];
};
const setType = function (name, type) {
    sourceTypes[name] = type;
};

function generateTargetKey(target) {
    if ('layerId' in target) {
        return `layer:${ target.layerId }`;
    } else {
        const {featuresetId, importId} = target;
        return `featureset:${ featuresetId }${ importId ? `:import:${ importId }` : '' }`;
    }
}
function getFeatureTargetKey(variant, feature, targetId = '') {
    return `${ targetId }:${ feature.id || '' }:${ feature.layer.id }:${ generateTargetKey(variant.target) }`;
}
function shouldSkipFeatureVariant(variant, feature, uniqueFeatureSet, targetId = '') {
    if (variant.uniqueFeatureID) {
        const key = getFeatureTargetKey(variant, feature, targetId);
        if (uniqueFeatureSet.has(key)) {
            return true;
        }
        uniqueFeatureSet.add(key);
    }
    return false;
}
function queryRenderedFeatures(queryGeometry, query, availableImages, transform, visualizeQueryGeometry = false) {
    const sourceCacheTransform = query.sourceCache.transform;
    const tileResults = query.sourceCache.tilesIn(queryGeometry, query.has3DLayers, visualizeQueryGeometry);
    tileResults.sort(sortTilesIn);
    const renderedFeatureLayers = [];
    for (const tileResult of tileResults) {
        const queryResults = tileResult.tile.queryRenderedFeatures(query, tileResult, availableImages, transform, sourceCacheTransform, visualizeQueryGeometry);
        if (Object.keys(queryResults).length) {
            renderedFeatureLayers.push({
                wrappedTileID: tileResult.tile.tileID.wrapped().key,
                queryResults
            });
        }
    }
    if (renderedFeatureLayers.length === 0) {
        return {};
    }
    return mergeRenderedFeatureLayers(renderedFeatureLayers);
}
function queryRenderedSymbols(queryGeometry, query, availableImages, 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], queryData.bucketIndex, queryData.sourceLayerIndex, query, availableImages);
        for (const layerID in bucketSymbols) {
            const resultFeatures = result[layerID] = result[layerID] || [];
            const layerSymbols = bucketSymbols[layerID];
            layerSymbols.sort((a, b) => {
                const featureSortOrder = queryData.featureSortOrder;
                if (featureSortOrder) {
                    const sortedA = featureSortOrder.indexOf(a.featureIndex);
                    const sortedB = featureSortOrder.indexOf(b.featureIndex);
                    return sortedB - sortedA;
                } else {
                    return b.featureIndex - a.featureIndex;
                }
            });
            for (const symbolFeature of layerSymbols) {
                resultFeatures.push(symbolFeature);
            }
        }
    }
    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) {
    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;
}

function deserialize(input, style) {
    const output = {};
    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;
        }
        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;
}

const meshSize = 32;
const gridSize = meshSize + 1;
const numTriangles = meshSize * meshSize * 2 - 2;
const numParentTriangles = numTriangles - meshSize * meshSize;
const coords = new Uint16Array(numTriangles * 4);
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;
    } else {
        ax = ay = cy = meshSize;
    }
    while ((id >>= 1) > 1) {
        const mx = ax + bx >> 1;
        const my = ay + by >> 1;
        if (id & 1) {
            bx = ax;
            by = ay;
            ax = cx;
            ay = cy;
        } else {
            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;
}
const reprojectedCoords = new Uint16Array(gridSize * gridSize * 2);
const used = new Uint8Array(gridSize * gridSize);
const indexMap = new Uint16Array(gridSize * gridSize);
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 = index.aQ(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 = index.aR((canonical.x + (x + seamPadding(x)) / meshSize) / z2);
            const lat = index.aS((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) * index.ag);
            reprojectedCoords[2 * k + 1] = Math.round((p.y * cs.scale - cs.y) * index.ag);
        }
    }
    used.fill(0);
    indexMap.fill(0);
    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;
        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];
        const isUsed = Math.hypot((rax + rbx) / 2 - rmx, (ray + rby) / 2 - rmy) >= 16;
        used[mIndex] = used[mIndex] || (isUsed ? 1 : 0);
        if (i < numParentTriangles) {
            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 index.aT();
    const indices = new index.aU();
    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 * index.ag / meshSize, y * index.ag / meshSize);
            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]) {
            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
    };
}

const CLOCK_SKEW_RETRY_TIMEOUT = 30000;
const BOUNDS_FEATURE = /* @__PURE__ */
((() => {
    return {
        type: 2,
        extent: index.ag,
        loadGeometry() {
            return [[
                    new index.P(0, 0),
                    new index.P(index.ag + 1, 0),
                    new index.P(index.ag + 1, index.ag + 1),
                    new index.P(0, index.ag + 1),
                    new index.P(0, 0)
                ]];
        }
    };
})());
function getPixelPosMatrix(transform, tileID) {
    const t = index.ab.mat4.fromScaling([], [
        transform.width * 0.5,
        -transform.height * 0.5,
        1
    ]);
    index.ab.mat4.translate(t, t, [
        1,
        -1,
        0
    ]);
    index.ab.mat4.multiply(t, t, transform.calculateProjMatrix(tileID.toUnwrapped()));
    return Float32Array.from(t);
}
class Tile {
    /**
   * @param {OverscaledTileID} tileID
   * @param size
   * @private
   */
    constructor(tileID, size, tileZoom, painter, isRaster) {
        this.tileID = tileID;
        this.uid = index.aV();
        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();
        }
        this.expiredRequestCount = 0;
        this.state = 'loading';
        if (painter && painter.transform) {
            this.projection = painter.transform.projection;
        }
    }
    registerFadeDuration(duration) {
        const fadeEndTime = duration + this.timeAdded;
        if (fadeEndTime < index.q.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 = index.aQ(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';
        if (!data) {
            this.collisionBoxArray = new index.aW();
            return;
        }
        if (data.featureIndex) {
            this.latestFeatureIndex = data.featureIndex;
            if (data.rawTileData) {
                this.latestRawTileData = data.rawTileData;
                this.latestFeatureIndex.rawTileData = data.rawTileData;
            } else if (this.latestRawTileData) {
                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 index.aX) {
                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 index.aX) {
                    if (bucket.hasRTLText) {
                        this.hasRTLText = true;
                        index.aY();
                        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';
    }
    loadModelData(data, painter, justReloaded) {
        if (!data) {
            return;
        }
        if (data.resourceTiming)
            this.resourceTiming = data.resourceTiming;
        this.buckets = Object.assign({}, this.buckets, deserialize(data.buckets, painter.style));
        if (data.featureIndex) {
            this.latestFeatureIndex = data.featureIndex;
        }
    }
    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;
        const atlas = this.imageAtlas;
        if (atlas && !atlas.uploaded) {
            const hasPattern = !!Object.keys(atlas.patternPositions).length;
            this.imageAtlasTexture = new index.T(context, atlas.image, gl.RGBA8, { useMipmap: hasPattern });
            this.imageAtlas.uploaded = true;
        }
        if (this.glyphAtlasImage) {
            this.glyphAtlasTexture = new index.T(context, this.glyphAtlasImage, gl.R8);
            this.glyphAtlasImage = null;
        }
        if (this.lineAtlas && !this.lineAtlas.uploaded) {
            this.lineAtlasTexture = new index.T(context, this.lineAtlas.image, gl.R8);
            this.lineAtlas.uploaded = true;
        }
    }
    prepare(imageManager, painter, scope) {
        if (this.imageAtlas && this.imageAtlasTexture) {
            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.updateBuckets(painter, this._lastUpdatedBrightness !== brightness);
        this._lastUpdatedBrightness = brightness;
    }
    // Queries non-symbol features rendered for this tile.
    // Symbol features are queried globally
    queryRenderedFeatures(query, tilespaceGeometry, availableImages, transform, sourceCacheTransform, visualizeQueryGeometry) {
        if (!this.latestFeatureIndex || !(this.latestFeatureIndex.rawTileData || this.latestFeatureIndex.is3DTile)) {
            return {};
        }
        const pixelPosMatrix = getPixelPosMatrix(sourceCacheTransform, this.tileID);
        return this.latestFeatureIndex.query(query, {
            tilespaceGeometry,
            pixelPosMatrix,
            transform,
            availableImages,
            tileTransform: this.tileTransform
        });
    }
    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 = index.aZ(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 = index.a_(feature, true);
                if (!filter.filter(new index.a8(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical))
                    continue;
            } else if (!filter.filter(new index.a8(this.tileID.overscaledZ), feature)) {
                continue;
            }
            const id = featureIndex.getId(feature, sourceLayer);
            const geojsonFeature = new index.a$(feature, z, x, y, id);
            geojsonFeature.tile = coord;
            result.push(geojsonFeature);
        }
    }
    hasData() {
        return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';
    }
    patternsLoaded() {
        return !!this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;
    }
    setExpiryData(data) {
        const prior = this.expirationTime;
        if (data.cacheControl) {
            const parsedCC = index.b0(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) {
                isExpired = true;
            } else {
                const delta = this.expirationTime - prior;
                if (!delta) {
                    isExpired = true;
                } else {
                    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 {
                return Math.min(this.expirationTime - /* @__PURE__ */
                new Date().getTime(), Math.pow(2, 31) - 1);
            }
        }
    }
    refreshFeatureState(painter) {
        if (!this.latestFeatureIndex || !(this.latestFeatureIndex.rawTileData || this.latestFeatureIndex.is3DTile) || !painter) {
            return;
        }
        this.updateBuckets(painter);
    }
    updateBuckets(painter, isBrightnessChanged) {
        if (!this.latestFeatureIndex)
            return;
        if (!painter.style)
            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];
            const bucketLayer = bucket.layers[0];
            const sourceLayerId = bucketLayer['sourceLayer'] || '_geojsonTileLayer';
            const sourceLayer = vtLayers[sourceLayerId];
            const sourceCache = painter.style.getLayerSourceCache(bucketLayer);
            let sourceLayerStates = {};
            if (sourceCache) {
                sourceLayerStates = sourceCache._state.getState(sourceLayerId, void 0);
            }
            const imagePositions = this.imageAtlas && this.imageAtlas.patternPositions || {};
            const withStateUpdates = Object.keys(sourceLayerStates).length > 0 && !isBrightnessChanged;
            const layers = withStateUpdates ? bucket.stateDependentLayers : bucket.layers;
            const updatesWithoutStateDependentLayers = withStateUpdates && !bucket.stateDependentLayers.length;
            if (!updatesWithoutStateDependentLayers || isBrightnessChanged) {
                bucket.update(sourceLayerStates, sourceLayer, availableImages, imagePositions, layers, isBrightnessChanged, brightness);
            }
            if (bucket instanceof index.b1 || bucket instanceof index.b2) {
                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 !== void 0;
    }
    symbolFadeFinished() {
        return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < index.q.now();
    }
    clearFadeHold() {
        this.symbolFadeHoldUntil = void 0;
    }
    setHoldDuration(duration) {
        this.symbolFadeHoldUntil = index.q.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 instanceof index.T) {
            this.texture.update(img);
        } else {
            this.texture = new index.T(context, img, gl.RGBA8, { 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;
        const boundsLine = index.b3(BOUNDS_FEATURE, this.tileID.canonical, this.tileTransform)[0];
        const debugVertices = new index.b4();
        const debugIndices = new index.b5();
        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, index.b6.members);
        this._tileDebugSegments = index.b7.simpleSegment(0, 0, debugVertices.length, debugIndices.length);
    }
    _makeTileBoundsBuffers(context, projection) {
        if (this._tileBoundsBuffer || !projection || projection.name === 'mercator')
            return;
        const boundsLine = index.b3(BOUNDS_FEATURE, this.tileID.canonical, this.tileTransform)[0];
        let boundsVertices, boundsIndices;
        if (this.isRaster) {
            const mesh = getTileMesh(this.tileID.canonical, projection);
            boundsVertices = mesh.vertices;
            boundsIndices = mesh.indices;
        } else {
            boundsVertices = new index.aT();
            boundsIndices = new index.aU();
            for (const {x, y} of boundsLine) {
                boundsVertices.emplaceBack(x, y, 0, 0);
            }
            const indices = index.b8(boundsVertices.int16, void 0, 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, index.b9.members);
        this._tileBoundsIndexBuffer = context.createIndexBuffer(boundsIndices);
        this._tileBoundsSegments = index.b7.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 = index.ba(id, transform);
        const normalizationMatrix = index.bb(bounds);
        const phase = index.ae(transform.zoom);
        let worldToECEFMatrix;
        if (phase > 0) {
            worldToECEFMatrix = index.ab.mat4.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) {
        let ecef = index.bc(x, y, id);
        if (worldToECEFMatrix) {
            const tileCount = 1 << id.z;
            const camX = index.at(tr.center.lng);
            const camY = index.aA(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 / index.ag + id.x) / tileCount + wrap;
            let mercatorY = (y / index.ag + id.y) / tileCount;
            mercatorX = (mercatorX - camX) * tr._pixelsPerMercatorPixel + camX;
            mercatorY = (mercatorY - camY) * tr._pixelsPerMercatorPixel + camY;
            const mercatorPos = [
                mercatorX * tr.worldSize,
                mercatorY * tr.worldSize,
                0
            ];
            index.ab.vec3.transformMat4(mercatorPos, mercatorPos, worldToECEFMatrix);
            ecef = index.bd(ecef, mercatorPos, phase);
        }
        const gp = index.ab.vec3.transformMat4(ecef, ecef, normalizationMatrix);
        return gp;
    }
    _makeGlobeTileDebugBorderBuffer(context, id, tr, normalizationMatrix, worldToECEFMatrix, phase) {
        const vertices = new index.b4();
        const indices = new index.b5();
        const extraGlobe = new index.be();
        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 = index.ag;
        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, index.b6.members);
        this._globeTileDebugBorderBuffer = context.createVertexBuffer(extraGlobe, index.bf.members);
        this._tileDebugSegments = index.b7.simpleSegment(0, 0, vertices.length, indices.length);
    }
    _makeGlobeTileDebugTextBuffer(context, id, tr, normalizationMatrix, worldToECEFMatrix, phase) {
        const SEGMENTS = 4;
        const numVertices = SEGMENTS + 1;
        const step = index.ag / SEGMENTS;
        const vertices = new index.b4();
        const indices = new index.aU();
        const extraGlobe = new index.be();
        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;
        };
        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]);
            }
        }
        for (let j = 0; j < SEGMENTS; j++) {
            for (let i = 0; i < SEGMENTS; i++) {
                const tl = toIndex(j, i);
                const tr2 = toIndex(j, i + 1);
                const bl = toIndex(j + 1, i);
                const br = toIndex(j + 1, i + 1);
                indices.emplaceBack(tl, tr2, bl);
                indices.emplaceBack(bl, tr2, br);
            }
        }
        this._tileDebugTextIndexBuffer = context.createIndexBuffer(indices);
        this._tileDebugTextBuffer = context.createVertexBuffer(vertices, index.b6.members);
        this._globeTileDebugTextBuffer = context.createVertexBuffer(extraGlobe, index.bf.members);
        this._tileDebugTextSegments = index.b7.simpleSegment(0, 0, totalVertices, totalTriangles);
    }
    /**
   * Release data and WebGL resources referenced by this tile.
   * @returns {undefined}
   * @private
   */
    destroy(preserveTexture = false) {
        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();
            delete this.imageAtlasTexture;
        }
        if (this.glyphAtlasTexture) {
            this.glyphAtlasTexture.destroy();
            delete this.glyphAtlasTexture;
        }
        if (this.lineAtlasTexture) {
            this.lineAtlasTexture.destroy();
            delete this.lineAtlasTexture;
        }
        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;
        }
        if (!preserveTexture && this.texture && this.texture instanceof index.T) {
            this.texture.destroy();
            delete this.texture;
        }
        if (this.hillshadeFBO) {
            this.hillshadeFBO.destroy();
            delete this.hillshadeFBO;
        }
        if (this.dem) {
            delete this.dem;
        }
        if (this.neighboringTiles) {
            delete this.neighboringTiles;
        }
        if (this.demTexture) {
            this.demTexture.destroy();
            delete this.demTexture;
        }
        if (this.rasterParticleState) {
            this.rasterParticleState.destroy();
            delete this.rasterParticleState;
        }
        this.latestFeatureIndex = null;
        this.state = 'unloaded';
    }
}

index.bg.setPbf(index.bh);
const FIRST_TRY_HEADER_LENGTH = 16384;
const MRT_DECODED_BAND_CACHE_SIZE = 30;
class RasterArrayTile extends Tile {
    constructor(tileID, size, tileZoom, painter, isRaster) {
        super(tileID, size, tileZoom, painter, isRaster);
        this._workQueue = [];
        this._fetchQueue = [];
        this._isHeaderLoaded = false;
    }
    setTexture(img, painter) {
        const context = painter.context;
        const gl = context.gl;
        this.texture = this.texture || painter.getTileTexture(img.width);
        if (this.texture && this.texture instanceof index.T) {
            this.texture.update(img, { premultiply: false });
        } else {
            this.texture = new index.T(context, img, gl.RGBA8, { premultiply: false });
        }
    }
    /**
   * Stops existing fetches
   * @private
   */
    flushQueues() {
        while (this._workQueue.length) {
            this._workQueue.pop()();
        }
        while (this._fetchQueue.length) {
            this._fetchQueue.pop()();
        }
    }
    fetchHeader(fetchLength = FIRST_TRY_HEADER_LENGTH, callback) {
        const mrt = this._mrt = new index.bg(MRT_DECODED_BAND_CACHE_SIZE);
        const headerRequestParams = Object.assign({}, this.requestParams, { headers: { Range: `bytes=0-${ fetchLength - 1 }` } });
        this.entireBuffer = null;
        this.request = index.bi(headerRequestParams, (error, dataBuffer, cacheControl, expires) => {
            if (error) {
                callback(error);
                return;
            }
            try {
                const headerLength = mrt.getHeaderLength(dataBuffer);
                if (headerLength > fetchLength) {
                    this.request = this.fetchHeader(headerLength, callback);
                    return;
                }
                mrt.parseHeader(dataBuffer);
                this._isHeaderLoaded = true;
                let lastByte = 0;
                for (const layer of Object.values(mrt.layers)) {
                    lastByte = Math.max(lastByte, layer.dataIndex[layer.dataIndex.length - 1].last_byte);
                }
                if (dataBuffer.byteLength >= lastByte) {
                    this.entireBuffer = dataBuffer;
                }
                callback(null, this.entireBuffer || dataBuffer, cacheControl, expires);
            } catch (error2) {
                callback(error2);
            }
        });
        return this.request;
    }
    fetchBand(sourceLayer, band, callback) {
        const mrt = this._mrt;
        if (!this._isHeaderLoaded || !mrt) {
            callback(new Error('Tile header is not ready'));
            return;
        }
        const actor = this.actor;
        if (!actor) {
            callback(new Error('Can\'t fetch tile band without an actor'));
            return;
        }
        let task;
        const onDataDecoded = (err, result) => {
            task.complete(err, result);
            if (err) {
                callback(err);
                return;
            }
            this.updateTextureDescriptor(sourceLayer, band);
            callback(null, this.textureDescriptor && this.textureDescriptor.img);
        };
        const onDataLoaded = (err, buffer) => {
            if (err)
                return callback(err);
            const params = {
                buffer,
                task
            };
            const workerJob = actor.send('decodeRasterArray', params, onDataDecoded, void 0, true);
            this._workQueue.push(() => {
                if (workerJob)
                    workerJob.cancel();
                task.cancel();
            });
        };
        const mrtLayer = mrt.getLayer(sourceLayer);
        if (!mrtLayer) {
            callback(new Error(`Unknown sourceLayer "${ sourceLayer }"`));
            return;
        }
        if (mrtLayer.hasDataForBand(band)) {
            this.updateTextureDescriptor(sourceLayer, band);
            callback(null, this.textureDescriptor ? this.textureDescriptor.img : null);
            return;
        }
        const range = mrtLayer.getDataRange([band]);
        task = mrt.createDecodingTask(range);
        if (task && !task.tasks.length) {
            callback(null);
            return;
        }
        this.flushQueues();
        if (this.entireBuffer) {
            onDataLoaded(null, this.entireBuffer.slice(range.firstByte, range.lastByte + 1));
        } else {
            const rangeRequestParams = Object.assign({}, this.requestParams, { headers: { Range: `bytes=${ range.firstByte }-${ range.lastByte }` } });
            const request = index.bi(rangeRequestParams, onDataLoaded);
            this._fetchQueue.push(() => {
                request.cancel();
                task.cancel();
            });
        }
    }
    updateNeeded(sourceLayer, band) {
        const textureUpdateNeeded = !this.textureDescriptor || this.textureDescriptor.band !== band || this.textureDescriptor.layer !== sourceLayer;
        return textureUpdateNeeded && this.state !== 'errored';
    }
    updateTextureDescriptor(sourceLayer, band) {
        if (!this._mrt)
            return;
        const mrtLayer = this._mrt.getLayer(sourceLayer);
        if (!mrtLayer || !mrtLayer.hasBand(band) || !mrtLayer.hasDataForBand(band))
            return;
        const {bytes, tileSize, buffer, offset, scale} = mrtLayer.getBandView(band);
        const size = tileSize + 2 * buffer;
        const img = {
            data: bytes,
            width: size,
            height: size
        };
        const texture = this.texture;
        if (texture && texture instanceof index.T) {
            texture.update(img, { premultiply: false });
        }
        this.textureDescriptor = {
            layer: sourceLayer,
            band,
            img,
            buffer,
            offset,
            tileSize,
            format: mrtLayer.pixelFormat,
            mix: [
                scale,
                scale * 256,
                scale * 65536,
                scale * 16777216
            ]
        };
    }
}

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] === void 0) {
            this.data[key] = [];
        }
        const dataWrapper = {
            value: data,
            timeout: void 0
        };
        if (expiryTimeout !== void 0) {
            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 === void 0 ? 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 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] || {};
        index.l(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 !== void 0) {
            if (this.deletedStates[sourceLayer][feature] !== null) {
                this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};
                this.deletedStates[sourceLayer][feature][key] = null;
            }
        } else if (featureId !== void 0) {
            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 base = this.state[sourceLayer] || {};
        const changes = this.stateChanges[sourceLayer] || {};
        const deletedStates = this.deletedStates[sourceLayer];
        if (deletedStates === null)
            return {};
        if (featureId !== void 0) {
            const feature = String(featureId);
            const reconciledState2 = index.l({}, base[feature], changes[feature]);
            if (deletedStates) {
                const featureDeletions = deletedStates[featureId];
                if (featureDeletions === null)
                    return {};
                for (const prop in featureDeletions)
                    delete reconciledState2[prop];
            }
            return reconciledState2;
        }
        const reconciledState = index.l({}, base, changes);
        if (deletedStates) {
            for (const feature in deletedStates)
                delete reconciledState[feature];
        }
        return reconciledState;
    }
    initializeTileState(tile, painter) {
        tile.refreshFeatureState(painter);
    }
    coalesceChanges(tiles, painter) {
        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] = {};
                index.l(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] || {};
            index.l(featuresChanged[sourceLayer], layerStates);
        }
        this.stateChanges = {};
        this.deletedStates = {};
        if (Object.keys(featuresChanged).length === 0)
            return;
        for (const id in tiles) {
            const tile = tiles[id];
            tile.refreshFeatureState(painter);
        }
    }
}

class SourceCache extends index.E {
    constructor(id, source, onlySymbols) {
        super();
        this.id = id;
        this._onlySymbols = onlySymbols;
        source.on('data', e => {
            if (e.dataType === 'source' && e.sourceDataType === 'metadata')
                this._sourceLoaded = true;
            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 = {};
        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.tileCoverLift = 0;
        this._coveredTiles = {};
        this._shadowCasterTiles = {};
        this._state = new SourceFeatureState();
        this._isRaster = this._source.type === 'raster' || this._source.type === 'raster-dem' || this._source.type === 'raster-array' || // @ts-expect-error - TS2339 - Property '_dataType' does not exist on type 'VideoSource | ImageSource | CanvasSource | CustomSource<ImageBitmap | HTMLCanvasElement | HTMLImageElement | ImageData>'.
        this._source.type === 'custom' && this._source._dataType === 'raster';
    }
    onAdd(map) {
        this.map = map;
        this._minTileCacheSize = this._minTileCacheSize === void 0 && map ? map._minTileCacheSize : this._minTileCacheSize;
        this._maxTileCacheSize = this._maxTileCacheSize === void 0 && 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 !== 'loaded' && tile.state !== 'errored')
                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 index.bj(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 index.P(a.canonical.x, a.canonical.y)._rotate(this.transform.angle);
                const rotatedB = new index.P(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];
        if (!tile)
            return;
        if (tile.state !== 'loading') {
            tile.state = state;
        }
        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 index.y(err, { tile }));
            else {
                this._source.fire(new index.z('data', {
                    dataType: 'source',
                    sourceDataType: 'error',
                    sourceId: this._source.id,
                    tile
                }));
                const hasParent = tile.tileID.key in this._loadedParentTiles;
                if (!hasParent)
                    return;
                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 = index.q.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 index.z('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(tile2, borderTile) {
            if (!tile2.dem || tile2.dem.borderReady)
                return;
            tile2.needsHillshadePrepare = true;
            tile2.needsDEMTextureUpload = true;
            let dx = borderTile.tileID.canonical.x - tile2.tileID.canonical.x;
            const dy = borderTile.tileID.canonical.y - tile2.tileID.canonical.y;
            const dim = Math.pow(2, tile2.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) {
                if (Math.abs(dx + dim) === 1) {
                    dx += dim;
                } else if (Math.abs(dx - dim) === 1) {
                    dx -= dim;
                }
            }
            if (!borderTile.dem || !tile2.dem)
                return;
            tile2.dem.backfillBorder(borderTile.dem, dx, dy);
            if (tile2.neighboringTiles && tile2.neighboringTiles[borderId])
                tile2.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];
            if (retain[id] || !tile.hasData() || tile.tileID.overscaledZ <= zoom || tile.tileID.overscaledZ > maxCoveringZoom)
                continue;
            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;
                }
            }
            let tileID = topmostLoadedID;
            while (tileID.overscaledZ > zoom) {
                tileID = tileID.scaledTo(tileID.overscaledZ - 1);
                if (idealTiles[tileID.key]) {
                    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;
        }
        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) {
        const prevLng = this._prevLng === void 0 ? 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;
            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) {
            return;
        }
        this.updateCacheSize(transform, tileSize);
        if (this.transform.projection.name !== 'globe') {
            this.handleWrapJump(this.transform.center.lng);
        }
        this._shadowCasterTiles = {};
        this._coveredTiles = {};
        const isBatchedModelType = this._source.type === 'batched-model';
        let idealTileIDs;
        let maxZoom = this._source.maxzoom;
        const terrain = this.map && this.map.painter ? this.map.painter._terrain : null;
        const sourceUsedForTerrain = terrain && terrain.sourceCache === this;
        if (sourceUsedForTerrain && terrain.attenuationRange()) {
            const minAttenuationZoom = terrain.attenuationRange()[0];
            const demMaxZoom = Math.floor(minAttenuationZoom) - Math.log2(terrain.getDemUpscale());
            if (maxZoom > demMaxZoom) {
                maxZoom = demMaxZoom;
            }
        }
        if (!this.used && !this.usedForTerrain) {
            idealTileIDs = [];
        } else if (this._source.tileID) {
            idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID).map(unwrapped => new index.aG(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));
        } else if (this.tileCoverLift !== 0) {
            const modifiedTransform = transform.clone();
            modifiedTransform.tileCoverLift = this.tileCoverLift;
            idealTileIDs = modifiedTransform.coveringTiles({
                tileSize: tileSize || this._source.tileSize,
                minzoom: this._source.minzoom,
                maxzoom: maxZoom,
                roundZoom: this._source.roundZoom && !updateForTerrain,
                reparseOverscaled: this._source.reparseOverscaled,
                isTerrainDEM: this.usedForTerrain,
                calculateQuadrantVisibility: isBatchedModelType
            });
            if (this._source.minzoom <= 1 && transform.projection.name === 'globe') {
                idealTileIDs.push(new index.aG(1, 0, 1, 0, 0));
                idealTileIDs.push(new index.aG(1, 0, 1, 1, 0));
                idealTileIDs.push(new index.aG(1, 0, 1, 0, 1));
                idealTileIDs.push(new index.aG(1, 0, 1, 1, 1));
            }
        } else {
            idealTileIDs = transform.coveringTiles({
                tileSize: tileSize || this._source.tileSize,
                minzoom: this._source.minzoom,
                maxzoom: maxZoom,
                roundZoom: this._source.roundZoom && !updateForTerrain,
                reparseOverscaled: this._source.reparseOverscaled,
                isTerrainDEM: this.usedForTerrain,
                calculateQuadrantVisibility: isBatchedModelType
            });
            if (this._source.hasTile) {
                const hasTile = this._source.hasTile.bind(this._source);
                idealTileIDs = idealTileIDs.filter(coord => hasTile(coord));
            }
        }
        if (idealTileIDs.length > 0 && this.castsShadows && directionalLight && this.transform.projection.name !== 'globe' && !this.usedForTerrain && !isRasterType(this._source.type)) {
            const coveringZoom = transform.coveringZoomLevel({
                tileSize: tileSize || this._source.tileSize,
                roundZoom: this._source.roundZoom && !updateForTerrain
            });
            const idealZoom = Math.min(coveringZoom, this._source.maxzoom);
            if (isBatchedModelType) {
                const batchedModelTileIDs = transform.extendTileCover(idealTileIDs, idealZoom);
                for (const id of batchedModelTileIDs) {
                    idealTileIDs.push(id);
                }
            } else {
                const shadowCasterTileIDs = transform.extendTileCover(idealTileIDs, idealZoom, directionalLight);
                for (const id of shadowCasterTileIDs) {
                    this._shadowCasterTiles[id.key] = true;
                    idealTileIDs.push(id);
                }
            }
        }
        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 <= index.q.now())
                    continue;
                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;
            }
            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]) {
                    this._coveredTiles[id] = true;
                    retain[id] = parentsForFading[id];
                }
            }
        }
        for (const retainedId in retain) {
            this._tiles[retainedId].clearFadeHold();
        }
        const remove = index.bk(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);
            }
        }
        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[tileID.key] = tileID;
            if (tile.hasData())
                continue;
            if (minZoom < this._source.maxzoom) {
                missingTiles[tileID.key] = tileID;
            }
        }
        this._retainLoadedChildren(missingTiles, minZoom, maxCoveringZoom, retain);
        for (const tileID of idealTileIDs) {
            let tile = this._tiles[tileID.key];
            if (tile.hasData())
                continue;
            if (tileID.canonical.z >= this._source.maxzoom) {
                const childCoord = tileID.children(this._source.maxzoom)[0];
                const childTile = this.getTile(childCoord);
                if (!!childTile && childTile.hasData()) {
                    retain[childCoord.key] = childCoord;
                    continue;
                }
            } else {
                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;
            }
            let parentWasRequested = tile.wasRequested();
            for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {
                const parentId = tileID.scaledTo(overscaledZ);
                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;
                    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;
            while (currentId.overscaledZ > 0) {
                if (currentId.key in this._loadedParentTiles) {
                    parentTile = this._loadedParentTiles[currentId.key];
                    break;
                }
                path.push(currentId.key);
                const parentId = currentId.scaledTo(currentId.overscaledZ - 1);
                parentTile = this._getLoadedTile(parentId);
                if (parentTile) {
                    break;
                }
                currentId = parentId;
            }
            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) {
                this._reloadTile(tileID.key, 'reloading');
            }
            return tile;
        }
        tile = this._cache.getAndRemove(tileID);
        if (tile) {
            this._setTileReloadTimer(tileID.key, tile);
            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;
            const size = this._source.tileSize * tileID.overscaleFactor();
            const isRasterArray = this._source.type === 'raster-array';
            tile = isRasterArray ? new RasterArrayTile(tileID, size, this.transform.tileZoom, painter, this._isRaster) : new Tile(tileID, size, this.transform.tileZoom, painter, this._isRaster);
            this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));
        }
        if (!tile)
            return null;
        tile.uses++;
        this._tiles[tileID.key] = tile;
        if (!cached)
            this._source.fire(new index.z('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' || tile.state === 'empty') {
            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 = index.at(transform.center.lng);
        for (const tileID in this._tiles) {
            const tile = this._tiles[tileID];
            if (visualizeQueryGeometry) {
                tile.clearQueryDebugViz();
            }
            if (tile.holdingForFade()) {
                continue;
            }
            let tilesToCheck;
            if (isGlobe) {
                const id = tile.tileID.canonical;
                if (id.z === 0) {
                    const distances = [
                        Math.abs(index.aw(centerX, ...tileBoundsX(id, -1)) - centerX),
                        Math.abs(index.aw(centerX, ...tileBoundsX(id, 1)) - centerX)
                    ];
                    tilesToCheck = [
                        0,
                        distances.indexOf(Math.min(...distances)) * 2 - 1
                    ];
                } else {
                    const distances = [
                        Math.abs(index.aw(centerX, ...tileBoundsX(id, -1)) - centerX),
                        Math.abs(index.aw(centerX, ...tileBoundsX(id, 0)) - centerX),
                        Math.abs(index.aw(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);
        const isGlobe = this.transform.projection.name === 'globe';
        for (const coord of coords) {
            coord.projMatrix = this.transform.calculateProjMatrix(coord.toUnwrapped());
            if (isGlobe) {
                coord.expandedProjMatrix = this.transform.calculateProjMatrix(coord.toUnwrapped(), false, true);
            } else {
                coord.expandedProjMatrix = coord.projMatrix;
            }
        }
        return coords;
    }
    sortCoordinatesByDistance(coords) {
        const sortedCoords = coords.slice();
        const camPos = this.transform._camera.position;
        const camFwd = this.transform._camera.forward();
        const precomputedDistances = {};
        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 !== void 0 && tile.fadeEndTime >= index.q.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 = /* @__PURE__ */
        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 tileIDs2 = 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 tileIDs2) {
                coveringTilesIDs.set(tileID.key, tileID);
            }
            if (this.usedForTerrain) {
                tr.updateElevation(false);
            }
        }
        const tileIDs = Array.from(coveringTilesIDs.values());
        index.bl(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) {
    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
    ];
}

class BuildingIndex {
    // when layer're hidden since the last frame, don't keep previous elevation, while loading tiles.
    constructor(style) {
        this.style = style;
        this.layersGotHidden = false;
        this.layers = [];
    }
    processLayersChanged() {
        this.layers = [];
        const visible = false, visibilityChanged = false;
        for (const layerId in this.style._mergedLayers) {
            const layer = this.style._mergedLayers[layerId];
            if (layer.type === 'fill-extrusion') {
                this.layers.push({
                    layer,
                    visible,
                    visibilityChanged
                });
            } else if (layer.type === 'model') {
                const source = this.style.getLayerSource(layer);
                if (source && source.type === 'batched-model') {
                    this.layers.push({
                        layer,
                        visible,
                        visibilityChanged
                    });
                }
            }
        }
    }
    // Check if some of the building layers are disabled or with opacity evaluated to 0.
    onNewFrame(zoom) {
        this.layersGotHidden = false;
        for (const l of this.layers) {
            const layer = l.layer;
            let visible = false;
            if (layer.type === 'fill-extrusion') {
                visible = !layer.isHidden(zoom) && layer.paint.get('fill-extrusion-opacity') > 0;
            } else if (layer.type === 'model') {
                visible = !layer.isHidden(zoom) && layer.paint.get('model-opacity').constantOr(1) > 0;
            }
            this.layersGotHidden = this.layersGotHidden || !visible && l.visible;
            l.visible = visible;
        }
    }
    updateZOffset(symbolBucket, tileID) {
        this.currentBuildingBuckets = [];
        for (const l of this.layers) {
            const layer = l.layer;
            const sourceCache = this.style.getLayerSourceCache(layer);
            let verticalScale = 1;
            if (layer.type === 'fill-extrusion') {
                verticalScale = l.visible ? 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 !== Number.NEGATIVE_INFINITY ? 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 * index.ag) * zDiff - id.x * index.ag | 0;
            tileY = (y + tid.canonical.y * index.ag) * zDiff - id.y * index.ag | 0;
        }
        return {
            tileX,
            tileY
        };
    }
    _getHeightAtTileOffset(tid, x, y) {
        let availableHeight;
        let maxFillExtrusionHeight;
        for (let i = 0; i < this.layers.length; ++i) {
            const l = this.layers[i];
            const layer = l.layer;
            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 === void 0)
                continue;
            if (heightData.hidden) {
                availableHeight = heightData.height;
                continue;
            }
            maxFillExtrusionHeight = Math.max(heightData.height * verticalScale, maxFillExtrusionHeight || 0);
        }
        if (maxFillExtrusionHeight !== void 0) {
            return maxFillExtrusionHeight;
        }
        for (let i = 0; i < this.layers.length; ++i) {
            const l = this.layers[i];
            const layer = l.layer;
            if (layer.type !== 'model' || !l.visible)
                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 === void 0 && availableHeight !== void 0)
                return Math.min(heightData.maxHeight, availableHeight) * heightData.verticalScale;
            return heightData.height ? heightData.height * heightData.verticalScale : Number.NEGATIVE_INFINITY;
        }
        return this.layersGotHidden ? 0 : Number.NEGATIVE_INFINITY;
    }
}

function deref(layer, parent) {
    const result = {};
    for (const k in layer) {
        if (k !== 'ref') {
            result[k] = layer[k];
        }
    }
    index.bm.forEach(k => {
        if (k in parent) {
            result[k] = parent[k];
        }
    });
    return result;
}
function derefLayers(layers) {
    layers = layers.slice();
    const map = /* @__PURE__ */
    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: 'setSnow', args: [snowProperties] }
   */
    setSnow: 'setSnow',
    /*
   *  { command: 'setRain', args: [rainProperties] }
   */
    setRain: 'setRain',
    /*
   *  { 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: 'updateImport', args: [importId, importSpecification | styleUrl] }
   */
    updateImport: 'updateImport'
};
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' && !index.bn(before[sourceId][prop], after[sourceId][prop])) {
            return false;
        }
    }
    for (prop in after[sourceId]) {
        if (!after[sourceId].hasOwnProperty(prop))
            continue;
        if (prop !== 'data' && !index.bn(before[sourceId][prop], after[sourceId][prop])) {
            return false;
        }
    }
    return true;
}
function diffSources(before, after, commands, sourcesRemoved) {
    before = before || {};
    after = after || {};
    let sourceId;
    for (sourceId in before) {
        if (!before.hasOwnProperty(sourceId))
            continue;
        if (!after.hasOwnProperty(sourceId)) {
            removeSource(sourceId, commands, sourcesRemoved);
        }
    }
    for (sourceId in after) {
        if (!after.hasOwnProperty(sourceId))
            continue;
        const source = after[sourceId];
        if (!before.hasOwnProperty(sourceId)) {
            addSource(sourceId, after, commands);
        } else if (!index.bn(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 {
                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 (!index.bn(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 (!index.bn(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 || [];
    const beforeOrder = before.map(pluckId);
    const afterOrder = after.map(pluckId);
    const beforeIndex = before.reduce(indexById, {});
    const afterIndex = after.reduce(indexById, {});
    const tracker = beforeOrder.slice();
    const clean = /* @__PURE__ */
    Object.create(null);
    let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;
    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 {
            d++;
        }
    }
    for (i = 0, d = 0; i < afterOrder.length; i++) {
        layerId = afterOrder[afterOrder.length - 1 - i];
        if (tracker[tracker.length - 1 - i] === layerId)
            continue;
        if (beforeIndex.hasOwnProperty(layerId)) {
            commands.push({
                command: operations.removeLayer,
                args: [layerId]
            });
            tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);
        } else {
            d++;
        }
        insertBeforeLayerId = tracker[tracker.length - i];
        commands.push({
            command: operations.addLayer,
            args: [
                afterIndex[layerId],
                insertBeforeLayerId
            ]
        });
        tracker.splice(tracker.length - i, 0, layerId);
        clean[layerId] = true;
    }
    for (i = 0; i < afterOrder.length; i++) {
        layerId = afterOrder[i];
        beforeLayer = beforeIndex[layerId];
        afterLayer = afterIndex[layerId];
        if (clean[layerId] || index.bn(beforeLayer, afterLayer))
            continue;
        if (!index.bn(beforeLayer.source, afterLayer.source) || !index.bn(beforeLayer['source-layer'], afterLayer['source-layer']) || !index.bn(beforeLayer.type, afterLayer.type)) {
            commands.push({
                command: operations.removeLayer,
                args: [layerId]
            });
            insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];
            commands.push({
                command: operations.addLayer,
                args: [
                    afterLayer,
                    insertBeforeLayerId
                ]
            });
            continue;
        }
        diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);
        diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);
        if (!index.bn(beforeLayer.slot, afterLayer.slot)) {
            commands.push({
                command: operations.setSlot,
                args: [
                    layerId,
                    afterLayer.slot
                ]
            });
        }
        if (!index.bn(beforeLayer.filter, afterLayer.filter)) {
            commands.push({
                command: operations.setFilter,
                args: [
                    layerId,
                    afterLayer.filter
                ]
            });
        }
        if (!index.bn(beforeLayer.minzoom, afterLayer.minzoom) || !index.bn(beforeLayer.maxzoom, afterLayer.maxzoom)) {
            commands.push({
                command: operations.setLayerZoomRange,
                args: [
                    layerId,
                    afterLayer.minzoom,
                    afterLayer.maxzoom
                ]
            });
        }
        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 (!index.bn(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 (!index.bn(beforeLayer[prop], afterLayer[prop])) {
                commands.push({
                    command: operations.setLayerProperty,
                    args: [
                        layerId,
                        prop,
                        afterLayer[prop]
                    ]
                });
            }
        }
    }
}
function diffImports(before = [], after = [], commands) {
    before = before || [];
    after = after || [];
    const beforeOrder = before.map(pluckId);
    const afterOrder = after.map(pluckId);
    const beforeIndex = before.reduce(indexById, {});
    const afterIndex = after.reduce(indexById, {});
    const tracker = beforeOrder.slice();
    let i, d, importId, insertBefore;
    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 {
            d++;
        }
    }
    for (i = 0, d = 0; i < afterOrder.length; i++) {
        importId = afterOrder[afterOrder.length - 1 - i];
        if (tracker[tracker.length - 1 - i] === importId)
            continue;
        if (beforeIndex.hasOwnProperty(importId)) {
            commands.push({
                command: operations.removeImport,
                args: [importId]
            });
            tracker.splice(tracker.lastIndexOf(importId, tracker.length - d), 1);
        } else {
            d++;
        }
        insertBefore = tracker[tracker.length - i];
        commands.push({
            command: operations.addImport,
            args: [
                afterIndex[importId],
                insertBefore
            ]
        });
        tracker.splice(tracker.length - i, 0, importId);
    }
    for (const afterImport of after) {
        const beforeImport = beforeIndex[afterImport.id];
        if (!beforeImport || index.bn(beforeImport, afterImport))
            continue;
        commands.push({
            command: operations.updateImport,
            args: [
                afterImport.id,
                afterImport
            ]
        });
    }
}
function diffStyles(before, after) {
    if (!before)
        return [{
                command: operations.setStyle,
                args: [after]
            }];
    let commands = [];
    try {
        if (!index.bn(before.version, after.version)) {
            return [{
                    command: operations.setStyle,
                    args: [after]
                }];
        }
        if (!index.bn(before.center, after.center)) {
            commands.push({
                command: operations.setCenter,
                args: [after.center]
            });
        }
        if (!index.bn(before.zoom, after.zoom)) {
            commands.push({
                command: operations.setZoom,
                args: [after.zoom]
            });
        }
        if (!index.bn(before.bearing, after.bearing)) {
            commands.push({
                command: operations.setBearing,
                args: [after.bearing]
            });
        }
        if (!index.bn(before.pitch, after.pitch)) {
            commands.push({
                command: operations.setPitch,
                args: [after.pitch]
            });
        }
        if (!index.bn(before.sprite, after.sprite)) {
            commands.push({
                command: operations.setSprite,
                args: [after.sprite]
            });
        }
        if (!index.bn(before.glyphs, after.glyphs)) {
            commands.push({
                command: operations.setGlyphs,
                args: [after.glyphs]
            });
        }
        if (!index.bn(before.imports, after.imports)) {
            diffImports(before.imports, after.imports, commands);
        }
        if (!index.bn(before.transition, after.transition)) {
            commands.push({
                command: operations.setTransition,
                args: [after.transition]
            });
        }
        if (!index.bn(before.light, after.light)) {
            commands.push({
                command: operations.setLight,
                args: [after.light]
            });
        }
        if (!index.bn(before.fog, after.fog)) {
            commands.push({
                command: operations.setFog,
                args: [after.fog]
            });
        }
        if (!index.bn(before.snow, after.snow)) {
            commands.push({
                command: operations.setSnow,
                args: [after.snow]
            });
        }
        if (!index.bn(before.rain, after.rain)) {
            commands.push({
                command: operations.setRain,
                args: [after.rain]
            });
        }
        if (!index.bn(before.projection, after.projection)) {
            commands.push({
                command: operations.setProjection,
                args: [after.projection]
            });
        }
        if (!index.bn(before.lights, after.lights)) {
            commands.push({
                command: operations.setLights,
                args: [after.lights]
            });
        }
        if (!index.bn(before.camera, after.camera)) {
            commands.push({
                command: operations.setCamera,
                args: [after.camera]
            });
        }
        if (!index.bn(before['color-theme'], after['color-theme'])) {
            return [{
                    command: operations.setStyle,
                    args: [after]
                }];
        }
        const sourcesRemoved = {};
        const removeOrAddSourceCommands = [];
        diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);
        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);
                }
            });
        }
        let beforeTerrain = before.terrain;
        if (beforeTerrain) {
            if (sourcesRemoved[beforeTerrain.source]) {
                commands.push({
                    command: operations.setTerrain,
                    args: [void 0]
                });
                beforeTerrain = void 0;
            }
        }
        commands = commands.concat(removeOrAddSourceCommands);
        if (!index.bn(beforeTerrain, after.terrain)) {
            commands.push({
                command: operations.setTerrain,
                args: [after.terrain]
            });
        }
        diffLayers(beforeLayers, after.layers, commands);
    } catch (e) {
        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_ || [];
        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 = index.aw(t, 0, 1);
        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];
        }
        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));
    }
}

class GridIndex {
    constructor(width, height, cellSize) {
        const boxCells = this.boxCells = [];
        const circleCells = this.circleCells = [];
        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) {
        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) {
        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: {}
                }
            };
            this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);
            return hitTest ? result.length > 0 : result;
        }
    }
    _queryCircle(x, y, radius, hitTest, predicate) {
        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 : [];
        }
        const result = [];
        const queryArgs = {
            hitTest,
            circle: {
                x,
                y,
                radius
            },
            seenUids: {
                box: {},
                circle: {}
            }
        };
        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;
    }
}

const FlipState = {
    unknown: 0,
    flipRequired: 1,
    flipNotRequired: 2
};
const maxTangent = Math.tan(85 * Math.PI / 180);
function getLabelPlaneMatrixForRendering(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits) {
    const m = index.ab.mat4.create();
    if (pitchWithMap) {
        if (projection.name === 'globe') {
            const lm = index.bo(transform, tileID);
            index.ab.mat4.multiply(m, m, lm);
        } else {
            const s = index.ab.mat2.invert([], pixelsToTileUnits);
            m[0] = s[0];
            m[1] = s[1];
            m[4] = s[2];
            m[5] = s[3];
            if (!rotateWithMap) {
                index.ab.mat4.rotateZ(m, m, transform.angle);
            }
        }
    } else {
        index.ab.mat4.multiply(m, transform.labelPlaneMatrix, posMatrix);
    }
    return m;
}
function getLabelPlaneMatrixForPlacement(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits) {
    const m = getLabelPlaneMatrixForRendering(posMatrix, tileID, pitchWithMap, rotateWithMap, transform, projection, pixelsToTileUnits);
    if (projection.name !== 'globe' || !pitchWithMap) {
        m[2] = m[6] = m[10] = m[14] = 0;
    }
    return m;
}
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);
            index.ab.mat4.invert(m, m);
            index.ab.mat4.multiply(m, posMatrix, m);
            return m;
        } else {
            const m = index.ab.mat4.clone(posMatrix);
            const s = index.ab.mat4.identity([]);
            s[0] = pixelsToTileUnits[0];
            s[1] = pixelsToTileUnits[1];
            s[4] = pixelsToTileUnits[2];
            s[5] = pixelsToTileUnits[3];
            index.ab.mat4.multiply(m, m, s);
            if (!rotateWithMap) {
                index.ab.mat4.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) {
        index.ab.vec4.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
    ];
    index.ab.vec4.transformMat4(pos, pos, matrix);
    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;
}
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 = index.bp(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;
        if (writingMode === index.bq.vertical && !useVertical && prevWritingMode !== index.bq.horizontal) {
            useVertical = true;
        }
        prevWritingMode = writingMode;
        if ((symbol.hidden || writingMode === index.bq.vertical) && !useVertical) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
            continue;
        }
        useVertical = false;
        const tileAnchorPoint = new index.P(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
        ];
        index.ab.vec4.transformMat4(anchorPos, anchorPos, posMatrix);
        if (!isVisible(anchorPos, clippingBuffer)) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
            continue;
        }
        const cameraToAnchorDistance = anchorPos[3];
        const perspectiveRatio = getPerspectiveRatio(painter.transform.getCameraToCenterDistance(tr.projection), cameraToAnchorDistance);
        const fontSize = index.br(sizeData, partiallyEvaluatedSize, symbol);
        const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;
        const labelPlaneAnchorPoint = project(x, y, z, labelPlaneMatrix);
        if (labelPlaneAnchorPoint[3] <= 0) {
            hideGlyphs(numGlyphs, dynamicLayoutVertexArray);
            continue;
        }
        let projectionCache = {};
        const getElevationForPlacement = pitchWithMap ? null : getElevation;
        const placeUnflipped = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false, 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 = {};
        if (placeUnflipped.notEnoughRoom || useVertical || placeUnflipped.needsFlipping && placeGlyphsAlongLine(symbol, pitchScaledFontSize, true, 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
    };
}
function isInFlipRetainRange(dx, dy) {
    return dx === 0 || Math.abs(dy / dx) > maxTangent;
}
function requiresOrientationChange(writingMode, flipState, dx, dy) {
    if (writingMode === index.bq.horizontal && Math.abs(dy) > Math.abs(dx)) {
        return { useVertical: true };
    }
    if (writingMode === index.bq.vertical) {
        return dy > 0 ? { needsFlipping: true } : null;
    }
    if (flipState !== FlipState.unknown && isInFlipRetainRange(dx, dy)) {
        return flipState === FlipState.flipRequired ? { needsFlipping: true } : null;
    }
    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;
            index.bs(globeExtVertexArray, offset + 0, ux, uy, uz);
            index.bs(globeExtVertexArray, offset + 1, ux, uy, uz);
            index.bs(globeExtVertexArray, offset + 2, ux, uy, uz);
            index.bs(globeExtVertexArray, offset + 3, ux, uy, uz);
        }
        const [x, y, z] = glyph.point;
        index.bt(dynamicLayoutVertexArray, x, y, z, glyph.angle);
    };
    if (numGlyphs > 1) {
        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++) {
            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) {
                dynamicLayoutVertexArray.length -= 4 * (glyphIndex - glyphStartIndex);
                return { notEnoughRoom: true };
            }
            addGlyph(glyph);
        }
        addGlyph(firstAndLastGlyph.last);
    } else {
        if (keepUpright && !flip) {
            const a = project(tileAnchorPoint.x, tileAnchorPoint.y, 0, posMatrix);
            const tileVertexIndex = lineStartIndex + segment + 1;
            const tileSegmentEnd = new index.P(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex));
            const projectedVertex = project(tileSegmentEnd.x, tileSegmentEnd.y, 0, posMatrix);
            const b = projectedVertex[3] > 0 ? projectedVertex : // @ts-expect-error - TS2345 - Argument of type 'vec4' is not assignable to parameter of type 'vec3'.
            projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix, void 0, 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) {
    const unitVertex = previousTilePoint.sub(currentTilePoint)._unit()._add(previousTilePoint);
    const projectedUnit = elevatePointAndProject(unitVertex, tileID, projectionMatrix, projection, getElevation);
    index.ab.vec3.sub(projectedUnit, previousProjectedPoint, projectedUnit);
    index.ab.vec3.normalize(projectedUnit, projectedUnit);
    return index.ab.vec3.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) {
        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;
        if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex)
            return null;
        prev = current;
        prevVertex = currentVertex;
        pathVertices.push(prev);
        if (returnPathInTileCoords)
            tilePath.push(prevVertex);
        currentVertex = new index.P(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 {
                current = getTruncatedLineSegment();
            }
        }
        distanceToPrev += currentSegmentDistance;
        currentSegmentDistance = index.ab.vec3.distance(prev, current);
    }
    if (endGlyph && getElevation) {
        if (projectionCache[currentIndex]) {
            current = getTruncatedLineSegment();
            currentSegmentDistance = index.ab.vec3.distance(prev, current);
        }
        projectionCache[currentIndex] = current;
    }
    const segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance;
    const tilePoint = currentVertex.sub(prevVertex)._mult(segmentInterpolationT)._add(prevVertex);
    const prevToCurrent = index.ab.vec3.sub([], current, prev);
    const labelPlanePoint = index.ab.vec3.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) {
            const axisX = [
                axisZ[2],
                0,
                -axisZ[0]
            ];
            const axisY = index.ab.vec3.cross([], axisZ, axisX);
            index.ab.vec3.normalize(axisX, axisX);
            index.ab.vec3.normalize(axisY, axisY);
            diffX = index.ab.vec3.dot(prevToCurrent, axisX);
            diffY = index.ab.vec3.dot(prevToCurrent, axisY);
        }
    }
    if (lineOffsetY) {
        const offsetDir = index.ab.vec3.cross([], axisZ, prevToCurrent);
        index.ab.vec3.normalize(offsetDir, offsetDir);
        index.ab.vec3.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
    };
}
function hideGlyphs(num, dynamicLayoutVertexArray) {
    const offset = dynamicLayoutVertexArray.length;
    const end = offset + 4 * num;
    dynamicLayoutVertexArray.resize(end);
    dynamicLayoutVertexArray.float32.fill(-Infinity, offset * 4, end * 4);
}
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 viewportPadding = 100;
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;
        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;
        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 index.P(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) / index.bw;
        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, // @ts-expect-error - TS2345 - Argument of type 'vec4' is not assignable to parameter of type 'vec3'.
        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 index.P(-viewportPadding, -viewportPadding);
            const screenPlaneMax = new index.P(this.screenRightBoundary, this.screenBottomBoundary);
            const interpolator = new PathInterpolator();
            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]);
            }
            const circleDist = radius * 2.5;
            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);
                });
                if (projectedPath.some(point => point[3] <= 0)) {
                    projectedPath = [];
                }
            }
            let segments = [];
            if (projectedPath.length > 0) {
                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]);
                }
                if (maxx >= screenPlaneMin.x && minx <= screenPlaneMax.x && maxy >= screenPlaneMin.y && miny <= screenPlaneMax.y) {
                    segments = [projectedPath.map(p => new index.P(p[0], p[1]))];
                    if (minx < screenPlaneMin.x || maxx > screenPlaneMax.x || miny < screenPlaneMin.y || maxy > screenPlaneMax.y) {
                        segments = index.bu(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);
                    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)) {
                            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 index.P(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;
            if (seenFeatures[featureKey.bucketInstanceId] === void 0) {
                seenFeatures[featureKey.bucketInstanceId] = {};
            }
            if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {
                continue;
            }
            const bbox = [
                new index.P(feature.x1, feature.y1),
                new index.P(feature.x2, feature.y1),
                new index.P(feature.x2, feature.y2),
                new index.P(feature.x1, feature.y2)
            ];
            if (!index.bv(query, bbox)) {
                continue;
            }
            seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;
            if (result[featureKey.bucketInstanceId] === void 0) {
                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) {
            index.ab.vec4.transformMat4(p, p, posMatrix);
            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 index.P((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 = index.ab.mat4.identity([]);
        index.ab.mat4.translate(m, m, [
            -viewportPadding,
            -viewportPadding,
            0
        ]);
        return m;
    }
}

function reconstructTileMatrix(transform, projection, coord) {
    const tileMatrix = projection.createTileMatrix(transform, transform.worldSize, coord.toUnwrapped());
    return index.ab.mat4.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);
}

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 {
    constructor(text, icon, skipFade, clipped = false) {
        this.text = text;
        this.icon = icon;
        this.skipFade = skipFade;
        this.clipped = clipped;
    }
}
class CollisionCircleArray {
    constructor() {
        this.invProjMatrix = index.ab.mat4.create();
        this.viewportMatrix = index.ab.mat4.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) {
        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} = index.bD(anchor);
    const shiftX = -(horizontalAlign - 0.5) * width;
    const shiftY = -(verticalAlign - 0.5) * height;
    const offset = index.bC(anchor, textOffset);
    return new index.P(shiftX + offset[0] * textScale, shiftY + offset[1] * textScale);
}
function offsetShift(shiftX, shiftY, rotateWithMap, pitchWithMap, angle) {
    const shift = new index.P(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 = void 0;
        }
        this.placedOrientations = {};
    }
    getBucketParts(results, styleLayer, tile, sortAcrossTiles, scaleFactor = 1) {
        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 paint = symbolBucket.layers[0].paint;
        const collisionBoxArray = tile.collisionBoxArray;
        const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);
        const textPixelRatio = tile.tileSize / index.ag;
        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(styleLayer.options);
        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 = index.ab.mat4.multiply([], this.transform.labelPlaneMatrix, glMatrix);
        }
        let clippingData = null;
        if (!!dynamicFilter && tile.latestFeatureIndex) {
            clippingData = {
                unwrappedTileID,
                dynamicFilter,
                dynamicFilterNeedsFeature
            };
        }
        this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID);
        const [textSizeScaleRangeMin, textSizeScaleRangeMax] = symbolBucket.layers[0].layout.get('text-size-scale-range');
        const textScaleFactor = index.aw(scaleFactor, textSizeScaleRangeMin, textSizeScaleRangeMax);
        const [iconSizeScaleRangeMin, iconSizeScaleRangeMax] = layout.get('icon-size-scale-range');
        const iconScaleFactor = index.aw(scaleFactor, iconSizeScaleRangeMin, iconSizeScaleRangeMax);
        const parameters = {
            bucket: symbolBucket,
            layout,
            paint,
            posMatrix,
            textLabelPlaneMatrix,
            labelToScreenMatrix,
            clippingData,
            scale,
            textPixelRatio,
            holdingForFade: tile.holdingForFade(),
            collisionBoxArray,
            partiallyEvaluatedTextSize: index.bp(symbolBucket.textSizeData, this.transform.zoom, textScaleFactor),
            partiallyEvaluatedIconSize: index.bp(symbolBucket.iconSizeData, this.transform.zoom, iconScaleFactor),
            collisionGroup: this.collisionGroups.get(symbolBucket.sourceID),
            latestFeatureIndex: tile.latestFeatureIndex
        };
        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.prevPlacement && this.prevPlacement.variableOffsets[crossTileID] && this.prevPlacement.placements[crossTileID] && this.prevPlacement.placements[crossTileID].text) {
                prevAnchor = this.prevPlacement.variableOffsets[crossTileID].anchor;
            }
            this.variableOffsets[crossTileID] = {
                // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type '[number, number]'.
                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, scaleFactor = 1) {
        const {bucket, layout, paint, posMatrix, textLabelPlaneMatrix, labelToScreenMatrix, clippingData, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, partiallyEvaluatedIconSize, collisionGroup, latestFeatureIndex} = 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 zOffset = layout.get('symbol-z-elevate');
        const symbolZOffset = paint.get('symbol-z-offset');
        const elevationFromSea = layout.get('symbol-elevation-reference') === 'sea';
        const [textSizeScaleRangeMin, textSizeScaleRangeMax] = layout.get('text-size-scale-range');
        const [iconSizeScaleRangeMin, iconSizeScaleRangeMax] = layout.get('icon-size-scale-range');
        const textScaleFactor = index.aw(scaleFactor, textSizeScaleRangeMin, textSizeScaleRangeMax);
        const iconScaleFactor = index.aw(scaleFactor, iconSizeScaleRangeMin, iconSizeScaleRangeMax);
        this.transform.setProjection(bucket.projection);
        let alwaysShowText = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional);
        let alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional);
        const needsFeatureForElevation = !symbolZOffset.isConstant();
        if (!bucket.collisionArrays && collisionBoxArray) {
            bucket.deserializeCollisionBoxes(collisionBoxArray);
        }
        if (showCollisionBoxes && updateCollisionBoxIfNecessary) {
            bucket.updateCollisionDebugBuffers(this.transform.zoom, collisionBoxArray, textScaleFactor, iconScaleFactor);
        }
        const placeSymbol = (symbolInstance, boxIndex, collisionArrays) => {
            const {crossTileID, numVerticalGlyphVertices} = symbolInstance;
            let feature = null;
            if (clippingData && clippingData.dynamicFilterNeedsFeature || needsFeatureForElevation) {
                const retainedQueryData = this.retainedQueryData[bucket.bucketInstanceId];
                feature = latestFeatureIndex.loadFeature({
                    featureIndex: symbolInstance.featureIndex,
                    bucketIndex: retainedQueryData.bucketIndex,
                    sourceLayerIndex: retainedQueryData.sourceLayerIndex,
                    layoutVertexArrayOffset: 0
                });
            }
            if (clippingData) {
                const globals = {
                    zoom: this.transform.zoom,
                    pitch: this.transform.pitch
                };
                const canonicalTileId = this.retainedQueryData[bucket.bucketInstanceId].tileID.canonical;
                const filterFunc = clippingData.dynamicFilter;
                const shouldClip = !filterFunc(globals, feature, canonicalTileId, new index.P(symbolInstance.tileAnchorX, symbolInstance.tileAnchorY), this.transform.calculateDistanceTileData(clippingData.unwrappedTileID));
                if (shouldClip) {
                    this.placements[crossTileID] = new JointPlacement(false, false, false, true);
                    seenCrossTileIDs.add(crossTileID);
                    return;
                }
            }
            const symbolZOffsetValue = symbolZOffset.evaluate(feature, {});
            if (seenCrossTileIDs.has(crossTileID))
                return;
            if (holdingForFade) {
                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 = elevationFromSea ? symbolZOffsetValue : symbolZOffsetValue + (elevation ? elevation.getAtTileOffset(box.tileID, box.tileAnchorX, box.tileAnchorY) : 0);
                box.elevation += symbolInstance.zOffset;
            };
            const textBox = collisionArrays.textBox;
            if (textBox) {
                updateBoxData(textBox);
                const updatePreviousOrientationIfNotPlaced = isPlaced => {
                    let previousOrientation = index.bq.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 === index.bq.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, scaleFactor);
                        const placedFeature = this.collisionIndex.placeCollisionBox(bucket, textScale, collisionTextBox, new index.P(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, index.bq.horizontal);
                    };
                    const placeVertical = () => {
                        const verticalTextBox = collisionArrays.verticalTextBox;
                        if (bucket.allowVerticalPlacement && numVerticalGlyphVertices > 0 && verticalTextBox) {
                            updateBoxData(verticalTextBox);
                            return placeBox(verticalTextBox, index.bq.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.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, index.bq.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, index.bq.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 (!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 = index.br(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);
                const textPixelPadding = layout.get('text-padding');
                const circlePixelDiameter = symbolInstance.collisionCircleDiameter * fontSize / index.bw;
                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);
                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 index.P(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;
            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];
                    if (circleArray === void 0)
                        circleArray = this.collisionCircleArrays[id] = new CollisionCircleArray();
                    for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {
                        circleArray.circles.push(placedGlyphCircles.circles[i + 0]);
                        circleArray.circles.push(placedGlyphCircles.circles[i + 1]);
                        circleArray.circles.push(placedGlyphCircles.circles[i + 2]);
                        circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0);
                    }
                }
            }
            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 (bucket.sortFeaturesByY) {
            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)
                index.w(`${ 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];
            index.ab.mat4.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 = index.bB(placedAnchor);
        const autoIndex = orientation === index.bq.vertical ? vertical : justification === 'left' ? left : justification === 'center' ? center : justification === 'right' ? right : -1;
        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 === index.bq.horizontal || orientation === index.bq.horizontalOnly ? orientation : 0;
        const verticalOrientation = orientation === index.bq.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 : {};
        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;
            }
        }
        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, layerIndex, replacementSource) {
        const seenCrossTileIDs = /* @__PURE__ */
        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, tile.collisionBoxArray, layerIndex, replacementSource, tile.tileID, styleLayer.scope);
                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, tile, collisionBoxArray, layerIndex, replacementSource, coord, scope) {
        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 paint = bucket.layers[0].paint;
        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';
        const symbolZOffset = paint.get('symbol-z-offset');
        const elevationFromSea = layout.get('symbol-elevation-reference') === 'sea';
        const needsFeatureForElevation = !symbolZOffset.isConstant();
        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;
        if (replacementSource) {
            bucket.updateReplacement(coord, replacementSource);
        }
        for (let s = 0; s < bucket.symbolInstances.length; s++) {
            const symbolInstance = bucket.symbolInstances.get(s);
            const {numHorizontalGlyphVertices, numVerticalGlyphVertices, crossTileID, numIconVertices, tileAnchorX, tileAnchorY} = symbolInstance;
            let feature = null;
            const retainedQueryData = this.retainedQueryData[bucket.bucketInstanceId];
            if (needsFeatureForElevation && symbolInstance && retainedQueryData) {
                const featureIndex = tile.latestFeatureIndex;
                feature = featureIndex.loadFeature({
                    featureIndex: symbolInstance.featureIndex,
                    bucketIndex: retainedQueryData.bucketIndex,
                    sourceLayerIndex: retainedQueryData.sourceLayerIndex,
                    layoutVertexArrayOffset: 0
                });
            }
            const symbolZOffsetValue = symbolZOffset.evaluate(feature, {});
            const isDuplicate = seenCrossTileIDs.has(crossTileID);
            let opacityState = this.opacities[crossTileID];
            if (isDuplicate) {
                opacityState = duplicateOpacityState;
            } else if (!opacityState) {
                opacityState = defaultOpacityState;
                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 === index.bq.vertical;
            const verticalHidden = placedOrientation === index.bq.horizontal || placedOrientation === index.bq.horizontalOnly;
            if ((hasText || hasIcon) && !opacityState.isHidden())
                visibleInstanceCount++;
            let clippedSymbol = false;
            if ((hasText || hasIcon) && replacementSource) {
                for (const region of bucket.activeReplacements) {
                    if (index.bx(region, layerIndex, index.by.Symbol, scope))
                        continue;
                    if (region.min.x > tileAnchorX || tileAnchorX > region.max.x || region.min.y > tileAnchorY || tileAnchorY > region.max.y) {
                        continue;
                    }
                    const p = index.bz(tileAnchorX, tileAnchorY, coord.canonical, region.footprintTileId.canonical);
                    clippedSymbol = index.bA(p, region.footprint);
                    if (clippedSymbol)
                        break;
                }
            }
            if (hasText) {
                const packedOpacity = clippedSymbol ? PACKED_HIDDEN_OPACITY : packOpacity(opacityState.text);
                const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
                addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);
                const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
                addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);
                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 = clippedSymbol ? PACKED_HIDDEN_OPACITY : 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 index.P(0, 0);
                    let used = true;
                    if (collisionArrays.textBox || collisionArrays.verticalTextBox) {
                        if (variablePlacement) {
                            const variableOffset = this.variableOffsets[crossTileID];
                            if (variableOffset) {
                                shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textScale);
                                if (rotateWithMap) {
                                    shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle);
                                }
                            } else {
                                used = false;
                            }
                        }
                        if (hasClipping) {
                            used = !opacityState.clipped;
                        }
                        if (collisionArrays.textBox) {
                            updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || horizontalHidden, symbolZOffsetValue, elevationFromSea, shift.x, shift.y);
                        }
                        if (collisionArrays.verticalTextBox) {
                            updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || verticalHidden, symbolZOffsetValue, elevationFromSea, shift.x, shift.y);
                        }
                    }
                    const verticalIconUsed = used && Boolean(!verticalHidden && collisionArrays.verticalIconBox);
                    if (collisionArrays.iconBox) {
                        updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, verticalIconUsed, symbolZOffsetValue, elevationFromSea, symbolInstance.hasIconTextFit ? shift.x : 0, symbolInstance.hasIconTextFit ? shift.y : 0);
                    }
                    if (collisionArrays.verticalIconBox) {
                        updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, !verticalIconUsed, symbolZOffsetValue, elevationFromSea, 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);
        }
        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) {
        return Math.max(0, (this.transform.zoom - zoom) / 1.5);
    }
    hasTransitions(now) {
        return this.stale || now - this.lastPlacementChangeTime < this.fadeDuration;
    }
    stillRecent(now, zoom) {
        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, elevation, elevationFromSea, shiftX, shiftY) {
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, elevation, elevationFromSea ? 1 : 0);
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, elevation, elevationFromSea ? 1 : 0);
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, elevation, elevationFromSea ? 1 : 0);
    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, elevation, elevationFromSea ? 1 : 0);
}
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) !== void 0;
        this._currentTileIndex = 0;
        this._currentPartIndex = 0;
        this._seenCrossTileIDs = /* @__PURE__ */
        new Set();
        this._bucketParts = [];
    }
    continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement, scaleFactor) {
        const bucketParts = this._bucketParts;
        while (this._currentTileIndex < tiles.length) {
            const tile = tiles[this._currentTileIndex];
            placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles, scaleFactor);
            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, scaleFactor);
            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, scaleFactor) {
        const startTime = index.q.now();
        const shouldPausePlacement = () => {
            const elapsedTime = index.q.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 hasSymbolSortKey = symbolLayer.layout.get('symbol-sort-key').constantOr(1) !== void 0;
                const symbolZOrder = symbolLayer.layout.get('symbol-z-order');
                const sortSymbolByKey = symbolZOrder !== 'viewport-y' && hasSymbolSortKey;
                const zOrderByViewportY = symbolZOrder === 'viewport-y' || symbolZOrder === 'auto' && !sortSymbolByKey;
                const canOverlap = symbolLayer.layout.get('text-allow-overlap') || symbolLayer.layout.get('icon-allow-overlap') || symbolLayer.layout.get('text-ignore-placement') || symbolLayer.layout.get('icon-ignore-placement');
                const sortSymbolByViewportY = zOrderByViewportY && canOverlap;
                const inProgressLayer = this._inProgressLayer = this._inProgressLayer || new LayerPlacement(symbolLayer);
                const sourceId = index.aC(layer.source, layer.scope);
                const sortTileByY = zOffset || sortSymbolByViewportY;
                const pausePlacement = inProgressLayer.continuePlacement(sortTileByY ? layerTilesInYOrder[sourceId] : layerTiles[sourceId], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement, scaleFactor);
                if (pausePlacement) {
                    return;
                }
                delete this._inProgressLayer;
            }
            this._currentPlacementIndex--;
        }
        this._done = true;
    }
    commit(now) {
        this.placement.commit(now);
        return this.placement;
    }
}

const roundingFactor = 512 / index.ag / 2;
class TileLayerIndex {
    constructor(tileID, symbolInstances, bucketInstanceId) {
        this.tileID = tileID;
        this.bucketInstanceId = bucketInstanceId;
        this.index = new index.bE(symbolInstances.length, 16, Int32Array);
        this.keys = [];
        this.crossTileIDs = [];
        const tx = tileID.canonical.x * index.ag;
        const ty = tileID.canonical.y * index.ag;
        for (let i = 0; i < symbolInstances.length; i++) {
            const {key, crossTileID, tileAnchorX, tileAnchorY} = symbolInstances.get(i);
            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 * index.ag;
        const ty = newTileID.canonical.y * index.ag;
        for (let i = 0; i < symbolInstances.length; i++) {
            const symbolInstance = symbolInstances.get(i);
            if (symbolInstance.crossTileID) {
                continue;
            }
            const {key, tileAnchorX, tileAnchorY} = symbolInstance;
            const x = Math.floor((tx + tileAnchorX) * scale);
            const y = Math.floor((ty + tileAnchorY) * scale);
            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)) {
                    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) {
                    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 {
                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] = /* @__PURE__ */
            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) {
                symbolInstance.crossTileID = crossTileIDs.generate();
                zoomCrossTileIDs.add(symbolInstance.crossTileID);
            }
        }
        if (this.indexes[tileID.overscaledZ] === void 0) {
            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 === void 0) {
            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];
            }
        }
    }
}

const ZERO = 0;
const ONE = 1;
const SRC_ALPHA = 770;
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, index.aj.transparent, [
    false,
    false,
    false,
    false
]);
ColorMode.unblended = new ColorMode(ColorMode.Replace, index.aj.transparent, [
    true,
    true,
    true,
    true
]);
ColorMode.alphaBlended = new ColorMode([
    ONE,
    ONE_MINUS_SRC_ALPHA,
    ONE,
    ONE_MINUS_SRC_ALPHA
], index.aj.transparent, [
    true,
    true,
    true,
    true
]);
ColorMode.alphaBlendedNonPremultiplied = new ColorMode([
    SRC_ALPHA,
    ONE_MINUS_SRC_ALPHA,
    SRC_ALPHA,
    ONE_MINUS_SRC_ALPHA
], index.aj.transparent, [
    true,
    true,
    true,
    true
]);
ColorMode.multiply = new ColorMode([
    DST_COLOR,
    ZERO,
    DST_COLOR,
    ZERO
], index.aj.transparent, [
    true,
    true,
    true,
    true
]);

const ALWAYS$1 = 519;
class DepthMode {
    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 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);

function updateTransformOrientation(matrix, orientation) {
    const position = index.bG(matrix, 3);
    index.ab.mat4.fromQuat(matrix, orientation);
    index.bI(matrix, 3, position);
}
function updateTransformPosition(matrix, position) {
    index.bI(matrix, 3, [
        position[0],
        position[1],
        position[2],
        1
    ]);
}
function orientationFromPitchBearing(pitch, bearing) {
    const orientation = index.ab.quat.identity([]);
    index.ab.quat.rotateZ(orientation, orientation, -bearing);
    index.ab.quat.rotateX(orientation, orientation, -pitch);
    return orientation;
}
function orientationFromFrame(forward, up) {
    const xyForward = [
        forward[0],
        forward[1],
        0
    ];
    const xyUp = [
        up[0],
        up[1],
        0
    ];
    const epsilon = 1e-15;
    if (index.ab.vec3.length(xyForward) >= epsilon) {
        const xyDir = index.ab.vec3.normalize([], xyForward);
        index.ab.vec3.scale(xyUp, xyDir, index.ab.vec3.dot(xyUp, xyDir));
        up[0] = xyUp[0];
        up[1] = xyUp[1];
    }
    const right = index.ab.vec3.cross([], up, forward);
    if (index.ab.vec3.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);
}
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 index.aa ? position : new index.aa(position[0], position[1], position[2]);
            if (this._renderWorldCopies) {
                mercatorCoordinate.x = index.bF(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(index.aa.fromLngLat(location)) : 0;
        const target = index.aa.fromLngLat(location, altitude);
        const forward = [
            target.x - pos.x,
            target.y - pos.y,
            target.z - pos.z
        ];
        if (!up)
            up = [
                0,
                0,
                1
            ];
        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(index.ai(pitch), index.ai(-bearing));
    }
}
class FreeCamera {
    constructor(position, orientation) {
        this._transform = index.ab.mat4.identity([]);
        this.orientation = orientation;
        this.position = position;
    }
    get mercatorPosition() {
        const pos = this.position;
        return new index.aa(pos[0], pos[1], pos[2]);
    }
    get position() {
        const col = index.bG(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 || index.ab.quat.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 = index.bG(this._transform, 2);
        return [
            -col[0],
            -col[1],
            -col[2]
        ];
    }
    up() {
        const col = index.bG(this._transform, 1);
        return [
            -col[0],
            -col[1],
            -col[2]
        ];
    }
    right() {
        const col = index.bG(this._transform, 0);
        return [
            col[0],
            col[1],
            col[2]
        ];
    }
    getCameraToWorld(worldSize, pixelsPerMeter) {
        const cameraToWorld = new Float64Array(16);
        index.ab.mat4.invert(cameraToWorld, this.getWorldToCamera(worldSize, pixelsPerMeter));
        return cameraToWorld;
    }
    getCameraToWorldMercator() {
        return this._transform;
    }
    getWorldToCameraPosition(worldSize, pixelsPerMeter, uniformScale) {
        const invPosition = this.position;
        index.ab.vec3.scale(invPosition, invPosition, -worldSize);
        const matrix = new Float64Array(16);
        index.ab.mat4.fromScaling(matrix, [
            uniformScale,
            uniformScale,
            uniformScale
        ]);
        index.ab.mat4.translate(matrix, matrix, invPosition);
        matrix[10] *= pixelsPerMeter;
        return matrix;
    }
    getWorldToCamera(worldSize, pixelsPerMeter) {
        const matrix = new Float64Array(16);
        const invOrientation = new Float64Array(4);
        const invPosition = this.position;
        index.ab.quat.conjugate(invOrientation, this._orientation);
        index.ab.vec3.scale(invPosition, invPosition, -worldSize);
        index.ab.mat4.fromQuat(matrix, invOrientation);
        index.ab.mat4.translate(matrix, matrix, invPosition);
        matrix[1] *= -1;
        matrix[5] *= -1;
        matrix[9] *= -1;
        matrix[13] *= -1;
        matrix[8] *= pixelsPerMeter;
        matrix[9] *= pixelsPerMeter;
        matrix[10] *= pixelsPerMeter;
        matrix[11] *= pixelsPerMeter;
        return matrix;
    }
    getCameraToClipPerspective(fovy, aspectRatio, nearZ, farZ) {
        const matrix = new Float64Array(16);
        index.ab.mat4.perspective(matrix, fovy, aspectRatio, nearZ, farZ);
        return matrix;
    }
    getCameraToClipOrthographic(left, right, bottom, top, nearZ, farZ) {
        const matrix = new Float64Array(16);
        index.ab.mat4.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 : index.bH(elevationMeters, convert ? index.aS(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]);
    }
}

const shadowUniforms = context => ({
    'u_light_matrix_0': new index.bJ(context),
    'u_light_matrix_1': new index.bJ(context),
    'u_fade_range': new index.bK(context),
    'u_shadow_normal_offset': new index.bL(context),
    'u_shadow_intensity': new index.bM(context),
    'u_shadow_texel_size': new index.bM(context),
    'u_shadow_map_resolution': new index.bM(context),
    'u_shadow_direction': new index.bL(context),
    'u_shadow_bias': new index.bL(context),
    'u_shadowmap_0': new index.bN(context),
    'u_shadowmap_1': new index.bN(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
    };
}

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

const groundShadowUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_ground_shadow_factor': new index.bL(context)
});
const groundShadowUniformValues = (matrix, shadowFactor) => ({
    'u_matrix': matrix,
    'u_ground_shadow_factor': shadowFactor
});

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 = index.af(start.top, target.top, t);
        if (target.bottom != null && start.bottom != null)
            this.bottom = index.af(start.bottom, target.bottom, t);
        if (target.left != null && start.left != null)
            this.left = index.af(start.left, target.left, t);
        if (target.right != null && start.right != null)
            this.right = index.af(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) {
        const x = index.aw((this.left + width - this.right) / 2, 0, width);
        const y = index.aw((this.top + height - this.bottom) / 2, 0, height);
        return new index.P(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
        };
    }
}

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;
};
class Transform {
    constructor(minZoom, maxZoom, minPitch, maxPitch, renderWorldCopies, projection, bounds) {
        this.tileSize = 512;
        this._renderWorldCopies = renderWorldCopies === void 0 ? true : renderWorldCopies;
        this._minZoom = minZoom || DEFAULT_MIN_ZOOM;
        this._maxZoom = maxZoom || 22;
        this._minPitch = minPitch === void 0 || minPitch === null ? 0 : minPitch;
        this._maxPitch = maxPitch === void 0 || maxPitch === null ? 60 : maxPitch;
        this.setProjection(projection);
        this.setMaxBounds(bounds);
        this.width = 0;
        this.height = 0;
        this._center = new index.bO(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._expandedProjMatrixCache = {};
        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
        ];
        this._tileCoverLift = 0;
        this.freezeTileCoverage = false;
        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._orthographicProjectionAtLowPitch = this._orthographicProjectionAtLowPitch;
        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 index.ay(this.projection, [
            'name',
            'center',
            'parallels'
        ]);
    }
    // Returns whether the projection changes
    setProjection(projection) {
        this.projectionOptions = projection || { name: 'mercator' };
        const oldProjection = this.projection ? this.getProjection() : void 0;
        this.projection = index.bP(this.projectionOptions);
        const newProjection = this.getProjection();
        const projectionHasChanged = !index.bn(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 = index.bP({ 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 === void 0) {
            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 index.bH(1, this.center.lat) * this.cameraWorldSizeForFog;
    }
    get centerOffset() {
        return this.centerPoint._sub(this.size._div(2));
    }
    get size() {
        return new index.P(this.width, this.height);
    }
    get bearing() {
        return index.bF(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();
        this.rotationMatrix = index.ab.mat2.create();
        index.ab.mat2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);
    }
    get pitch() {
        return this._pitch / Math.PI * 180;
    }
    set pitch(pitch) {
        const p = index.aw(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 = index.ai(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;
    }
    get tileCoverLift() {
        return this._tileCoverLift;
    }
    set tileCoverLift(lift) {
        if (this._tileCoverLift === lift)
            return;
        this._tileCoverLift = lift;
    }
    _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)) {
            this._centerAltitude = 0;
            this._seaLevelZoom = null;
            this._centerAltitudeValidForExaggeration = void 0;
            return;
        }
        const elevation = this._elevation;
        if (usePreviousCenter || this._centerAltitude && this._centerAltitudeValidForExaggeration && elevation.exaggeration() && this._centerAltitudeValidForExaggeration !== elevation.exaggeration()) {
            const previousExaggeration = this._centerAltitudeValidForExaggeration;
            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 === void 0) {
            return;
        }
        const height = this.cameraToCenterDistance;
        const terrainElevation = this.pixelsPerMeter * this._centerAltitude;
        const mercatorZ = (terrainElevation + height) / this.worldSize;
        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 index.P(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;
        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;
        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) {
        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 = index.ab.vec3.length(index.ab.vec3.sub([], this._camera.position, targetPosition));
        return index.aw(this._zoomFromMercatorZ(distToTarget), this._minZoom, this._maxZoom);
    }
    setFreeCameraOptions(options) {
        if (!this.height)
            return;
        if (!options.position && !options.orientation)
            return;
        this._updateCameraState();
        let changed = false;
        if (options.orientation && !index.ab.quat.exactEquals(options.orientation, this._camera.orientation)) {
            changed = this._setCameraOrientation(options.orientation);
        }
        if (options.position) {
            const newPosition = [
                options.position.x,
                options.position.y,
                options.position.z
            ];
            if (!index.ab.vec3.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 index.aa(pos[0], pos[1], pos[2]);
        options.orientation = this._camera.orientation;
        options._elevation = this.elevation;
        options._renderWorldCopies = this.renderWorldCopies;
        return options;
    }
    _setCameraOrientation(orientation) {
        if (!index.ab.quat.length(orientation))
            return false;
        index.ab.quat.normalize(orientation, orientation);
        const forward = index.ab.vec3.transformQuat([], [
            0,
            0,
            -1
        ], orientation);
        const up = index.ab.vec3.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) {
        const minWorldSize = this.zoomScale(this.minZoom) * this.tileSize;
        const maxWorldSize = this.zoomScale(this.maxZoom) * this.tileSize;
        const distToCenter = this.cameraToCenterDistance;
        position[2] = index.aw(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));
        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 index.bQ(0, tileID)];
        if (this.renderWorldCopies) {
            const utl = this.pointCoordinate(new index.P(0, 0));
            const utr = this.pointCoordinate(new index.P(this.width, 0));
            const ubl = this.pointCoordinate(new index.P(this.width, this.height));
            const ubr = this.pointCoordinate(new index.P(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));
            const extraWorldCopy = 1;
            for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {
                if (w === 0)
                    continue;
                result.push(new index.bQ(w, tileID));
            }
        }
        return result;
    }
    isLODDisabled(checkPitch) {
        return (!checkPitch || this.pitch <= MIN_LOD_PITCH) && this._edgeInsets.top <= this._edgeInsets.bottom && !this._elevation && !this.projection.isReprojectedInTileSpace;
    }
    /**
   * Extends tile coverage to include potential neighboring tiles using either light direction or quadrant visibility information.
   * @param {Array<OverscaledTileID>} coveringTiles tile cover that is extended
   * @param {number} maxZoom maximum zoom level
   * @param {Vec3} lightDir direction of the light (unit vector), if undefined quadrant visibility information is used
   * @returns {Array<OverscaledTileID>} a set of extension tiles
   */
    extendTileCover(coveringTiles, maxZoom, lightDir) {
        let out = [];
        const extendShadows = lightDir !== void 0;
        const extendQuadrants = !extendShadows;
        if (extendQuadrants && this.zoom < maxZoom)
            return out;
        if (extendShadows && lightDir[0] === 0 && lightDir[1] === 0)
            return out;
        const addedTiles = /* @__PURE__ */
        new Set();
        const addTileId = (overscaledZ, wrap2, z, x, y) => {
            const key = index.c5(wrap2, overscaledZ, z, x, y);
            if (!addedTiles.has(key)) {
                out.push(new index.aG(overscaledZ, wrap2, z, x, y));
                addedTiles.add(key);
            }
        };
        for (let i = 0; i < coveringTiles.length; i++) {
            const id = coveringTiles[i];
            if (extendQuadrants && id.canonical.z !== maxZoom)
                continue;
            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 (extendShadows) {
                if (lightDir[0] < 0) {
                    addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y);
                    if (lightDir[1] < 0 && yMaxInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1);
                        addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y + 1);
                    }
                    if (lightDir[1] > 0 && yMinInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1);
                        addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y - 1);
                    }
                } else if (lightDir[0] > 0) {
                    addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y);
                    if (lightDir[1] < 0 && yMaxInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1);
                        addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y + 1);
                    }
                    if (lightDir[1] > 0 && yMinInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1);
                        addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y - 1);
                    }
                } else {
                    if (lightDir[1] < 0 && yMaxInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1);
                    } else if (yMinInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1);
                    }
                }
            } else {
                const visibility = id.visibleQuadrants;
                if (visibility & 1    /* TopLeft */) {
                    addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y);
                    if (yMinInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1);
                        addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y - 1);
                    }
                }
                if (visibility & 2    /* TopRight */) {
                    addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y);
                    if (yMinInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y - 1);
                        addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y - 1);
                    }
                }
                if (visibility & 4    /* BottomLeft */) {
                    addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y);
                    if (yMaxInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1);
                        addTileId(overscaledZ, leftWrap, tileId.z, leftTileX, tileId.y + 1);
                    }
                }
                if (visibility & 8    /* BottomRight */) {
                    addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y);
                    if (yMaxInsideRange) {
                        addTileId(overscaledZ, tileWrap, tileId.z, tileId.x, tileId.y + 1);
                        addTileId(overscaledZ, rightWrap, tileId.z, rightTileX, tileId.y + 1);
                    }
                }
            }
        }
        const nonOverlappingIds = [];
        for (const id of out) {
            if (!out.some(ancestorCandidate => id.isChildOf(ancestorCandidate))) {
                nonOverlappingIds.push(id);
            }
        }
        out = nonOverlappingIds.filter(newId => !coveringTiles.some(oldId => {
            if (newId.overscaledZ < maxZoom && oldId.isChildOf(newId)) {
                return true;
            }
            return newId.equals(oldId) || newId.isChildOf(oldId);
        }));
        if (extendQuadrants) {
            const numTiles = 1 << maxZoom;
            const isGlobe = this.projection.name === 'globe';
            const cameraCoord = isGlobe ? this._camera.mercatorPosition : this.pointCoordinate(this.getCameraPoint());
            const cameraPoint = [
                numTiles * cameraCoord.x,
                numTiles * cameraCoord.y
            ];
            const limit = 4;
            const limitSq = limit * limit;
            out = out.filter(id => {
                const tileCenterX = id.canonical.x + 0.5;
                const tileCenterY = id.canonical.y + 0.5;
                const dx = tileCenterX - cameraPoint[0];
                const dy = tileCenterY - cameraPoint[1];
                const distSq = dx * dx + dy * dy;
                return distSq < limitSq;
            });
        }
        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 !== void 0 && z < options.minzoom)
            return [];
        if (options.maxzoom !== void 0 && 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 = index.bR.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, z, zInMeters);
        const cameraCoord = isGlobe ? this._camera.mercatorPosition : this.pointCoordinate(this.getCameraPoint());
        const meterToTile = numTiles * index.bH(1, this.center.lat);
        const cameraAltitude = this._camera.position[2] / index.bH(1, this.center.lat);
        const cameraPoint = [
            numTiles * cameraCoord.x,
            numTiles * cameraCoord.y,
            cameraAltitude * (zInMeters ? 1 : meterToTile)
        ];
        const verticalFrustumIntersect = isGlobe || hasExaggeration;
        const zoomSplitDistance = this.cameraToCenterDistance / options.tileSize * (options.roundZoom ? 1 : 0.502);
        const minZoom = this.isLODDisabled(true) ? z : 0;
        let maxRange;
        if (this._elevation && options.isTerrainDEM) {
            maxRange = this._elevation.exaggeration() * 10000;
        } else if (this._elevation) {
            const minMaxOpt = this._elevation.getMinMaxForVisibleTiles();
            maxRange = minMaxOpt ? minMaxOpt.max : this._centerAltitude;
        } else {
            maxRange = this._centerAltitude;
        }
        const minRange = options.isTerrainDEM ? -maxRange : this._elevation ? this._elevation.getMinElevationBelowMSL() : 0;
        const scaleAdjustment = this.projection.isReprojectedInTileSpace ? index.bS(this) : 1;
        const relativeScaleAtMercatorCoord = mc => {
            const offset = 1 / 40000;
            const mcEast = new index.aa(mc.x + offset, mc.y, mc.z);
            const mcSouth = new index.aa(mc.x, mc.y + offset, mc.z);
            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);
            const dx = Math.hypot(pEast.x - p.x, pEast.y - p.y);
            const dy = Math.hypot(pSouth.x - p.x, pSouth.y - p.y);
            return Math.sqrt(dx * dy) * scaleAdjustment / offset;
        };
        const newRootTile = wrap2 => {
            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: index.bV(this, numTiles, 0, 0, 0, wrap2, min, max, this.projection),
                zoom: 0,
                x: 0,
                y: 0,
                minZ: min,
                maxZ: max,
                wrap: wrap2,
                fullyVisible: false
            };
        };
        const stack = [];
        let result = [];
        const maxZoom = z;
        const overscaledZ = options.reparseOverscaled ? actualZ : z;
        const cameraHeight = (cameraAltitude - this._centerAltitude) * meterToTile;
        const getAABBFromElevation = it => {
            if (!this._elevation || !it.tileID || !isMercator)
                return;
            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) {
                    aabb.min[2] = aabb.max[2] = aabb.center[2] = this._centerAltitude;
                }
            }
        };
        const distToSplitScale = (dz, d) => {
            const acuteAngleThresholdSin = 0.707;
            const stretchTile = 1.1;
            if (d * acuteAngleThresholdSin < dz)
                return 1;
            const r = d / dz;
            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 dz = cameraHeight;
            let tileScaleAdjustment = 1;
            if (isGlobe) {
                dz = it.aabb.distanceZ(cameraPoint);
                const tilesAtZoom = Math.pow(2, it.zoom);
                const minLat = index.aS((it.y + 1) / tilesAtZoom);
                const maxLat = index.aS(it.y / tilesAtZoom);
                const closestLat = Math.min(Math.max(centerLatitude, minLat), maxLat);
                const relativeTileScale = index.c9(closestLat) / index.c9(centerLatitude);
                if (closestLat === centerLatitude) {
                    const maxDivergence = 0.3;
                    tileScaleAdjustment = 1 / Math.max(1, this._mercatorScaleRatio - maxDivergence);
                } else {
                    tileScaleAdjustment = Math.min(1, relativeTileScale / this._mercatorScaleRatio);
                }
                if (this.zoom <= index.c6 && it.zoom === maxZoom - 1 && relativeTileScale >= 0.9) {
                    return true;
                }
            } else {
                if (useElevationData) {
                    dz = it.aabb.distanceZ(cameraPoint) * meterToTile;
                }
                if (this.projection.isReprojectedInTileSpace && actualZ <= 5) {
                    const numTiles2 = Math.pow(2, it.zoom);
                    const relativeScale = relativeScaleAtMercatorCoord(new index.aa((it.x + 0.5) / numTiles2, (it.y + 0.5) / numTiles2));
                    tileScaleAdjustment = relativeScale > 0.85 ? 1 : relativeScale;
                }
            }
            if (!isMercator) {
                const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
                let distToSplit2 = (1 << maxZoom - it.zoom) * zoomSplitDistance * tileScaleAdjustment;
                distToSplit2 = distToSplit2 * distToSplitScale(Math.max(dz, cameraHeight), distance);
                return distance < distToSplit2;
            }
            let closestDistance = Number.MAX_VALUE;
            let closestElevation = 0;
            const corners = it.aabb.getCorners();
            const distanceXyz = [];
            for (const corner of corners) {
                index.ab.vec3.sub(distanceXyz, corner, cameraPoint);
                if (!isGlobe) {
                    if (useElevationData) {
                        distanceXyz[2] *= meterToTile;
                    } else {
                        distanceXyz[2] = cameraHeight;
                    }
                }
                const dist = index.ab.vec3.dot(distanceXyz, this._camera.forward());
                if (dist < closestDistance) {
                    closestDistance = dist;
                    closestElevation = Math.abs(distanceXyz[2]);
                }
            }
            let distToSplit = (1 << maxZoom - it.zoom) * zoomSplitDistance * tileScaleAdjustment;
            distToSplit *= distToSplitScale(Math.max(closestElevation, cameraHeight), closestDistance);
            if (closestDistance < distToSplit) {
                return true;
            }
            const closestPointToCenter = it.aabb.closestPoint(centerPoint);
            return closestPointToCenter[0] === centerPoint[0] && closestPointToCenter[1] === centerPoint[1];
        };
        if (this.renderWorldCopies) {
            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);
            };
            if (!fullyVisible) {
                let intersectResult = verticalFrustumIntersect ? it.aabb.intersects(cameraFrustum) : it.aabb.intersectsFlat(cameraFrustum);
                if (intersectResult === 0 && isPoleNeighbourAndGlobeProjection()) {
                    const tileId = new index.bT(it.zoom, x, y);
                    const poleAABB = index.bU(this, numTiles, tileId, true);
                    intersectResult = poleAABB.intersects(cameraFrustum);
                }
                if (intersectResult === 0) {
                    continue;
                }
                fullyVisible = intersectResult === 2;
            }
            if (it.zoom === maxZoom || !shouldSplit(it)) {
                const tileZoom = it.zoom === maxZoom ? overscaledZ : it.zoom;
                if (!!options.minzoom && options.minzoom > tileZoom) {
                    continue;
                }
                let visibility = 0    /* None */;
                if (!fullyVisible) {
                    let intersectResult = verticalFrustumIntersect ? it.aabb.intersectsPrecise(cameraFrustum) : it.aabb.intersectsPreciseFlat(cameraFrustum);
                    if (intersectResult === 0 && isPoleNeighbourAndGlobeProjection()) {
                        const tileId = new index.bT(it.zoom, x, y);
                        const poleAABB = index.bU(this, numTiles, tileId, true);
                        intersectResult = poleAABB.intersectsPrecise(cameraFrustum);
                    }
                    if (intersectResult === 0) {
                        continue;
                    }
                    if (options.calculateQuadrantVisibility) {
                        if (cameraFrustum.containsPoint(it.aabb.center)) {
                            visibility = 15    /* All */;
                        } else {
                            for (let i = 0; i < 4; i++) {
                                const quadrantAabb = it.aabb.quadrant(i);
                                if (quadrantAabb.intersects(cameraFrustum) !== 0) {
                                    visibility |= 1 << i;
                                }
                            }
                        }
                    }
                }
                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 index.aG(tileZoom, it.wrap, it.zoom, x, y);
                if (options.calculateQuadrantVisibility) {
                    id.visibleQuadrants = visibility;
                }
                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) : index.bV(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: void 0,
                    shouldSplit: void 0,
                    minZ: it.minZ,
                    maxZ: it.maxZ
                };
                if (useElevationData && !isGlobe) {
                    child.tileID = new index.aG(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 = [
                    index.ag,
                    index.ag,
                    0,
                    1
                ];
                const fogTileMatrix = this.calculateFogTileMatrix(entry.tileID.toUnwrapped());
                index.ab.vec4.transformMat4(tl, tl, fogTileMatrix);
                index.ab.vec4.transformMat4(br, br, fogTileMatrix);
                const min = index.ab.vec4.min([], tl, br);
                const max = index.ab.vec4.max([], tl, br);
                const sqDist = index.bW(min, max);
                if (sqDist === 0) {
                    return true;
                }
                let overHorizonLine = false;
                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
                        };
                    }
                    const cornerFar = index.c7(this.rotation);
                    const farX = cornerFar[0] * index.ag;
                    const farY = cornerFar[1] * index.ag;
                    const worldFar = [
                        farX,
                        farY,
                        minmax.max
                    ];
                    index.ab.vec3.transformMat4(worldFar, worldFar, projMatrix);
                    const screenCoordY = (1 - worldFar[1]) * this.height * 0.5;
                    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 = index.aw(lnglat.lat, -index.bX, index.bX);
        const projectedLngLat = this.projection.project(lnglat.lng, lat);
        return new index.P(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 / index.bH(1, this.center.lat) / this.worldSize;
    }
    setLocationAtPoint(lnglat, point) {
        let x, y;
        const centerPoint = this.centerPoint;
        if (this.projection.name === '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 index.aa(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 ? index.bH(altitude, lngLat.lat) : void 0;
        const projectedLngLat = this.projection.project(lngLat.lng, lngLat.lat);
        return new index.aa(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 !== void 0 && z !== null ? z : this._centerAltitude;
        const p0 = [
            p.x,
            p.y,
            0,
            1
        ];
        const p1 = [
            p.x,
            p.y,
            1,
            1
        ];
        index.ab.vec4.transformMat4(p0, p0, this.pixelMatrixInverse);
        index.ab.vec4.transformMat4(p1, p1, this.pixelMatrixInverse);
        const w0 = p0[3];
        const w1 = p1[3];
        index.ab.vec4.scale(p0, p0, 1 / w0);
        index.ab.vec4.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
        ];
        index.ab.vec4.transformMat4(p0, p0, this.pixelMatrixInverse);
        index.ab.vec4.transformMat4(p1, p1, this.pixelMatrixInverse);
        index.ab.vec4.scale(p0, p0, 1 / p0[3]);
        index.ab.vec4.scale(p1, p1, 1 / p1[3]);
        p0[2] = index.bH(p0[2], this._center.lat) * this.worldSize;
        p1[2] = index.bH(p1[2], this._center.lat) * this.worldSize;
        index.ab.vec4.scale(p0, p0, 1 / this.worldSize);
        index.ab.vec4.scale(p1, p1, 1 / this.worldSize);
        return new index.aq([
            p0[0],
            p0[1],
            p0[2]
        ], index.ab.vec3.normalize([], index.ab.vec3.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 = index.bH(p0[2], this._center.lat);
        const z1 = index.bH(p1[2], this._center.lat);
        return new index.aa(index.af(p0[0], p1[0], t) / this.worldSize, index.af(p0[1], p1[1], t) / this.worldSize, index.af(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 index.aa(raycast[0], raycast[1], raycast[2]);
        let start = 0, end = this.horizonLineFromTop();
        if (p.y > end)
            return this.pointCoordinate(p);
        const samples = 10;
        const threshold = 0.02 * end;
        const r = p.clone();
        for (let i = 0; i < samples && end - start > threshold; i++) {
            r.y = index.af(start, end, 0.66);
            const rCast = this.projection.pointCoordinate3D(this, r.x, r.y);
            if (rCast) {
                end = r.y;
                raycast = rCast;
            } else {
                start = r.y;
            }
        }
        return raycast ? new index.aa(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 >= index.bY)
            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
        ];
        index.ab.vec4.transformMat4(p, p, this.pixelMatrix);
        return p[3] > 0 ? new index.P(p[0] / p[3], p[1] / p[3]) : new index.P(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 index.P(left, top));
        const tr = this.pointLocation3D(new index.P(right, top));
        const br = this.pointLocation3D(new index.P(right, bottom));
        const bl = this.pointLocation3D(new index.P(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);
        const s = Math.pow(2, -this.zoom);
        const maxErr = s / 16 * 270;
        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 index.P(mx, my);
            const {lng, lat} = this.pointLocation3D(p);
            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] = index.bZ(this);
            if (northPoleIsVisible) {
                north = 90;
                east = 180;
                west = -180;
            } else if (southPoleIsVisible) {
                south = -90;
                east = 180;
                west = -180;
            }
        }
        return new index.az(new index.bO(west, south), new index.bO(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 index.P(left, top);
        const topRight = new index.P(right, top);
        const bottomRight = new index.P(right, bottom);
        const bottomLeft = new index.P(left, bottom);
        let tl = this.pointCoordinate(topLeft, min);
        let tr = this.pointCoordinate(topRight, min);
        const br = this.pointCoordinate(bottomRight, max);
        const bl = this.pointCoordinate(bottomLeft, max);
        const slope = (p1, p2) => (p2.y - p1.y) / (p2.x - p1.x);
        if (tl.y > 1 && tr.y >= 0)
            tl = new index.aa((1 - bl.y) / slope(bl, tl) + bl.x, 1);
        else if (tl.y < 0 && tr.y <= 1)
            tl = new index.aa(-bl.y / slope(bl, tl) + bl.x, 0);
        if (tr.y > 1 && tl.y >= 0)
            tr = new index.aa((1 - br.y) / slope(br, tr) + br.x, 1);
        else if (tr.y < 0 && tl.y <= 1)
            tr = new index.aa(-br.y / slope(br, tr) + br.x, 0);
        return new index.az().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) {
        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 = -index.bX;
        this.maxLat = index.bX;
        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 = index.at(this.minLng) * this.tileSize;
        this.worldMaxX = index.at(this.maxLng) * this.tileSize;
        this.worldMinY = index.aA(this.maxLat) * this.tileSize;
        this.worldMaxY = index.aA(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];
        }
        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.x *= cws / this.worldSize;
        center.y *= cws / this.worldSize;
        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 / index.ag * 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);
        index.ab.mat4.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, expanded = false) {
        const projMatrixKey = unwrappedTileID.key;
        let cache;
        if (expanded) {
            cache = this._expandedProjMatrixCache;
        } else if (aligned) {
            cache = this._alignedProjMatrixCache;
        } else {
            cache = this._projMatrixCache;
        }
        if (cache[projMatrixKey]) {
            return cache[projMatrixKey];
        }
        const posMatrix = this.calculatePosMatrix(unwrappedTileID, this.worldSize);
        let projMatrix;
        if (this.projection.isReprojectedInTileSpace) {
            projMatrix = this.mercatorMatrix;
        } else if (expanded) {
            projMatrix = this.expandedFarZProjMatrix;
        } else {
            projMatrix = aligned ? this.alignedProjMatrix : this.projMatrix;
        }
        index.ab.mat4.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 = index.b_(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 = index.ab.mat4.fromScaling([], [
                pixelsToMerc,
                pixelsToMerc,
                pixelsToMerc
            ]);
            index.ab.mat4.multiply(m, m, this.globeMatrix);
            return m;
        }
        return void 0;
    }
    recenterOnTerrain() {
        if (!this._elevation || this.projection.name === 'globe')
            return;
        const elevation = this._elevation;
        this._updateCameraState();
        const mercPixelsPerMeter = index.bH(1, this._center.lat) * this.worldSize;
        const start = this._computeCameraPosition(mercPixelsPerMeter);
        const dir = this._camera.forward();
        const metersToMerc = index.bH(1, this._center.lat);
        start[2] /= metersToMerc;
        dir[2] /= metersToMerc;
        index.ab.vec3.normalize(dir, dir);
        const t = elevation.raycast(start, dir, elevation.exaggeration());
        if (t) {
            const point = index.ab.vec3.scaleAndAdd([], start, dir, t);
            const newCenter = new index.aa(point[0], point[1], index.bH(point[2], index.aS(point[1])));
            const camToNew = [
                newCenter.x - start[0],
                newCenter.y - start[1],
                newCenter.z - start[2] * metersToMerc
            ];
            const maxAltitude = (newCenter.z + index.ab.vec3.length(camToNew)) * this._pixelsPerMercatorPixel;
            this._seaLevelZoom = this._zoomFromMercatorZ(maxAltitude);
            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;
        const mercPixelsPerMeter = index.bH(1, this._center.lat) * this.worldSize;
        const pos = this._computeCameraPosition(mercPixelsPerMeter);
        const elevationAtCamera = elevation.getAtPointOrZero(new index.aa(...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 = index.ab.vec3.length(cameraToCenter);
                cameraToCenter[2] -= (minHeight - cameraHeight) / this._pixelsPerMercatorPixel;
                const newDistToCamera = index.ab.vec3.length(cameraToCenter);
                if (newDistToCamera === 0)
                    return;
                index.ab.vec3.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;
        if (this.projection.isReprojectedInTileSpace || isGlobe) {
            const center = this.center;
            center.lat = index.aw(center.lat, this.minLat, this.maxLat);
            if (this.maxBounds || !(this.renderWorldCopies || isGlobe))
                center.lng = index.aw(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;
            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) {
            this.center = this.unproject(new index.P(x2, y2));
        }
        if (s) {
            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';
        const pixelsPerMeter = this.pixelsPerMeter;
        if (this.projection.name === 'globe') {
            this._mercatorScaleRatio = index.bH(1, this.center.lat) / index.bH(1, index.c8);
        }
        const projectionT = index.b$(this.projection, this.zoom, this.width, this.height, 1024);
        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);
        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);
        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;
            let top = cameraToCenterDistance * Math.tan(this._fov * 0.5);
            let right = top * this.aspect;
            let left = -right;
            let bottom = -top;
            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 = index.ab.mat4.mul([], cameraToClipPerspective, worldToCamera);
        let m = index.ab.mat4.mul([], cameraToClip, worldToCamera);
        if (this.projection.isReprojectedInTileSpace) {
            const mc = this.locationCoordinate(this.center);
            const adjustments = index.ab.mat4.identity([]);
            index.ab.mat4.translate(adjustments, adjustments, [
                mc.x * this.worldSize,
                mc.y * this.worldSize,
                0
            ]);
            index.ab.mat4.multiply(adjustments, adjustments, index.c0(this));
            index.ab.mat4.translate(adjustments, adjustments, [
                -mc.x * this.worldSize,
                -mc.y * this.worldSize,
                0
            ]);
            index.ab.mat4.multiply(m, m, adjustments);
            index.ab.mat4.multiply(worldToClipPerspective, worldToClipPerspective, adjustments);
            this.inverseAdjustmentMatrix = index.c1(this);
        } else {
            this.inverseAdjustmentMatrix = [
                1,
                0,
                0,
                1
            ];
        }
        this.mercatorMatrix = index.ab.mat4.scale([], m, [
            this.worldSize,
            this.worldSize,
            this.worldSize / zUnit,
            1
        ]);
        this.projMatrix = m;
        this.invProjMatrix = index.ab.mat4.invert(new Float64Array(16), this.projMatrix);
        if (isGlobe) {
            const expandedCameraToClipPerspective = this._camera.getCameraToClipPerspective(this._fov, this.width / this.height, this._nearZ, Infinity);
            expandedCameraToClipPerspective[8] = -offset.x * 2 / this.width;
            expandedCameraToClipPerspective[9] = offset.y * 2 / this.height;
            this.expandedFarZProjMatrix = index.ab.mat4.mul([], expandedCameraToClipPerspective, worldToCamera);
        } else {
            this.expandedFarZProjMatrix = this.projMatrix;
        }
        const clipToCamera = index.ab.mat4.invert([], cameraToClip);
        this.frustumCorners = index.c2.fromInvProjectionMatrix(clipToCamera, this.horizonLineFromTop(), this.height);
        this.cameraFrustum = index.bR.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, 0, !isGlobe);
        const view = new Float32Array(16);
        index.ab.mat4.identity(view);
        index.ab.mat4.scale(view, view, [
            1,
            -1,
            1
        ]);
        index.ab.mat4.rotateX(view, view, this._pitch);
        index.ab.mat4.rotateZ(view, view, this.angle);
        const projection = index.ab.mat4.perspective(new Float32Array(16), this._fov, this.width / this.height, this._nearZ, this._farZ);
        this.starsProjMatrix = index.ab.mat4.clone(projection);
        const skyboxHorizonShift = (Math.PI / 2 - this._pitch) * (this.height / this._fov) * this._horizonShift;
        projection[8] = -offset.x * 2 / this.width;
        projection[9] = (offset.y + skyboxHorizonShift) * 2 / this.height;
        this.skyboxMatrix = index.ab.mat4.multiply(view, projection, view);
        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);
        index.ab.mat4.translate(alignedM, alignedM, [
            dx > 0.5 ? dx - 1 : dx,
            dy > 0.5 ? dy - 1 : dy,
            0
        ]);
        this.alignedProjMatrix = alignedM;
        m = index.ab.mat4.create();
        index.ab.mat4.scale(m, m, [
            this.width / 2,
            -this.height / 2,
            1
        ]);
        index.ab.mat4.translate(m, m, [
            1,
            -1,
            0
        ]);
        this.labelPlaneMatrix = m;
        m = index.ab.mat4.create();
        index.ab.mat4.scale(m, m, [
            1,
            -1,
            1
        ]);
        index.ab.mat4.translate(m, m, [
            -1,
            -1,
            0
        ]);
        index.ab.mat4.scale(m, m, [
            2 / this.width,
            2 / this.height,
            1
        ]);
        this.glCoordMatrix = m;
        this.pixelMatrix = index.ab.mat4.multiply(new Float64Array(16), this.labelPlaneMatrix, worldToClipPerspective);
        this._calcFogMatrices();
        this._distanceTileDataCache = {};
        m = index.ab.mat4.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 = index.c3(this);
            const globeCenter = [
                this.globeMatrix[12],
                this.globeMatrix[13],
                this.globeMatrix[14]
            ];
            this.globeCenterInViewSpace = index.ab.vec3.transformMat4(globeCenter, globeCenter, worldToCamera);
            this.globeRadius = this.worldSize / 2 / Math.PI - 1;
        } else {
            this.globeMatrix = m;
        }
        this._projMatrixCache = {};
        this._alignedProjMatrixCache = {};
        this._pixelsToTileUnitsCache = {};
        this._expandedProjMatrixCache = {};
    }
    _calcFogMatrices() {
        this._fogTileMatrixCache = {};
        const cameraWorldSizeForFog = this.cameraWorldSizeForFog;
        const cameraPixelsPerMeter = this.cameraPixelsPerMeter;
        const cameraPos = this._camera.position;
        const windowScaleFactor = 1 / this.height / this._pixelsPerMercatorPixel;
        const metersToPixel = [
            cameraWorldSizeForFog,
            cameraWorldSizeForFog,
            cameraPixelsPerMeter
        ];
        index.ab.vec3.scale(metersToPixel, metersToPixel, windowScaleFactor);
        index.ab.vec3.scale(cameraPos, cameraPos, -1);
        index.ab.vec3.multiply(cameraPos, cameraPos, metersToPixel);
        const m = index.ab.mat4.create();
        index.ab.mat4.translate(m, m, cameraPos);
        index.ab.mat4.scale(m, m, metersToPixel);
        this.mercatorFogMatrix = m;
        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;
        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;
        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();
        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();
        if (deltaZ > 0) {
            t = Math.min((maxZ - z) / deltaZ, 1);
        }
        this._camera.position = index.ab.vec3.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();
        const centerAltitude = index.bH(this._centerAltitude, this.center.lat) * this._pixelsPerMercatorPixel;
        const minHeight = this._mercatorZfromZoom(this._maxZoom) * Math.cos(index.ai(this._maxPitch));
        const height = Math.max((position[2] - centerAltitude) / Math.cos(pitch), minHeight);
        const zoom = this._zoomFromMercatorZ(height);
        index.ab.vec3.scaleAndAdd(position, position, dir, height);
        this._pitch = index.aw(pitch, index.ai(this.minPitch), index.ai(this.maxPitch));
        this.angle = index.bF(bearing, -Math.PI, Math.PI);
        this._setZoom(index.aw(zoom, this._minZoom, this._maxZoom));
        this._updateSeaLevelZoom();
        this._center = this.coordinateLocation(new index.aa(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() {
        const MAX_DRAPE_OVERZOOM = 4;
        const zoom = Math.min(this._seaLevelZoom != null ? this._seaLevelZoom : this._zoom, this._maxZoom) + MAX_DRAPE_OVERZOOM;
        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 = index.bY;
        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) {
            index.w('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 index.P(minX, minY);
        const max = new index.P(maxX, maxY);
        const corners = [
            min,
            max,
            new index.P(minX, maxY),
            new index.P(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);
            if (rayIntersection.t < 0) {
                return true;
            }
            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() {
        const horizonAngleEpsilon = 2;
        if (this.pitch + index.c4(this.fovAboveCenter) > 90 - horizonAngleEpsilon) {
            return true;
        }
        return this.anyCornerOffEdge(new index.P(0, 0), new index.P(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 = index.ab.vec3.length(index.ab.vec3.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') {
            const center = [
                this.globeMatrix[12],
                this.globeMatrix[13],
                this.globeMatrix[14]
            ];
            const pos = projectClamped(center, this.pixelMatrix);
            return new index.P(pos[0], pos[1]);
        } else {
            const pitch = this._pitch;
            const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);
            return this.centerPoint.add(new index.P(0, yOffset));
        }
    }
    getCameraToCenterDistance(projection, zoom = this.zoom, worldSize = this.worldSize) {
        const t = index.b$(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;
        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') {
            index.ab.mat4.multiply(worldToCamera, worldToCamera, this.globeMatrix);
        }
        return worldToCamera;
    }
    getFrustum(zoom) {
        const zInMeters = this.projection.zAxisUnit === 'meters';
        return index.bR.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, zoom, zInMeters);
    }
}

const cutoffUniforms = context => ({ 'u_cutoff_params': new index.ca(context) });
const getCutoffParams = (painter, cutoffFadeRange) => {
    if (cutoffFadeRange > 0 && painter.terrain) {
        index.w('Cutoff is currently disabled on terrain');
    }
    if (cutoffFadeRange <= 0 || painter.terrain) {
        return {
            shouldRenderCutoff: false,
            uniformValues: {
                'u_cutoff_params': [
                    0,
                    0,
                    0,
                    1
                ]
            }
        };
    }
    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) ? index.ac(MIN_LOD_PITCH, MIN_LOD_PITCH - 15, tr.pitch) : index.ac(30, 15, tr.pitch);
    const zRange = tr._farZ - tr._nearZ;
    const cameraToCenterDistance = tr.cameraToCenterDistance;
    const fadeRangePixels = cutoffFadeRange * tr.height;
    const cutoffDistance = lerp(cameraToCenterDistance, 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
            ]
        }
    };
};

const shadowParameters = {
    cascadeCount: 2,
    normalOffset: 3,
    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 !== void 0) {
            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 = index.cd.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]
                    ];
                    index.ab.vec3.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._forceDisable = false;
        this.useNormalOffset = false;
        painter.tp.registerParameter(this, ['Shadows'], '_forceDisable', { label: 'forceDisable' }, () => {
            this.painter.style.map.triggerRepaint();
        });
        painter.tp.registerParameter(shadowParameters, ['Shadows'], 'cascadeCount', {
            min: 1,
            max: 2,
            step: 1
        });
        painter.tp.registerParameter(shadowParameters, ['Shadows'], 'normalOffset', {
            min: 0,
            max: 10,
            step: 0.05
        });
        painter.tp.registerParameter(shadowParameters, ['Shadows'], 'shadowMapResolution', {
            min: 32,
            max: 2048,
            step: 32
        });
        painter.tp.registerBinding(this, ['Shadows'], '_numCascadesToRender', {
            readonly: true,
            label: 'numCascadesToRender'
        });
    }
    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 = shadowParameters.shadowMapResolution;
        const height = shadowParameters.shadowMapResolution;
        if (this._cascades.length === 0 || shadowParameters.shadowMapResolution !== this._cascades[0].texture.size[0]) {
            this._cascades = [];
            for (let i = 0; i < shadowParameters.cascadeCount; ++i) {
                const useColor = painter._shadowMapDebug;
                const gl = context.gl;
                const fbo = context.createFramebuffer(width, height, useColor, 'texture');
                const depthTexture = new index.T(context, {
                    width,
                    height,
                    data: null
                }, gl.DEPTH_COMPONENT16);
                fbo.depthAttachment.set(depthTexture.texture);
                if (useColor) {
                    const colorTexture = new index.T(context, {
                        width,
                        height,
                        data: null
                    }, gl.RGBA8);
                    fbo.colorAttachment.set(colorTexture.texture);
                }
                this._cascades.push({
                    framebuffer: fbo,
                    texture: depthTexture,
                    matrix: [],
                    far: 0,
                    boundingSphereRadius: 0,
                    frustum: new index.bR(),
                    scale: 0
                });
            }
        }
        this.shadowDirection = shadowDirectionFromProperties(directionalLight);
        let verticalRange = 0;
        if (transform.elevation) {
            const elevation2 = transform.elevation;
            const range = [
                10000,
                -10000
            ];
            elevation2.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]) * elevation2.exaggeration();
            }
        }
        const cascadeSplitDist = transform.cameraToCenterDistance * 1.5;
        const shadowCutoutDist = cascadeSplitDist * 3;
        const cameraInvProj = new Float64Array(16);
        for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) {
            const cascade = this._cascades[cascadeIndex];
            let near = transform.height / 50;
            let far = 1;
            if (shadowParameters.cascadeCount === 1) {
                far = shadowCutoutDist;
            } else {
                if (cascadeIndex === 0) {
                    far = cascadeSplitDist;
                } else {
                    near = cascadeSplitDist;
                    far = shadowCutoutDist;
                }
            }
            const [matrix, radius] = createLightMatrix(transform, this.shadowDirection, near, far, shadowParameters.shadowMapResolution, verticalRange);
            cascade.scale = transform.scale;
            cascade.matrix = matrix;
            cascade.boundingSphereRadius = radius;
            index.ab.mat4.invert(cameraInvProj, cascade.matrix);
            cascade.frustum = index.bR.fromInvProjectionMatrix(cameraInvProj, 1, 0, true);
            cascade.far = far;
        }
        const fadeRangeIdx = this._cascades.length - 1;
        this._uniformValues['u_fade_range'] = [
            this._cascades[fadeRangeIdx].far * 0.75,
            this._cascades[fadeRangeIdx].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 / shadowParameters.shadowMapResolution;
        this._uniformValues['u_shadow_map_resolution'] = shadowParameters.shadowMapResolution;
        this._uniformValues['u_shadowmap_0'] = TextureSlots.ShadowMap0;
        this._uniformValues['u_shadowmap_1'] = TextureSlots.ShadowMap0 + 1;
        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 && !this._forceDisable;
    }
    set enabled(enabled) {
        this._enabled = enabled;
    }
    drawShadowPass(style, sourceCoords) {
        if (!this.enabled) {
            return;
        }
        const painter = this.painter;
        const context = painter.context;
        this._numCascadesToRender = this._receivers.computeRequiredCascades(painter.transform.getFrustum(0), painter.transform.worldSize, this._cascades);
        context.viewport.set([
            0,
            0,
            shadowParameters.shadowMapResolution,
            shadowParameters.shadowMapResolution
        ]);
        for (let cascade = 0; cascade < this._numCascadesToRender; ++cascade) {
            painter.currentShadowCascade = cascade;
            context.bindFramebuffer.set(this._cascades[cascade].framebuffer.framebuffer);
            context.clear({
                color: index.aj.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] : void 0;
                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');
        }
        baseDefines.push('RENDER_SHADOWS', 'DEPTH_TEXTURE');
        if (this.useNormalOffset) {
            baseDefines.push('NORMAL_OFFSET');
        }
        const shadowColor = calculateGroundShadowFactor(style, 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;
        index.ab.mat4.multiply(tileMatrix, lightMatrix, tileMatrix);
        return Float32Array.from(tileMatrix);
    }
    calculateShadowPassMatrixFromMatrix(matrix) {
        const lightMatrix = this._cascades[this.painter.currentShadowCascade].matrix;
        index.ab.mat4.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 < this._cascades.length; i++) {
            index.ab.mat4.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 = index.cc(unwrappedTileID.canonical);
            const texelScale = 2 / transform.tileSize * index.ag / shadowParameters.shadowMapResolution;
            const shadowTexelInTileCoords0 = texelScale * this._cascades[0].boundingSphereRadius;
            const shadowTexelInTileCoords1 = texelScale * this._cascades[this._cascades.length - 1].boundingSphereRadius;
            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
            ];
        } 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 < shadowParameters.cascadeCount; i++) {
            index.ab.mat4.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 = shadowParameters.normalOffset;
            uniforms['u_shadow_normal_offset'] = [
                1,
                scale,
                scale
            ];
            uniforms['u_shadow_bias'] = [
                0.00006,
                0.0012,
                0.012
            ];
        } 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];
        if (lightDir[0] < 0) {
            index.ab.vec3.add(corners[0], corners[0], [
                lightDir[0] * t,
                0,
                0
            ]);
            index.ab.vec3.add(corners[3], corners[3], [
                lightDir[0] * t,
                0,
                0
            ]);
        } else if (lightDir[0] > 0) {
            index.ab.vec3.add(corners[1], corners[1], [
                lightDir[0] * t,
                0,
                0
            ]);
            index.ab.vec3.add(corners[2], corners[2], [
                lightDir[0] * t,
                0,
                0
            ]);
        }
        if (lightDir[1] < 0) {
            index.ab.vec3.add(corners[0], corners[0], [
                0,
                lightDir[1] * t,
                0
            ]);
            index.ab.vec3.add(corners[1], corners[1], [
                0,
                lightDir[1] * t,
                0
            ]);
        } else if (lightDir[1] > 0) {
            index.ab.vec3.add(corners[2], corners[2], [
                0,
                lightDir[1] * t,
                0
            ]);
            index.ab.vec3.add(corners[3], corners[3], [
                0,
                lightDir[1] * t,
                0
            ]);
        }
        const tileShadowVolume = {};
        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, index.cd.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 index.cd([
        minx,
        miny,
        0
    ], [
        maxx,
        maxy,
        height
    ]);
}
function computePlane(a, b, c) {
    const bc = index.ab.vec3.sub([], c, b);
    const ba = index.ab.vec3.sub([], a, b);
    const normal = index.ab.vec3.cross([], bc, ba);
    const len = index.ab.vec3.length(normal);
    if (len === 0) {
        return [
            0,
            0,
            1,
            0
        ];
    }
    index.ab.vec3.scale(normal, normal, 1 / len);
    return [
        normal[0],
        normal[1],
        normal[2],
        -index.ab.vec3.dot(normal, b)
    ];
}
function shadowDirectionFromProperties(directionalLight) {
    const direction = directionalLight.properties.get('direction');
    const spherical = index.cb(direction.x, direction.y, direction.z);
    const MaxPolarCoordinate = 75;
    spherical[2] = index.aw(spherical[2], 0, MaxPolarCoordinate);
    const position = index.ce([
        spherical[0],
        spherical[1],
        spherical[2]
    ]);
    return index.ab.vec3.fromValues(position.x, position.y, position.z);
}
function calculateGroundShadowFactor(style, directionalLight, ambientLight) {
    const dirColorIgnoreLut = directionalLight.properties.get('color-use-theme') === 'none';
    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 ambientColorIgnoreLut = ambientLight.properties.get('color-use-theme') === 'none';
    const ambientColor = ambientLight.properties.get('color');
    const ambientIntensity = ambientLight.properties.get('intensity');
    const groundNormal = [
        0,
        0,
        1
    ];
    const dirDirectionalFactor = Math.max(index.ab.vec3.dot(groundNormal, directionVec), 0);
    const ambStrength = [
        0,
        0,
        0
    ];
    index.ab.vec3.scale(ambStrength, ambientColor.toRenderColor(ambientColorIgnoreLut ? null : style.getLut(directionalLight.scope)).toArray01Linear().slice(0, 3), ambientIntensity);
    const dirStrength = [
        0,
        0,
        0
    ];
    index.ab.vec3.scale(dirStrength, dirColor.toRenderColor(dirColorIgnoreLut ? null : style.getLut(ambientLight.scope)).toArray01Linear().slice(0, 3), dirDirectionalFactor * dirIntensity);
    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
    ];
    return index.cf(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;
    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
    ];
    index.ab.vec3.transformMat4(sphereCenter, sphereCenter, cameraToWorldMerc);
    let sphereRadius = radius * wsInverse;
    const frustumPointToMercator = function (point) {
        point[0] /= scale;
        point[1] /= scale;
        point[2] = index.bH(point[2], transform._center.lat);
        return point;
    };
    const padding = transform._edgeInsets;
    if (padding.left !== 0 || padding.top !== 0 || padding.right !== 0 || padding.bottom !== 0) {
        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);
            cameraToClip[8] = -transform.centerOffset.x * 2 / transform.width;
            cameraToClip[9] = transform.centerOffset.y * 2 / transform.height;
            const cameraProj = new Float64Array(16);
            index.ab.mat4.mul(cameraProj, cameraToClip, worldToCamera);
            const cameraInvProj = new Float64Array(16);
            index.ab.mat4.invert(cameraInvProj, cameraProj);
            const frustum = index.bR.fromInvProjectionMatrix(cameraInvProj, ws, zoom, true);
            for (const p of frustum.points) {
                const fp = frustumPointToMercator(p);
                sphereRadius = Math.max(sphereRadius, index.ab.vec3.len(index.ab.vec3.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);
    const lightWorldToView = camera.getWorldToCamera(ws, pixelsPerMeter);
    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);
    index.ab.mat4.multiply(lightWorldToClip, lightViewToClip, lightWorldToView);
    const alignedCenter = index.ab.vec3.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
    ];
    index.ab.vec3.transformMat4(projectedPoint, alignedCenter, lightWorldToClip);
    index.ab.vec3.scale(projectedPoint, projectedPoint, halfResolution);
    const roundedPoint = [
        Math.floor(projectedPoint[0]),
        Math.floor(projectedPoint[1]),
        Math.floor(projectedPoint[2])
    ];
    const offsetVec = [
        0,
        0,
        0
    ];
    index.ab.vec3.sub(offsetVec, projectedPoint, roundedPoint);
    index.ab.vec3.scale(offsetVec, offsetVec, -1 / halfResolution);
    const truncMatrix = new Float64Array(16);
    index.ab.mat4.identity(truncMatrix);
    index.ab.mat4.translate(truncMatrix, truncMatrix, offsetVec);
    index.ab.mat4.multiply(lightWorldToClip, truncMatrix, lightWorldToClip);
    return [
        lightWorldToClip,
        radiusPx
    ];
}

class ModelManager extends index.E {
    constructor(requestManager) {
        super();
        this.requestManager = requestManager;
        this.models = { '': {} };
        this.modelUris = { '': {} };
        this.numModelsLoading = {};
    }
    loadModel(id, url) {
        return index.aM(this.requestManager.transformRequest(url, index.R.Model).url).then(gltf => {
            if (!gltf)
                return;
            const nodes = index.aN(gltf);
            const model = new index.aO(id, void 0, void 0, nodes);
            model.computeBoundsAndApplyParent();
            return model;
        }).catch(err => {
            if (err && err.status === 404) {
                return null;
            }
            this.fire(new index.y(new Error(`Could not load model ${ id } from ${ url }: ${ err.message }`)));
        });
    }
    load(modelUris, scope, options = { keepNumReferences: false }) {
        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) {
                    const previousModel = this.models[scope][modelIds[i]];
                    const numReferences = options.keepNumReferences && previousModel ? previousModel.numReferences : 1;
                    this.models[scope][modelIds[i]] = {
                        model: value,
                        numReferences
                    };
                }
            }
            this.numModelsLoading[scope] -= modelIds.length;
            this.fire(new index.z('data', { dataType: 'style' }));
        }).catch(err => {
            this.fire(new index.y(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] ? this.models[scope][id].model : void 0;
    }
    addModel(id, url, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        if (!this.modelUris[scope])
            this.modelUris[scope] = {};
        if (this.hasModel(id, scope)) {
            this.models[scope][id].numReferences++;
        }
        this.modelUris[scope][id] = this.requestManager.normalizeModelURL(url);
        this.load({ [id]: this.modelUris[scope][id] }, scope);
    }
    addModels(models, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        if (!this.modelUris[scope])
            this.modelUris[scope] = {};
        const modelUris = this.modelUris[scope];
        for (const modelId in models) {
            this.models[scope][modelId] = {};
            modelUris[modelId] = this.requestManager.normalizeModelURL(models[modelId]);
        }
        this.load(modelUris, scope, { keepNumReferences: true });
    }
    reloadModels(scope) {
        this.load(this.modelUris[scope], scope);
    }
    addModelsFromBucket(modelUris, scope) {
        if (!this.models[scope])
            this.models[scope] = {};
        if (!this.modelUris[scope])
            this.modelUris[scope] = {};
        const modelsRequests = {};
        for (const modelUri of modelUris) {
            if (this.hasModel(modelUri, scope)) {
                this.models[scope][modelUri].numReferences++;
            } else {
                this.modelUris[scope][modelUri] = this.requestManager.normalizeModelURL(modelUri);
                modelsRequests[modelUri] = this.modelUris[scope][modelUri];
            }
        }
        this.load(modelsRequests, scope);
    }
    removeModel(id, scope) {
        if (!this.models[scope] || !this.models[scope][id])
            return;
        this.models[scope][id].numReferences--;
        if (this.models[scope][id].numReferences === 0) {
            const model = this.models[scope][id].model;
            delete this.models[scope][id];
            delete this.modelUris[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]) {
            if (this.models[scope][modelId].model) {
                this.models[scope][modelId].model.upload(painter.context);
            }
        }
    }
}

const colorizationProperties = new index.a5({ 'data': new index.a6(index.a3.colorTheme.data) });
function evaluateColorThemeProperties(scope, values, configOptions) {
    const properties = index.l({}, values);
    for (const name of Object.keys(index.a3.colorTheme)) {
        if (properties[name] === void 0) {
            properties[name] = index.a3.colorTheme[name].default;
        }
    }
    const transitionable = new index.a4(colorizationProperties, scope, new Map(configOptions));
    transitionable.setTransitionOrValue(properties, configOptions);
    const transitioning = transitionable.untransitioned();
    return transitioning.possiblyEvaluate(new index.a8(0));
}

function getCircumcircle(rectangle) {
    const [[topLeftX, topLeftY], [bottomRightX, bottomRightY]] = rectangle;
    const dx = (bottomRightX - topLeftX + 360) % 360;
    const wrappedDx = dx > 180 ? 360 - dx : dx;
    const centerX = (topLeftX + wrappedDx / 2 + 360) % 360;
    const centerY = (topLeftY + bottomRightY) / 2;
    const dy = bottomRightY - topLeftY;
    const radius = Math.sqrt(wrappedDx ** 2 + dy ** 2) / 2;
    return {
        center: [
            centerX,
            centerY
        ],
        radius
    };
}
function isPointInCircle(point, circle) {
    const [px, py] = point;
    const {center, radius} = circle;
    const [cx, cy] = center;
    const dx = Math.abs(px - cx);
    const wrappedDx = dx > 180 ? 360 - dx : dx;
    const dy = py - cy;
    const distance = Math.sqrt(wrappedDx ** 2 + dy ** 2);
    return distance <= radius;
}
const indoorSchemaExtension = {
    // Contains an array of IDs with the active floorplans in the area
    'mbx-indoor-active-floorplans': {
        'default': [
            'literal',
            []
        ]
    },
    // True if the map should render underground floors (currently used for dimming)
    'mbx-indoor-underground': {
        'default': [
            'literal',
            false
        ]
    },
    // Contains an array of the loaded level IDs (Note: Not the same as selected!)
    'mbx-indoor-loaded-levels': {
        'default': [
            'literal',
            []
        ]
    },
    // Contains a map from the level IDs to the top height of the floor
    'mbx-indoor-level-height': {
        'default': [
            'literal',
            {}
        ]
    },
    // Contains a map from the level IDs to the base height of the floor
    'mbx-indoor-level-base': {
        'default': [
            'literal',
            {}
        ]
    },
    // Contains the selection state of the level (value is true if it is selected)
    'mbx-indoor-level-selected': {
        'default': [
            'literal',
            {}
        ]
    },
    // Contains the overlapped state of the level (value is true if it is overlapped by another level)
    'mbx-indoor-level-overlapped': {
        'default': [
            'literal',
            {}
        ]
    }
};
function expandSchemaWithIndoor(schema) {
    schema = schema ? schema : {};
    return Object.assign(schema, indoorSchemaExtension);
}
class IndoorManager extends index.E {
    constructor(map) {
        super();
        //// Public configuration options
        // If true, floors with similar floorIDs will be merged, in a floorplan that contains multiple set of floors.
        this.mergeFloors = true;
        this._scope = void 0;
        this._queryFeatureSetId = void 0;
        this._buildingEntryFeatureSetId = void 0;
        //// Indoor state management
        // The active floorplan in the current area
        this._selectedFloorplan = void 0;
        // The parsed indoor-data field of the active floorplan
        this._indoorData = void 0;
        // The selected level of the floorplan. If undefined, the map should show the overview of the area.
        // Note: currently only one level can be active per floorplan,
        // but this could be extended for multi-level selection in future use-cases.
        this._selectedLevel = void 0;
        // Tracker of the previously selected floorplan elements
        // which is used to restore selections when leaving and returning to the area.
        this._floorplanStates = {};
        index.aP([
            '_onLoad',
            '_onMove',
            '_checkFloorplanVisible'
        ], this);
        this._map = map;
        this._checkFloorplanVisible(true);
        this._map.on('load', this._onLoad);
        this._map.on('move', this._onMove);
    }
    destroy() {
        this._map.indoor.off('load', this._onLoad);
        this._map.indoor.off('move', this._onMove);
        this._map = void 0;
    }
    // Prepare IndoorManager on the map load.
    // If the style contains any fragment with "indoor" property
    // the manager gets automatically enabled and it starts querying features.
    _onLoad() {
        this._map.style.forEachFragmentStyle(style => {
            if (style.stylesheet.indoor) {
                if (!this._queryFeatureSetId) {
                    this._queryFeatureSetId = style.stylesheet.indoor.floorplanFeaturesetId;
                    this._buildingEntryFeatureSetId = style.stylesheet.indoor.buildingFeaturesetId;
                    this._scope = style.scope;
                } else {
                    this.fire(new index.y(new Error('Multiple indoor map styles detected, simultaneous usage is not allowed currently.')));
                }
            }
        });
        if (this._queryFeatureSetId && this._buildingEntryFeatureSetId) {
            this._map.addInteraction('mbx-indoor-buildingclick', {
                type: 'click',
                target: {
                    featuresetId: this._buildingEntryFeatureSetId,
                    importId: this._scope
                },
                handler: e => {
                    if (e.feature && e.feature.properties.floorplan) {
                        this.selectFloorplan(e.feature.properties.floorplan);
                    }
                    return true;
                }
            });
        }
        this._checkFloorplanVisible(true);
    }
    _onMove() {
        this._checkFloorplanVisible(false);
    }
    _checkFloorplanVisible(queryWholeScreen) {
        if (!this._queryFeatureSetId) {
            return;
        }
        if (!this._map.isStyleLoaded()) {
            return;
        }
        if (this._map.transform.zoom < 13) {
            return;
        }
        if (this._indoorData && !isPointInCircle([
                this._map.getCenter().lng,
                this._map.getCenter().lat
            ], this._indoorData.circumCircle)) {
            this._indoorData = void 0;
            this._selectedFloorplan = void 0;
            this._map.setConfigProperty(this._scope, 'mbx-indoor-underground', false);
            this._map.setConfigProperty(this._scope, 'mbx-indoor-active-floorplans', [
                'literal',
                []
            ]);
            this.fire(new index.z('floorplangone'));
        }
        const queryParams = {
            target: {
                featuresetId: this._queryFeatureSetId,
                importId: this._scope
            }
        };
        const centerPoint = new index.P(this._map.transform.width / 2, this._map.transform.height / 2);
        const wholeScreen = [
            new index.P(0, 0),
            new index.P(this._map.transform.width, this._map.transform.height)
        ];
        const features = queryWholeScreen ? this._map.queryRenderedFeatures(wholeScreen, queryParams) : this._map.queryRenderedFeatures(centerPoint, queryParams);
        if (features.length > 0) {
            if (!this._selectedFloorplan || features[0].properties.id !== this._selectedFloorplan.properties.id) {
                this._selectedFloorplan = features[0];
                this._floorplanSelected(false);
            }
        }
    }
    _floorplanSelected(withUserInput) {
        this._indoorData = JSON.parse(this._selectedFloorplan.properties['indoor-data']);
        this._indoorData.id = this._selectedFloorplan.properties.id;
        this._indoorData.circumCircle = getCircumcircle(this._indoorData.extent);
        if (!this._floorplanStates[this._indoorData.id]) {
            this._floorplanStates[this._indoorData.id] = {};
        }
        const selectedBuildingId = this._floorplanStates[this._indoorData.id].selectedBuilding;
        const selectedLevelId = this._floorplanStates[this._indoorData.id].selectedLevel;
        this._map.setConfigProperty(this._scope, 'mbx-indoor-active-floorplans', this._indoorData.floorplanIDs);
        let selectedLevelIdForFloorplan;
        if (this._selectedLevel) {
            for (const level of this._indoorData.levels) {
                if (level.id === this._selectedLevel.id) {
                    selectedLevelIdForFloorplan = level.id;
                }
            }
        }
        this.fire(new index.z('floorplanselected', {
            buildings: this._indoorData.buildings,
            levels: this._indoorData.levels,
            selectedLevelId: selectedLevelIdForFloorplan
        }));
        if (selectedBuildingId) {
            const building = this._indoorData.buildings.find(e => e.id === selectedBuildingId);
            this._buildingSelected(building, false);
        } else if (this._indoorData.buildings.length > 0) {
            this._buildingSelected(this._indoorData.buildings[0], false);
        }
        if (selectedLevelId) {
            const defaultLevel = this._indoorData.levels.find(l => l.id === selectedLevelId);
            this._updateLevels(defaultLevel, withUserInput);
        } else if (withUserInput) {
            if (this._indoorData['default-levels'].length > 0) {
                this.selectLevel(this._indoorData['default-levels'][0]);
            }
        }
    }
    _buildingSelected(selectedBuilding, animated) {
        if (animated && selectedBuilding && selectedBuilding.extent) {
            this._map.fitBounds(selectedBuilding.extent, {
                pitch: this._map.getPitch(),
                bearing: this._map.getBearing()
            });
        }
        this._floorplanStates[this._indoorData.id].selectedBuilding = selectedBuilding ? selectedBuilding.id : void 0;
        const levelsForBuilding = this._indoorData.levels.filter(item => selectedBuilding.levels.includes(item.id));
        this.fire(new index.z('buildingselected', {
            buildingId: selectedBuilding.id,
            levels: levelsForBuilding
        }));
    }
    _levelSelected(id) {
        if (id === 'overview') {
            this._updateLevels(void 0, true);
        } else {
            const selectedLevel = this._indoorData.levels.find(l => l.id === id);
            this._updateLevels(selectedLevel, true);
        }
        this.fire(new index.z('levelselected', { levelId: id === 'overview' ? void 0 : id }));
    }
    _updateLevels(selectedLevel, animated) {
        if (!selectedLevel) {
            this._map.setConfigProperty(this._scope, 'mbx-indoor-loaded-levels', [
                'literal',
                []
            ]);
            this._map.setConfigProperty(this._scope, 'mbx-indoor-underground', false);
            this._floorplanStates[this._indoorData.id].selectedLevel = void 0;
            if (animated && this._indoorData.extent) {
                this._map.fitBounds(this._indoorData.extent, {
                    pitch: this._map.getPitch(),
                    bearing: this._map.getBearing()
                });
            }
            return;
        }
        this._selectedLevel = selectedLevel;
        function getIdFromFloorString(input) {
            const floorIndex = input.indexOf('/floor/');
            if (floorIndex === -1)
                return input;
            const idStart = floorIndex + '/floor/'.length;
            const idEnd = input.indexOf('/', idStart);
            return idEnd === -1 ? input.slice(idStart) : input.slice(idStart, idEnd);
        }
        this._floorplanStates[this._indoorData.id].selectedLevel = selectedLevel ? selectedLevel.id : void 0;
        const levelkeys = [];
        const levelHeight = {};
        const levelBase = {};
        const levelSelected = {};
        const levelOverlapped = {};
        for (const level of this._indoorData.levels) {
            levelkeys.push(level.id);
            levelHeight[level.id] = level.height;
            levelBase[level.id] = level.base;
            if (selectedLevel) {
                if (this.mergeFloors) {
                    const selectedFloor = getIdFromFloorString(selectedLevel.id);
                    const targetFloor = getIdFromFloorString(level.id);
                    levelSelected[level.id] = targetFloor === selectedFloor ? 'true' : 'false';
                } else {
                    levelSelected[level.id] = level.id === selectedLevel.id ? 'true' : 'false';
                }
                levelOverlapped[level.id] = level.base < selectedLevel.base ? 'true' : 'false';
            } else {
                levelOverlapped[level.id] = true;
            }
        }
        this._map.setConfigProperty(this._scope, 'mbx-indoor-loaded-levels', [
            'literal',
            levelkeys
        ]);
        this._map.setConfigProperty(this._scope, 'mbx-indoor-level-height', [
            'literal',
            levelHeight
        ]);
        this._map.setConfigProperty(this._scope, 'mbx-indoor-level-base', [
            'literal',
            levelBase
        ]);
        this._map.setConfigProperty(this._scope, 'mbx-indoor-level-selected', [
            'literal',
            levelSelected
        ]);
        this._map.setConfigProperty(this._scope, 'mbx-indoor-level-overlapped', [
            'literal',
            levelOverlapped
        ]);
        if (selectedLevel) {
            this._map.setConfigProperty(this._scope, 'mbx-indoor-underground', !!selectedLevel.isUnderground);
            if (animated && selectedLevel.extent) {
                const cameraPlacement = this._map.cameraForBounds(selectedLevel.extent, {
                    pitch: this._map.getPitch(),
                    bearing: this._map.getBearing()
                });
                const currentZoom = this._map.getZoom();
                const zoomDiff = cameraPlacement.zoom ? Math.abs(currentZoom - cameraPlacement.zoom) : 0;
                if (zoomDiff >= 1) {
                    this._map.fitBounds(selectedLevel.extent, {
                        pitch: this._map.getPitch(),
                        bearing: this._map.getBearing()
                    });
                } else {
                    this._map.fitBounds(selectedLevel.extent, {
                        pitch: this._map.getPitch(),
                        bearing: this._map.getBearing(),
                        zoom: currentZoom
                    });
                }
            }
        }
    }
    //// Public functions
    // Selects a floorplan based on a provided ID, if the associated feature is visible on the screen.
    selectFloorplan(floorplanId) {
        const queryParams = {
            target: {
                featuresetId: this._queryFeatureSetId,
                importId: this._scope
            }
        };
        const wholeScreen = [
            new index.P(0, 0),
            new index.P(this._map.transform.width, this._map.transform.height)
        ];
        const features = this._map.queryRenderedFeatures(wholeScreen, queryParams);
        if (features.length > 0) {
            for (const feature of features) {
                const indoorData = JSON.parse(feature.properties['indoor-data']);
                if (indoorData.floorplanIDs.includes(floorplanId)) {
                    this._selectedFloorplan = feature;
                    this._floorplanSelected(true);
                    break;
                }
            }
        }
    }
    // Selects a building based on a provided ID.
    selectBuilding(id) {
        const selectedBuilding = this._indoorData.buildings.find(e => e.id === id);
        this._buildingSelected(selectedBuilding, true);
    }
    // Selects a level of based on a provided ID.
    selectLevel(levelId) {
        this._levelSelected(levelId);
    }
}

function getContentArea(icon) {
    if (!icon.metadata || !icon.metadata.content_area) {
        return void 0;
    }
    const dpr = index.q.devicePixelRatio;
    const {left, top, width, height} = icon.metadata.content_area;
    const scaledLeft = left * dpr;
    const scaledTop = top * dpr;
    return [
        scaledLeft,
        scaledTop,
        scaledLeft + width * dpr,
        scaledTop + height * dpr
    ];
}
function getStretchArea(stretchArea) {
    if (!stretchArea) {
        return void 0;
    }
    return stretchArea.map(([l, r]) => [
        l * index.q.devicePixelRatio,
        r * index.q.devicePixelRatio
    ]);
}
function loadIconset(loadURL, requestManager, callback) {
    return index.bi(requestManager.transformRequest(requestManager.normalizeIconsetURL(loadURL), index.R.Iconset), (err, data) => {
        if (err) {
            callback(err);
            return;
        }
        const result = {};
        const iconSet = index.cg(new index.bh(data));
        for (const icon of iconSet.icons) {
            const styleImage = {
                version: 1,
                pixelRatio: index.q.devicePixelRatio,
                content: getContentArea(icon),
                stretchX: icon.metadata ? getStretchArea(icon.metadata.stretch_x_areas) : void 0,
                stretchY: icon.metadata ? getStretchArea(icon.metadata.stretch_y_areas) : void 0,
                sdf: false,
                usvg: true,
                icon
            };
            result[icon.name] = styleImage;
        }
        callback(null, result);
    });
}

const emitValidationErrors = (evented, errors) => emitValidationErrors$1(evented, errors && errors.filter(error => error.identifier !== 'source.canvas'));
const supportedDiffOperations = index.ay(operations, [
    'addLayer',
    'removeLayer',
    'setLights',
    'setPaintProperty',
    'setLayoutProperty',
    'setSlot',
    'setFilter',
    'addSource',
    'removeSource',
    'setLayerZoomRange',
    'setLight',
    'setTransition',
    'setGeoJSONSourceData',
    'setTerrain',
    'setFog',
    'setSnow',
    'setRain',
    'setProjection',
    'setCamera',
    'addImport',
    'removeImport',
    'updateImport'    // 'setGlyphs',
                      // 'setSprite',
]);
const ignoredDiffOperations = index.ay(operations, [
    'setCenter',
    'setZoom',
    'setBearing',
    'setPitch'
]);
const featurelessLayerTypes = /* @__PURE__ */
new Set([
    'background',
    'sky',
    'slot',
    'custom'
]);
const empty = emptyStyle();
const MAX_IMPORT_DEPTH = 5;
const defaultTransition = {
    duration: 300,
    delay: 0
};
class Style extends index.E {
    constructor(map, options = {}) {
        super();
        this.map = map;
        this.scope = options.scope || '';
        this.globalId = null;
        this.fragments = [];
        this.importDepth = options.importDepth || 0;
        this.importsCache = options.importsCache || /* @__PURE__ */
        new Map();
        this.resolvedImports = options.resolvedImports || /* @__PURE__ */
        new Set();
        this.transition = index.l({}, defaultTransition);
        this._buildingIndex = new BuildingIndex(this);
        this.crossTileSymbolIndex = new CrossTileSymbolIndex();
        this._mergedOrder = [];
        this._drapedFirstOrder = [];
        this._mergedLayers = {};
        this._mergedSourceCaches = {};
        this._mergedOtherSourceCaches = {};
        this._mergedSymbolSourceCaches = {};
        this._clipLayerPresent = false;
        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 index.D(index.ci(), this);
        }
        if (options.imageManager) {
            this.imageManager = options.imageManager;
        } else {
            this.imageManager = new ImageManager(this.map._spriteFormat);
            this.imageManager.setEventedParent(this);
        }
        this.imageManager.createScope(this.scope);
        if (options.glyphManager) {
            this.glyphManager = options.glyphManager;
        } else {
            this.glyphManager = new index.cj(map._requestManager, options.localFontFamily ? index.ck.all : options.localIdeographFontFamily ? index.ck.ideographs : index.ck.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._sourceCaches = {};
        this._otherSourceCaches = {};
        this._symbolSourceCaches = {};
        this._loaded = false;
        this._precompileDone = false;
        this._shouldPrecompile = false;
        this._availableImages = [];
        this._order = [];
        this._markersNeedUpdate = false;
        this.options = options.configOptions ? options.configOptions : /* @__PURE__ */
        new Map();
        this._configDependentLayers = options.configDependentLayers ? options.configDependentLayers : /* @__PURE__ */
        new Set();
        this._config = options.config;
        this._styleColorTheme = {
            lut: null,
            lutLoading: false,
            lutLoadingCorrelationID: 0,
            colorTheme: null,
            colorThemeOverride: options.colorThemeOverride
        };
        this._styleColorThemeForScope = {};
        this._initialConfig = options.initialConfig;
        this.dispatcher.broadcast('setReferrer', index.cl());
        const self = this;
        this._rtlTextPluginCallback = Style.registerForPluginStateChange(event => {
            const state = {
                pluginStatus: event.pluginStatus,
                pluginURL: event.pluginURL
            };
            self.dispatcher.broadcast('syncRTLPluginState', state, (err, results) => {
                index.cm(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();
                            }
                        }
                    }
                }
            });
        });
        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);
                }
            }
        });
    }
    load(style) {
        if (!style) {
            return this;
        }
        if (typeof style === 'string') {
            this.loadURL(style);
        } else {
            this.loadJSON(style);
        }
        return this;
    }
    _getGlobalId(loadedStyle) {
        if (!loadedStyle) {
            return null;
        }
        if (typeof loadedStyle === 'string') {
            if (index.f(loadedStyle)) {
                return loadedStyle;
            }
            const url = index.cn(loadedStyle);
            if (!url.startsWith('http')) {
                try {
                    return new URL(url, location.href).toString();
                } catch (_e) {
                    return url;
                }
            }
            return url;
        }
        return `json://${ index.co(JSON.stringify(loadedStyle)) }`;
    }
    _diffStyle(style, onStarted, onFinished) {
        this.globalId = this._getGlobalId(style);
        const handleStyle = (json, callback) => {
            try {
                callback(null, this.setState(json, onFinished));
            } catch (e) {
                callback(e, false);
            }
        };
        if (typeof style === 'string') {
            const url = this.map._requestManager.normalizeStyleURL(style);
            const request = this.map._requestManager.transformRequest(url, index.R.Style);
            index.n(request, (error, json) => {
                if (error) {
                    this.fire(new index.y(error));
                } else if (json) {
                    handleStyle(json, onStarted);
                }
            });
        } else if (typeof style === 'object') {
            handleStyle(style, onStarted);
        }
    }
    loadURL(url, options = {}) {
        this.fire(new index.z('dataloading', { dataType: 'style' }));
        const validate = typeof options.validate === 'boolean' ? options.validate : !index.f(url);
        this.globalId = this._getGlobalId(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, index.R.Style);
        this._request = index.n(request, (error, json) => {
            this._request = null;
            if (error) {
                this.fire(new index.y(error));
            } else if (json) {
                this.importsCache.set(url, json);
                return this._load(json, validate);
            }
        });
    }
    loadJSON(json, options = {}) {
        this.fire(new index.z('dataloading', { dataType: 'style' }));
        this.globalId = this._getGlobalId(json);
        this._request = index.q.frame(() => {
            this._request = null;
            this._load(json, options.validate !== false);
        });
    }
    loadEmpty() {
        this.fire(new index.z('dataloading', { dataType: 'style' }));
        this._load(empty, false);
    }
    _loadImports(imports, validate, beforeId) {
        if (this.importDepth >= MAX_IMPORT_DEPTH - 1) {
            index.w(`Style doesn't support nesting deeper than ${ MAX_IMPORT_DEPTH }`);
            return Promise.resolve();
        }
        const waitForStyles = [];
        for (const importSpec of imports) {
            const style = this._createFragmentStyle(importSpec);
            const waitForStyle = new Promise(resolve => {
                style.once('style.import.load', resolve);
                style.once('error', resolve);
            }).then(() => this.mergeAll());
            waitForStyles.push(waitForStyle);
            if (this.resolvedImports.has(importSpec.url)) {
                style.loadEmpty();
                continue;
            }
            const json = importSpec.data || this.importsCache.get(importSpec.url);
            if (json) {
                style.loadJSON(json, { validate });
                if (this._isInternalStyle(json)) {
                    style.globalId = null;
                }
            } else if (importSpec.url) {
                style.loadURL(importSpec.url, { validate });
            } else {
                style.loadEmpty();
            }
            const fragment = {
                style,
                id: importSpec.id,
                config: importSpec.config
            };
            if (beforeId) {
                const beforeIndex = this.fragments.findIndex(({id}) => id === beforeId);
                this.fragments = this.fragments.slice(0, beforeIndex).concat(fragment).concat(this.fragments.slice(beforeIndex));
            } else {
                this.fragments.push(fragment);
            }
        }
        return Promise.allSettled(waitForStyles);
    }
    getImportGlobalIds(style = this, ids = /* @__PURE__ */
    new Set()) {
        for (const fragment of style.fragments) {
            if (fragment.style.globalId) {
                ids.add(fragment.style.globalId);
            }
            this.getImportGlobalIds(fragment.style, ids);
        }
        return [...ids.values()];
    }
    _createFragmentStyle(importSpec) {
        const scope = this.scope ? index.aC(importSpec.id, this.scope) : importSpec.id;
        let config;
        const initialConfig = this._initialConfig && this._initialConfig[scope];
        if (importSpec.config || initialConfig) {
            config = index.l({}, importSpec.config, initialConfig);
        }
        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,
            config,
            configOptions: this.options,
            colorThemeOverride: importSpec['color-theme'],
            configDependentLayers: this._configDependentLayers
        });
        style.setEventedParent(this.map, { style });
        return style;
    }
    _reloadImports() {
        this.mergeAll();
        this._updateMapProjection();
        this.updateConfigDependencies();
        this.map._triggerCameraUpdate(this.camera);
        this.dispatcher.broadcast('setLayers', {
            layers: this._serializeLayers(this._order),
            scope: this.scope,
            options: this.options
        });
        this._shouldPrecompile = this.map._precompilePrograms && this.isRootStyle();
    }
    _isInternalStyle(json) {
        return this.isRootStyle() && (json.fragment || !!json.schema && json.fragment !== false);
    }
    _load(json, validate) {
        const schema = json.indoor ? expandSchemaWithIndoor(json.schema) : json.schema;
        if (this._isInternalStyle(json)) {
            const basemap = {
                id: 'basemap',
                data: json,
                url: ''
            };
            const style = index.l({}, empty, { imports: [basemap] });
            this._load(style, validate);
            return;
        }
        this.updateConfig(this._config, schema);
        if (validate && emitValidationErrors(this, validateStyle(json))) {
            return;
        }
        this._loaded = true;
        this.stylesheet = index.cp(json);
        const proceedWithStyleLoad = () => {
            for (const id in json.sources) {
                this.addSource(id, json.sources[id], {
                    validate: false,
                    isInitialLoad: true
                });
            }
            if (json.sprite) {
                this._loadIconset(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) {
                index.w('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 = {};
            for (const layer of layers) {
                const styleLayer = index.cu(layer, this.scope, this._styleColorTheme.lut, this.options);
                if (styleLayer.configDependencies.size !== 0)
                    this._configDependentLayers.add(styleLayer.fqid);
                styleLayer.setEventedParent(this, { layer: { id: styleLayer.id } });
                this._layers[styleLayer.id] = styleLayer;
                const sourceCache = this.getOwnLayerSourceCache(styleLayer);
                const shadowsEnabled = !!this.directionalLight && this.directionalLight.shadowsEnabled();
                if (sourceCache && styleLayer.canCastShadows() && shadowsEnabled) {
                    sourceCache.castsShadows = true;
                }
            }
            if (this.stylesheet.featuresets) {
                this.setFeaturesetSelectors(this.stylesheet.featuresets);
            }
            if (this.stylesheet.models) {
                this.modelManager.addModels(this.stylesheet.models, this.scope);
            }
            const terrain = this.stylesheet.terrain;
            if (terrain) {
                this.checkCanvasFingerprintNoise();
                if (!this.disableElevatedTerrain && !this.terrainSetForDrapingOnly()) {
                    this._createTerrain(terrain, DrapeRenderMode.elevated);
                }
            }
            if (this.stylesheet.fog) {
                this._createFog(this.stylesheet.fog);
            }
            if (this.stylesheet.snow) {
                this._createSnow(this.stylesheet.snow);
            }
            if (this.stylesheet.rain) {
                this._createRain(this.stylesheet.rain);
            }
            if (this.stylesheet.transition) {
                this.setTransition(this.stylesheet.transition);
            }
            this.fire(new index.z('data', { dataType: 'style' }));
            const isRootStyle = this.isRootStyle();
            if (json.imports) {
                this._loadImports(json.imports, validate).then(() => {
                    this._reloadImports();
                    this.fire(new index.z(isRootStyle ? 'style.load' : 'style.import.load'));
                });
            } else {
                this._reloadImports();
                this.fire(new index.z(isRootStyle ? 'style.load' : 'style.import.load'));
            }
        };
        this._styleColorTheme.colorTheme = this.stylesheet['color-theme'];
        const colorTheme = this._styleColorTheme.colorThemeOverride ? this._styleColorTheme.colorThemeOverride : this._styleColorTheme.colorTheme;
        if (colorTheme) {
            const data = this._evaluateColorThemeData(colorTheme);
            this._loadColorTheme(data).then(() => {
                proceedWithStyleLoad();
            }).catch(e => {
                index.w(`Couldn't load color theme from the stylesheet: ${ e }`);
                proceedWithStyleLoad();
            });
        } else {
            this._styleColorTheme.lut = null;
            proceedWithStyleLoad();
        }
    }
    isRootStyle() {
        return this.importDepth === 0;
    }
    mergeAll() {
        let light;
        let ambientLight;
        let directionalLight;
        let terrain;
        let fog;
        let snow;
        let rain;
        let projection;
        let transition;
        let camera;
        const styleColorThemeForScope = {};
        if (this.terrain && this.terrain.scope !== this.scope) {
            delete this.terrain;
        }
        this.forEachFragmentStyle(style => {
            if (!style.stylesheet)
                return;
            if (style.light != null)
                light = style.light;
            if (style.stylesheet.lights) {
                for (const light2 of style.stylesheet.lights) {
                    if (light2.type === 'ambient' && style.ambientLight != null)
                        ambientLight = style.ambientLight;
                    if (light2.type === 'directional' && style.directionalLight != null)
                        directionalLight = style.directionalLight;
                }
            }
            terrain = this._prioritizeTerrain(terrain, style.terrain, style.stylesheet.terrain);
            if (style.stylesheet.fog && style.fog != null)
                fog = style.fog;
            if (style.stylesheet.snow && style.snow != null)
                snow = style.snow;
            if (style.stylesheet.rain && style.rain != null)
                rain = style.rain;
            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;
            styleColorThemeForScope[style.scope] = style._styleColorTheme;
        });
        this.light = light;
        this.ambientLight = ambientLight;
        this.directionalLight = directionalLight;
        this.fog = fog;
        this.snow = snow;
        this.rain = rain;
        this._styleColorThemeForScope = styleColorThemeForScope;
        if (terrain === null) {
            delete this.terrain;
        } else {
            this.terrain = terrain;
        }
        this.camera = camera || { 'camera-projection': 'perspective' };
        this.projection = projection || { name: 'mercator' };
        this.transition = index.l({}, defaultTransition, transition);
        this.mergeSources();
        this.mergeLayers();
    }
    forEachFragmentStyle(fn) {
        const traverse = style => {
            for (const fragment of style.fragments) {
                traverse(fragment.style);
            }
            fn(style);
        };
        traverse(this);
    }
    _prioritizeTerrain(prevTerrain, nextTerrain, nextTerrainSpec) {
        const prevIsDeffered = prevTerrain && prevTerrain.drapeRenderMode === DrapeRenderMode.deferred;
        const nextIsDeffered = nextTerrain && nextTerrain.drapeRenderMode === DrapeRenderMode.deferred;
        if (nextTerrainSpec === null) {
            if (nextIsDeffered)
                return nextTerrain;
            if (prevIsDeffered)
                return prevTerrain;
            return null;
        }
        if (nextTerrain != null) {
            const nextIsElevated = nextTerrain && nextTerrain.drapeRenderMode === DrapeRenderMode.elevated;
            if (!prevTerrain || prevIsDeffered || nextIsElevated)
                return nextTerrain;
        }
        return prevTerrain;
    }
    mergeTerrain() {
        let terrain;
        if (this.terrain && this.terrain.scope !== this.scope) {
            delete this.terrain;
        }
        this.forEachFragmentStyle(style => {
            terrain = this._prioritizeTerrain(terrain, style.terrain, style.stylesheet.terrain);
        });
        if (terrain === null) {
            delete this.terrain;
        } else {
            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 = index.aC(id, style.scope);
                mergedSourceCaches[fqid] = style._sourceCaches[id];
            }
            for (const id in style._otherSourceCaches) {
                const fqid = index.aC(id, style.scope);
                mergedOtherSourceCaches[fqid] = style._otherSourceCaches[id];
            }
            for (const id in style._symbolSourceCaches) {
                const fqid = index.aC(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._mergedSlots = [];
        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 = index.cq(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 = index.cq(layer.id);
                    if (slots[slotName])
                        sort(slots[slotName]);
                    this._mergedSlots.push(slotName);
                } else {
                    const fqid = index.aC(layer.id, layer.scope);
                    this._mergedOrder.push(fqid);
                    mergedLayers[fqid] = layer;
                    if (layer.is3D())
                        this._has3DLayers = true;
                    if (layer.type === 'circle')
                        this._hasCircleLayers = true;
                    if (layer.type === 'symbol')
                        this._hasSymbolLayers = true;
                    if (layer.type === 'clip')
                        this._clipLayerPresent = true;
                }
            }
        };
        sort(mergedOrder);
        this._mergedOrder.sort((layerName1, layerName2) => {
            const l1 = mergedLayers[layerName1];
            const l2 = mergedLayers[layerName2];
            if (l1.hasInitialOcclusionOpacityProperties) {
                if (l2.is3D()) {
                    return 1;
                }
                return 0;
            }
            if (l1.is3D()) {
                if (l2.hasInitialOcclusionOpacityProperties) {
                    return -1;
                }
                return 0;
            }
            return 0;
        });
        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 = index.l({}, this.stylesheet.camera, camera);
        this.camera = this.stylesheet.camera;
        return this;
    }
    _evaluateColorThemeData(theme) {
        if (!theme.data) {
            return null;
        }
        const properties = evaluateColorThemeProperties(this.scope, theme, this.options);
        return properties.get('data');
    }
    _loadColorTheme(inputData) {
        this._styleColorTheme.lutLoading = true;
        this._styleColorTheme.lutLoadingCorrelationID += 1;
        const correlationID = this._styleColorTheme.lutLoadingCorrelationID;
        return new Promise((resolve, reject) => {
            const dataURLPrefix = 'data:image/png;base64,';
            if (!inputData || inputData.length === 0) {
                this._styleColorTheme.lut = null;
                this._styleColorTheme.lutLoading = false;
                resolve();
                return;
            }
            let colorThemeData = inputData;
            if (!colorThemeData.startsWith(dataURLPrefix)) {
                colorThemeData = dataURLPrefix + colorThemeData;
            }
            const styleLutName = 'mapbox-reserved-lut';
            const lutImage = new Image();
            lutImage.src = colorThemeData;
            lutImage.onerror = () => {
                this._styleColorTheme.lutLoading = false;
                reject(new Error('Failed to load image data'));
            };
            lutImage.onload = () => {
                if (this._styleColorTheme.lutLoadingCorrelationID !== correlationID) {
                    resolve();
                    return;
                }
                this._styleColorTheme.lutLoading = false;
                const {width, height, data} = index.q.getImageData(lutImage);
                if (height > 32) {
                    reject(new Error('The height of the image must be less than or equal to 32 pixels.'));
                    return;
                }
                if (width !== height * height) {
                    reject(new Error('The width of the image must be equal to the height squared.'));
                    return;
                }
                if (this.getImage(styleLutName)) {
                    this.removeImage(styleLutName);
                }
                this.addImage(styleLutName, {
                    data: new index.r({
                        width,
                        height
                    }, data),
                    pixelRatio: 1,
                    sdf: false,
                    usvg: false,
                    version: 0
                });
                const image = this.imageManager.getImage(styleLutName, this.scope);
                if (!image) {
                    reject(new Error('Missing LUT image.'));
                } else {
                    this._styleColorTheme.lut = {
                        image: image.data,
                        data: inputData
                    };
                    resolve();
                }
            };
        });
    }
    getLut(scope) {
        const styleColorTheme = this._styleColorThemeForScope[scope];
        return styleColorTheme ? styleColorTheme.lut : null;
    }
    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) && !this.disableElevatedTerrain;
            if (!hasTerrain) {
                this.setTerrainForDraping();
            }
        } else if (this.terrainSetForDrapingOnly()) {
            this.setTerrain(null, DrapeRenderMode.deferred);
        }
    }
    _updateMapProjection() {
        if (!this.isRootStyle())
            return;
        if (!this.map._useExplicitProjection) {
            this.map._prioritizeAndUpdateProjection(null, this.projection);
        } else {
            this.applyProjectionUpdate();
        }
    }
    _loadSprite(url) {
        this._spriteRequest = loadSprite(url, this.map._requestManager, (err, images) => {
            this._spriteRequest = null;
            if (err) {
                this.fire(new index.y(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 index.z('data', { dataType: 'style' }));
        });
    }
    _loadIconset(url) {
        if (!index.f(url) && this.map._spriteFormat !== 'icon_set' || this.map._spriteFormat === 'raster') {
            this._loadSprite(url);
            return;
        }
        const isFallbackExists = this.map._spriteFormat === 'auto';
        this._spriteRequest = loadIconset(url, this.map._requestManager, (err, images) => {
            this._spriteRequest = null;
            if (err) {
                if (isFallbackExists) {
                    this._loadSprite(url);
                } else {
                    this.fire(new index.y(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 index.z('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 index.y(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.getUpdatedSourceCaches()).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;
        if (this._styleColorTheme.lutLoading)
            return false;
        for (const {style} of this.fragments) {
            if (!style.loaded())
                return false;
        }
        return true;
    }
    _serializeImports() {
        if (!this.stylesheet.imports)
            return void 0;
        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();
    }
    hasSnowTransition() {
        if (!this.snow)
            return false;
        return this.snow.hasTransition();
    }
    hasRainTransition() {
        if (!this.rain)
            return false;
        return this.rain.hasTransition();
    }
    hasTransitions() {
        if (this.hasLightTransitions()) {
            return true;
        }
        if (this.hasFogTransition()) {
            return true;
        }
        if (this.hasSnowTransition()) {
            return true;
        }
        if (this.hasRainTransition()) {
            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;
    }
    /**
   * Returns active order for when terrain or globe are enabled (when draping is enabled).
   * @param drapingEnabled {boolean} speficy if order is requested for draping enabled.
   * @private
   */
    _getOrder(drapingEnabled) {
        return drapingEnabled ? this.order : this._mergedOrder;
    }
    isLayerDraped(layer) {
        if (!this.terrain)
            return false;
        return layer.isDraped(this.getLayerSourceCache(layer));
    }
    _checkLoaded() {
        if (!this._loaded) {
            throw new Error('Style is not done loading');
        }
    }
    _checkLayer(layerId) {
        const layer = this.getOwnLayer(layerId);
        if (!layer) {
            this.fire(new index.y(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 index.y(new Error(`The source '${ sourceId }' does not exist in the map's style.`)));
            return;
        }
        return source;
    }
    precompilePrograms(layer, parameters) {
        const painter = this.map.painter;
        if (!painter) {
            return;
        }
        for (let i = layer.minzoom || DEFAULT_MIN_ZOOM; i < (layer.maxzoom || DEFAULT_MAX_ZOOM); i++) {
            const programIds = layer.getProgramIds();
            if (!programIds)
                continue;
            for (const programId of programIds) {
                const params = layer.getDefaultProgramParams(programId, parameters.zoom, this._styleColorTheme.lut);
                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);
                    }
                }
            }
        }
    }
    /**
   * 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.isDirty();
        let layersUpdated = false;
        if (this._changes.isDirty()) {
            const updatesByScope = this._changes.getLayerUpdatesByScope();
            for (const scope in updatesByScope) {
                const {updatedIds, removedIds} = updatesByScope[scope];
                if (updatedIds || removedIds) {
                    this._updateWorkerLayers(scope, updatedIds, removedIds);
                    layersUpdated = true;
                }
            }
            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);
            }
            if (this.snow) {
                this.snow.updateTransitions(parameters);
            }
            if (this.rain) {
                this.rain.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;
            sourceCache.tileCoverLift = 0;
        }
        for (const layerId of this._mergedOrder) {
            const layer = this._mergedLayers[layerId];
            layer.recalculate(parameters, this._availableImages);
            if (!layer.isHidden(parameters.zoom)) {
                const sourceCache = this.getLayerSourceCache(layer);
                if (sourceCache) {
                    sourceCache.used = true;
                    sourceCache.tileCoverLift = Math.max(sourceCache.tileCoverLift, layer.tileCoverLift());
                }
            }
            if (!this._precompileDone && this._shouldPrecompile) {
                if ('requestIdleCallback' in window) {
                    requestIdleCallback(() => {
                        this.precompilePrograms(layer, parameters);
                    });
                } else {
                    this.precompilePrograms(layer, parameters);
                }
            }
        }
        if (this._shouldPrecompile) {
            this._precompileDone = true;
        }
        if (this.terrain && layersUpdated) {
            this.mergeLayers();
        }
        for (const sourceId in sourcesUsedBefore) {
            const sourceCache = this._mergedSourceCaches[sourceId];
            if (sourcesUsedBefore[sourceId] !== sourceCache.used) {
                const source = sourceCache.getSource();
                source.fire(new index.z('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);
        }
        if (this.snow) {
            this.snow.recalculate(parameters);
        }
        if (this.rain) {
            this.rain.recalculate(parameters);
        }
        this.z = parameters.zoom;
        if (this._markersNeedUpdate) {
            this._updateMarkersOpacity();
            this._markersNeedUpdate = false;
        }
        if (changed) {
            this.fire(new index.z('data', { dataType: 'style' }));
        }
    }
    /*
   * Apply any queued image changes.
   */
    _updateTilesForChangedImages() {
        const updatedImages = this._changes.getUpdatedImages();
        if (updatedImages.length) {
            for (const name in this._sourceCaches) {
                this._sourceCaches[name].reloadTilesForDependencies([
                    'icons',
                    'patterns'
                ], updatedImages);
            }
            this._changes.resetUpdatedImages();
        }
    }
    _updateWorkerLayers(scope, updatedIds, removedIds) {
        const fragmentStyle = this.getFragmentStyle(scope);
        if (!fragmentStyle)
            return;
        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, onFinish) {
        this._checkLoaded();
        if (emitValidationErrors(this, validateStyle(nextState)))
            return false;
        nextState = index.cp(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(', ') }.`);
        }
        const changesPromises = [];
        changes.forEach(op => {
            changesPromises.push(this[op.command].apply(this, op.args));
        });
        if (onFinish) {
            Promise.all(changesPromises).then(onFinish);
        }
        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 index.y(new Error('An image with this name already exists.')));
        }
        this.imageManager.addImage(id, this.scope, image);
        this._afterImageUpdated(id);
        return this;
    }
    updateImage(id, image, performSymbolLayout = false) {
        this.imageManager.updateImage(id, this.scope, image);
        if (performSymbolLayout) {
            this._afterImageUpdated(id);
        }
    }
    getImage(id) {
        return this.imageManager.getImage(id, this.scope);
    }
    removeImage(id) {
        if (!this.getImage(id)) {
            return this.fire(new index.y(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.updateImage(id);
        this.dispatcher.broadcast('setImages', {
            scope: this.scope,
            images: this._availableImages
        });
        this.fire(new index.z('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.setDirty();
        return this;
    }
    hasModel(id) {
        return this.modelManager.hasModel(id, this.scope);
    }
    removeModel(id) {
        if (!this.hasModel(id)) {
            return this.fire(new index.y(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) !== void 0) {
            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 = index.aC(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);
        if (!options.isInitialLoad) {
            this.mergeSources();
            this._changes.setDirty();
        }
    }
    /**
   * 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 index.y(new Error(`Source "${ id }" cannot be removed while layer "${ layerId }" is using it.`)));
            }
        }
        if (this.terrain && this.terrain.scope === this.scope && this.terrain.get().source === id) {
            return this.fire(new index.y(new Error(`Source "${ id }" cannot be removed while terrain is using it.`)));
        }
        const sourceCaches = this.getOwnSourceCaches(id);
        for (const sourceCache of sourceCaches) {
            const id2 = index.cq(sourceCache.id);
            delete this._sourceCaches[id2];
            this._changes.discardSourceCacheUpdate(sourceCache.id);
            sourceCache.fire(new index.z('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.setDirty();
        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.setDirty();
    }
    /**
   * 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;
    }
    areTilesLoaded() {
        const sources = this._mergedSourceCaches;
        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;
    }
    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, getProperties$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, getProperties(), this.scope, this.options);
                }
                break;
            }
        }
        const evaluationParameters = new index.a8(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;
        }
        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').toRenderColor(null).toArray01();
        const directionalIntensity = directional.properties.get('intensity');
        const direction = directional.properties.get('direction');
        const sphericalDirection = index.cb(direction.x, direction.y, direction.z);
        const polarIntensity = 1 - sphericalDirection[2] / 90;
        const directionalBrightness = relativeLuminance(directionalColor) * directionalIntensity * polarIntensity;
        const ambientColor = ambient.properties.get('color').toRenderColor(null).toArray01();
        const ambientIntensity = ambient.properties.get('intensity');
        const ambientBrightness = relativeLuminance(ambientColor) * ambientIntensity;
        const brightness = (directionalBrightness + ambientBrightness) / 2;
        return Number(brightness.toFixed(6));
    }
    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;
    }
    /**
   * Returns the fragment style associated with the provided fragmentId.
   * If no fragmentId is provided, returns itself.
   */
    getFragmentStyle(fragmentId) {
        if (!fragmentId)
            return this;
        if (index.cr(fragmentId)) {
            const scope = index.cs(fragmentId);
            const fragment = this.fragments.find(({id}) => id === scope);
            if (!fragment)
                throw new Error(`Style import '${ fragmentId }' not found`);
            const name = index.cq(fragmentId);
            return fragment.style.getFragmentStyle(name);
        } else {
            const fragment = this.fragments.find(({id}) => id === fragmentId);
            return fragment ? fragment.style : void 0;
        }
    }
    setFeaturesetSelectors(featuresets) {
        if (!featuresets)
            return;
        const sourceInfoMap = {};
        const createKey = (sourceId, sourcelayerId = '') => `${ sourceId }::${ sourcelayerId }`;
        this._featuresetSelectors = {};
        for (const featuresetId in featuresets) {
            const featuresetSelectors = this._featuresetSelectors[featuresetId] = [];
            for (const selector of featuresets[featuresetId].selectors) {
                if (selector.featureNamespace) {
                    const layer = this.getOwnLayer(selector.layer);
                    if (!layer) {
                        index.w(`Layer is undefined for selector: ${ selector.layer }`);
                        continue;
                    }
                    const sourceKey = createKey(layer.source, layer.sourceLayer);
                    if (sourceKey in sourceInfoMap && sourceInfoMap[sourceKey] !== selector.featureNamespace) {
                        index.w(`"featureNamespace ${ selector.featureNamespace } of featureset ${ featuresetId }'s selector is not associated to the same source, skip this selector`);
                        continue;
                    }
                    sourceInfoMap[sourceKey] = selector.featureNamespace;
                }
                let properties;
                if (selector.properties) {
                    for (const name in selector.properties) {
                        const expression = index.U(selector.properties[name]);
                        if (expression.result === 'success') {
                            properties = properties || {};
                            properties[name] = expression.value;
                        }
                    }
                }
                featuresetSelectors.push({
                    layerId: selector.layer,
                    namespace: selector.featureNamespace,
                    properties,
                    uniqueFeatureID: selector._uniqueFeatureID
                });
            }
        }
    }
    /**
   * Returns the featureset descriptors associated with a style fragment.
   * If no fragmentId is provided, returns own featureset descriptors.
   */
    getFeaturesetDescriptors(fragmentId) {
        const style = this.getFragmentStyle(fragmentId);
        if (!style || !style.stylesheet.featuresets)
            return [];
        const featuresetDescriptors = [];
        for (const id in style.stylesheet.featuresets) {
            featuresetDescriptors.push({
                featuresetId: id,
                importId: style.scope ? style.scope : void 0
            });
        }
        return featuresetDescriptors;
    }
    /**
   * Returns the layers associated with a featureset in the style fragment.
   * If no fragmentId is provided, returns the layers associated with own featuresets.
   */
    getFeaturesetLayers(featuresetId, fragmentId) {
        const style = this.getFragmentStyle(fragmentId);
        const featuresets = style.stylesheet.featuresets;
        if (!featuresets || !featuresets[featuresetId]) {
            this.fire(new index.y(new Error(`The featureset '${ featuresetId }' does not exist in the map's style and cannot be queried.`)));
            return [];
        }
        const layers = [];
        for (const selector of featuresets[featuresetId].selectors) {
            const layer = style.getOwnLayer(selector.layer);
            if (layer)
                layers.push(layer);
        }
        return layers;
    }
    getConfigProperty(fragmentId, key) {
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        if (!fragmentStyle)
            return null;
        const fqid = index.aC(key, fragmentStyle.scope);
        const expressions = fragmentStyle.options.get(fqid);
        const expression = expressions ? expressions.value || expressions.default : null;
        return expression ? expression.serialize() : null;
    }
    setConfigProperty(fragmentId, key, value) {
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        if (!fragmentStyle)
            return;
        const schema = fragmentStyle.stylesheet.indoor ? expandSchemaWithIndoor(fragmentStyle.stylesheet.schema) : fragmentStyle.stylesheet.schema;
        if (!schema || !schema[key])
            return;
        const expressionParsed = index.U(value);
        if (expressionParsed.result !== 'success') {
            emitValidationErrors(this, expressionParsed.value);
            return;
        }
        const expression = expressionParsed.value.expression;
        const fqid = index.aC(key, fragmentStyle.scope);
        const expressions = fragmentStyle.options.get(fqid);
        if (!expressions)
            return;
        let defaultExpression;
        const {minValue, maxValue, stepValue, type, values} = schema[key];
        const defaultExpressionParsed = index.U(schema[key].default);
        if (defaultExpressionParsed.result === 'success') {
            defaultExpression = defaultExpressionParsed.value.expression;
        }
        if (!defaultExpression) {
            this.fire(new index.y(new Error(`No schema defined for the config option "${ key }" in the "${ fragmentId }" fragment.`)));
            return;
        }
        this.options.set(fqid, Object.assign({}, expressions, {
            value: expression,
            default: defaultExpression,
            minValue,
            maxValue,
            stepValue,
            type,
            values
        }));
        this.updateConfigDependencies(key);
    }
    getConfig(fragmentId) {
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        if (!fragmentStyle)
            return null;
        const schema = fragmentStyle.stylesheet.schema;
        if (!schema)
            return null;
        const config = {};
        for (const key in schema) {
            const fqid = index.aC(key, fragmentStyle.scope);
            const expressions = fragmentStyle.options.get(fqid);
            const expression = expressions ? expressions.value || expressions.default : null;
            config[key] = expression ? expression.serialize() : null;
        }
        return config;
    }
    setConfig(fragmentId, config) {
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        if (!fragmentStyle)
            return;
        const schema = fragmentStyle.stylesheet.schema;
        fragmentStyle.updateConfig(config, schema);
        this.updateConfigDependencies();
    }
    getSchema(fragmentId) {
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        if (!fragmentStyle)
            return null;
        return fragmentStyle.stylesheet.schema;
    }
    setSchema(fragmentId, schema) {
        const fragmentStyle = this.getFragmentStyle(fragmentId);
        if (!fragmentStyle)
            return;
        fragmentStyle.stylesheet.schema = schema;
        fragmentStyle.updateConfig(fragmentStyle._config, schema);
        this.updateConfigDependencies();
    }
    updateConfig(config, schema) {
        this._config = config;
        if (!config && !schema)
            return;
        if (!schema) {
            this.fire(new index.y(new Error(`Attempting to set config for a style without schema.`)));
            return;
        }
        for (const id in schema) {
            let defaultExpression;
            let configExpression;
            const expression = schema[id].default;
            const expressionParsed = index.U(expression);
            if (expressionParsed.result === 'success') {
                defaultExpression = expressionParsed.value.expression;
            }
            if (config && config[id] !== void 0) {
                const expressionParsed2 = index.U(config[id]);
                if (expressionParsed2.result === 'success') {
                    configExpression = expressionParsed2.value.expression;
                }
            }
            const {minValue, maxValue, stepValue, type, values} = schema[id];
            if (defaultExpression) {
                const fqid = index.aC(id, this.scope);
                this.options.set(fqid, {
                    default: defaultExpression,
                    value: configExpression,
                    minValue,
                    maxValue,
                    stepValue,
                    type,
                    values
                });
            } else {
                this.fire(new index.y(new Error(`No schema defined for config option "${ id }".`)));
            }
        }
    }
    updateConfigDependencies(configKey) {
        for (const id of this._configDependentLayers) {
            const layer = this.getLayer(id);
            if (layer) {
                if (configKey && !layer.configDependencies.has(configKey)) {
                    continue;
                }
                layer.possiblyEvaluateVisibility();
                this._updateLayer(layer);
            }
        }
        if (this.ambientLight) {
            this.ambientLight.updateConfig(this.options);
        }
        if (this.directionalLight) {
            this.directionalLight.updateConfig(this.options);
        }
        if (this.fog) {
            this.fog.updateConfig(this.options);
        }
        if (this.snow) {
            this.snow.updateConfig(this.options);
        }
        if (this.rain) {
            this.rain.updateConfig(this.options);
        }
        this.forEachFragmentStyle(style => {
            const colorTheme = style._styleColorTheme.colorThemeOverride ? style._styleColorTheme.colorThemeOverride : style._styleColorTheme.colorTheme;
            if (colorTheme) {
                const data = style._evaluateColorThemeData(colorTheme);
                if (!style._styleColorTheme.lut && data !== '' || style._styleColorTheme.lut && data !== style._styleColorTheme.lut.data) {
                    style.setColorTheme(colorTheme);
                }
            }
        });
        this._changes.setDirty();
    }
    /**
   * 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 index.y(new Error(`Layer with id "${ id }" already exists on this map`)));
            return;
        }
        let layer;
        if (layerObject.type === 'custom') {
            if (emitValidationErrors(this, index.ct(layerObject)))
                return;
            layer = index.cu(layerObject, this.scope, this._styleColorTheme.lut, this.options);
        } else {
            if (typeof layerObject.source === 'object') {
                this.addSource(id, layerObject.source);
                layerObject = index.cp(layerObject);
                layerObject = index.l(layerObject, { source: id });
            }
            if (this._validate(validateLayer, `layers.${ id }`, layerObject, { arrayIndex: -1 }, options))
                return;
            layer = index.cu(layerObject, this.scope, this._styleColorTheme.lut, this.options);
            this._validateLayer(layer);
            layer.setEventedParent(this, { layer: { id } });
        }
        if (layer.configDependencies.size !== 0)
            this._configDependentLayers.add(layer.fqid);
        let index$1 = this._order.length;
        if (before) {
            const beforeIndex = this._order.indexOf(before);
            if (beforeIndex === -1) {
                this.fire(new index.y(new Error(`Layer with id "${ before }" does not exist on this map.`)));
                return;
            }
            const beforeLayer = this._layers[before];
            if (layer.slot === beforeLayer.slot)
                index$1 = beforeIndex;
            else
                index.w(`Layer with id "${ before }" has a different slot. Layers can only be rearranged within the same slot.`);
        }
        this._order.splice(index$1, 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') {
            this._changes.discardLayerRemoval(layer);
            const fqid = index.aC(layer.source, layer.scope);
            if (removedLayer.type !== layer.type) {
                this._changes.updateSourceCache(fqid, 'clear');
            } else {
                this._changes.updateSourceCache(fqid, 'reload');
                sourceCache.pause();
            }
        }
        this._updateLayer(layer);
        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();
        const layer = this._checkLayer(id);
        if (!layer)
            return;
        if (id === before) {
            return;
        }
        const index$1 = this._order.indexOf(id);
        this._order.splice(index$1, 1);
        let newIndex = this._order.length;
        if (before) {
            const beforeIndex = this._order.indexOf(before);
            if (beforeIndex === -1) {
                this.fire(new index.y(new Error(`Layer with id "${ before }" does not exist on this map.`)));
                return;
            }
            const beforeLayer = this._layers[before];
            if (layer.slot === beforeLayer.slot)
                newIndex = beforeIndex;
            else
                index.w(`Layer with id "${ before }" has a different slot. Layers can only be rearranged within the same slot.`);
        }
        this._order.splice(newIndex, 0, id);
        this._changes.setDirty();
        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];
        this._changes.setDirty();
        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);
    }
    getSlots() {
        this._checkLoaded();
        return this._mergedSlots;
    }
    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 (index.bn(layer.filter, filter)) {
            return;
        }
        if (filter === null || filter === void 0) {
            layer.filter = void 0;
            this._updateLayer(layer);
            return;
        }
        if (this._validate(validateFilter, `layers.${ layer.id }.filter`, filter, { layerType: layer.type }, options)) {
            return;
        }
        layer.filter = index.cp(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 index.cp(layer.filter);
    }
    setLayoutProperty(layerId, name, value, options = {}) {
        this._checkLoaded();
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        if (index.bn(layer.getLayoutProperty(name), value))
            return;
        if (value !== null && value !== void 0 && !(options && options.validate === false)) {
            const key = `layers.${ layerId }.layout.${ name }`;
            const errors = emitValidationErrors(layer, validateLayoutProperty.call(validateStyle, {
                key,
                layerType: layer.type,
                objectKey: name,
                value,
                styleSpec: index.a3,
                // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407
                style: {
                    glyphs: true,
                    sprite: true
                }
            }));
            if (errors) {
                return;
            }
        }
        layer.setLayoutProperty(name, value);
        if (layer.configDependencies.size !== 0)
            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 (index.bn(layer.getPaintProperty(name), value))
            return;
        if (value !== null && value !== void 0 && !(options && options.validate === false)) {
            const key = `layers.${ layerId }.paint.${ name }`;
            const errors = emitValidationErrors(layer, validatePaintProperty.call(validateStyle, {
                key,
                layerType: layer.type,
                objectKey: name,
                value,
                styleSpec: index.a3
            }));
            if (errors) {
                return;
            }
        }
        const requiresRelayout = layer.setPaintProperty(name, value);
        if (layer.configDependencies.size !== 0)
            this._configDependentLayers.add(layer.fqid);
        if (requiresRelayout) {
            this._updateLayer(layer);
        }
        this._changes.updatePaintProperties(layer);
    }
    getPaintProperty(layerId, name) {
        const layer = this._checkLayer(layerId);
        if (!layer)
            return;
        return layer.getPaintProperty(name);
    }
    setFeatureState(target, state) {
        this._checkLoaded();
        if ('target' in target) {
            if ('featuresetId' in target.target) {
                const {featuresetId, importId} = target.target;
                const fragment = this.getFragmentStyle(importId);
                const layers = fragment.getFeaturesetLayers(featuresetId);
                for (const {
                            source: source2,
                            sourceLayer: sourceLayer2
                        } of layers) {
                    fragment.setFeatureState({
                        id: target.id,
                        source: source2,
                        sourceLayer: sourceLayer2
                    }, state);
                }
            } else if ('layerId' in target.target) {
                const {layerId} = target.target;
                const layer = this.getLayer(layerId);
                this.setFeatureState({
                    id: target.id,
                    source: layer.source,
                    sourceLayer: layer.sourceLayer
                }, state);
            }
            return;
        }
        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 index.y(new Error(`GeoJSON sources cannot have a sourceLayer parameter.`)));
            return;
        }
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new index.y(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
            return;
        }
        if (target.id === void 0) {
            this.fire(new index.y(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();
        if ('target' in target) {
            if ('featuresetId' in target.target) {
                const {featuresetId, importId} = target.target;
                const fragment = this.getFragmentStyle(importId);
                const layers = fragment.getFeaturesetLayers(featuresetId);
                for (const {
                            source: source2,
                            sourceLayer: sourceLayer2
                        } of layers) {
                    fragment.removeFeatureState({
                        id: target.id,
                        source: source2,
                        sourceLayer: sourceLayer2
                    }, key);
                }
            } else if ('layerId' in target.target) {
                const {layerId} = target.target;
                const layer = this.getLayer(layerId);
                this.removeFeatureState({
                    id: target.id,
                    source: layer.source,
                    sourceLayer: layer.sourceLayer
                }, key);
            }
            return;
        }
        const sourceId = target.source;
        const source = this._checkSource(sourceId);
        if (!source)
            return;
        const sourceType = source.type;
        const sourceLayer = sourceType === 'vector' ? target.sourceLayer : void 0;
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new index.y(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 index.y(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();
        if ('target' in target) {
            let finalState;
            if ('featuresetId' in target.target) {
                const {featuresetId, importId} = target.target;
                const fragment = this.getFragmentStyle(importId);
                const layers = fragment.getFeaturesetLayers(featuresetId);
                for (const {
                            source: source2,
                            sourceLayer: sourceLayer2
                        } of layers) {
                    const state = fragment.getFeatureState({
                        id: target.id,
                        source: source2,
                        sourceLayer: sourceLayer2
                    });
                    if (state && !finalState) {
                        finalState = state;
                    } else if (!index.bn(finalState, state)) {
                        this.fire(new index.y(new Error(`The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.`)));
                        return;
                    }
                }
            } else if ('layerId' in target.target) {
                const {layerId} = target.target;
                const layer = this.getLayer(layerId);
                finalState = this.getFeatureState({
                    id: target.id,
                    source: layer.source,
                    sourceLayer: layer.sourceLayer
                });
            }
            return finalState;
        }
        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 index.y(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
            return;
        }
        if (target.id === void 0) {
            this.fire(new index.y(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 = index.l({}, this.stylesheet.transition, transition);
        this.transition = this.stylesheet.transition;
        return this;
    }
    getTransition() {
        return index.l({}, this.stylesheet.transition);
    }
    serialize() {
        this._checkLoaded();
        const terrain = this.getTerrain();
        const scopedTerrain = terrain && this.terrain && this.terrain.scope === this.scope ? terrain : this.stylesheet.terrain;
        return index.cv({
            version: this.stylesheet.version,
            name: this.stylesheet.name,
            metadata: this.stylesheet.metadata,
            fragment: this.stylesheet.fragment,
            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,
            snow: this.stylesheet.snow,
            rain: this.stylesheet.rain,
            center: this.stylesheet.center,
            'color-theme': this.stylesheet['color-theme'],
            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 !== void 0;
        });
    }
    _updateFilteredLayers(filter) {
        for (const layer of Object.values(this._mergedLayers)) {
            if (filter(layer)) {
                this._updateLayer(layer);
            }
        }
    }
    _updateLayer(layer) {
        this._changes.updateLayer(layer);
        const sourceCache = this.getLayerSourceCache(layer);
        const fqid = index.aC(layer.source, layer.scope);
        const sourceCacheUpdates = this._changes.getUpdatedSourceCaches();
        if (layer.source && !sourceCacheUpdates[fqid] && // Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865)
            sourceCache && sourceCache.getSource().type !== 'raster') {
            this._changes.updateSourceCache(fqid, 'reload');
            sourceCache.pause();
        }
        layer.invalidateCompiledFilter();
    }
    _flattenAndSortRenderedFeatures(sourceResults) {
        const isLayer3D = layerId => this._mergedLayers[layerId].is3D();
        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)) {
                for (let i = features3D.length - 1; i >= 0; i--) {
                    const topmost3D = features3D[i].feature;
                    if (topmost3D.layer && 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) {
        let filter;
        if (params && !Array.isArray(params) && params.filter) {
            this._validate(validateFilter, 'queryRenderedFeatures.filter', params.filter, null, params);
            filter = index.aZ(params.filter);
        }
        const queries = {};
        const addLayerToQuery = styleLayer => {
            if (featurelessLayerTypes.has(styleLayer.type))
                return;
            const sourceCache = this.getOwnLayerSourceCache(styleLayer);
            const querySourceCache = queries[sourceCache.id] = queries[sourceCache.id] || {
                sourceCache,
                layers: {},
                has3DLayers: false
            };
            if (styleLayer.is3D())
                querySourceCache.has3DLayers = true;
            querySourceCache.layers[styleLayer.fqid] = querySourceCache.layers[styleLayer.fqid] || {
                styleLayer,
                targets: []
            };
            querySourceCache.layers[styleLayer.fqid].targets.push({ filter });
        };
        if (params && params.layers) {
            if (!Array.isArray(params.layers)) {
                this.fire(new index.y(new Error('parameters.layers must be an Array.')));
                return [];
            }
            for (const layerId of params.layers) {
                const styleLayer = this._layers[layerId];
                if (!styleLayer) {
                    this.fire(new index.y(new Error(`The layer '${ layerId }' does not exist in the map's style and cannot be queried for features.`)));
                    return [];
                }
                addLayerToQuery(styleLayer);
            }
        } else {
            for (const layerId in this._layers) {
                addLayerToQuery(this._layers[layerId]);
            }
        }
        const renderedFeatures = this._queryRenderedFeatures(queryGeometry, queries, transform);
        const sortedFeatures = this._flattenAndSortRenderedFeatures(renderedFeatures);
        const features = [];
        for (const feature of sortedFeatures) {
            const scope = index.cs(feature.layer.id);
            if (scope === this.scope)
                features.push(feature);
        }
        return features;
    }
    queryRenderedFeatureset(queryGeometry, params, transform) {
        let filter;
        if (params && !Array.isArray(params) && params.filter) {
            this._validate(validateFilter, 'queryRenderedFeatures.filter', params.filter, null, params);
            filter = index.aZ(params.filter);
        }
        const targetId = 'mock';
        const targets = [];
        if (params && params.target) {
            targets.push(Object.assign({}, params, {
                targetId,
                filter
            }));
        } else {
            const featuresetDescriptors = this.getFeaturesetDescriptors();
            for (const featureset of featuresetDescriptors) {
                targets.push({
                    targetId,
                    filter,
                    target: featureset
                });
            }
            for (const {style} of this.fragments) {
                const featuresetDescriptors2 = style.getFeaturesetDescriptors();
                for (const featureset of featuresetDescriptors2) {
                    targets.push({
                        targetId,
                        filter,
                        target: featureset
                    });
                }
            }
        }
        const features = this.queryRenderedTargets(queryGeometry, targets, transform);
        const targetFeatures = [];
        const uniqueFeatureSet = /* @__PURE__ */
        new Set();
        for (const feature of features) {
            for (const variant of feature.variants[targetId]) {
                if (shouldSkipFeatureVariant(variant, feature, uniqueFeatureSet)) {
                    continue;
                }
                targetFeatures.push(new index.cw(feature, variant));
            }
        }
        return targetFeatures;
    }
    queryRenderedTargets(queryGeometry, targets, transform) {
        const queries = {};
        const addLayerToQuery = (styleLayer, sourceCache, target, selector) => {
            const querySourceCache = queries[sourceCache.id] = queries[sourceCache.id] || {
                sourceCache,
                layers: {},
                has3DLayers: false
            };
            querySourceCache.layers[styleLayer.fqid] = querySourceCache.layers[styleLayer.fqid] || {
                styleLayer,
                targets: []
            };
            if (styleLayer.is3D())
                querySourceCache.has3DLayers = true;
            if (!selector) {
                target.uniqueFeatureID = false;
                querySourceCache.layers[styleLayer.fqid].targets.push(target);
                return;
            }
            querySourceCache.layers[styleLayer.fqid].targets.push(Object.assign({}, target, {
                namespace: selector.namespace,
                properties: selector.properties,
                uniqueFeatureID: selector.uniqueFeatureID
            }));
        };
        for (const target of targets) {
            if ('featuresetId' in target.target) {
                const {featuresetId, importId} = target.target;
                const style = this.getFragmentStyle(importId);
                if (!style || !style._featuresetSelectors)
                    continue;
                const selectors = style._featuresetSelectors[featuresetId];
                if (!selectors) {
                    this.fire(new index.y(new Error(`The featureset '${ featuresetId }' does not exist in the map's style and cannot be queried for features.`)));
                    continue;
                }
                for (const selector of selectors) {
                    const styleLayer = style.getOwnLayer(selector.layerId);
                    if (!styleLayer || featurelessLayerTypes.has(styleLayer.type))
                        continue;
                    const sourceCache = style.getOwnLayerSourceCache(styleLayer);
                    addLayerToQuery(styleLayer, sourceCache, target, selector);
                }
            } else if ('layerId' in target.target) {
                const {layerId} = target.target;
                const styleLayer = this.getLayer(layerId);
                if (!styleLayer || featurelessLayerTypes.has(styleLayer.type))
                    continue;
                const sourceCache = this.getLayerSourceCache(styleLayer);
                addLayerToQuery(styleLayer, sourceCache, target);
            }
        }
        const renderedFeatures = this._queryRenderedFeatures(queryGeometry, queries, transform);
        const sortedFeatures = this._flattenAndSortRenderedFeatures(renderedFeatures);
        return sortedFeatures;
    }
    _queryRenderedFeatures(queryGeometry, queries, transform) {
        const queryResults = [];
        const showQueryGeometry = !!this.map._showQueryGeometry;
        const queryGeometryStruct = QueryGeometry.createFromScreenPoints(queryGeometry, transform);
        for (const sourceCacheId in queries) {
            const queryResult = queryRenderedFeatures(queryGeometryStruct, queries[sourceCacheId], this._availableImages, transform, showQueryGeometry);
            if (Object.keys(queryResult).length)
                queryResults.push(queryResult);
        }
        if (this.placement) {
            for (const sourceCacheId in queries) {
                if (!queries[sourceCacheId].sourceCache._onlySymbols)
                    continue;
                const queryResult = queryRenderedSymbols(queryGeometryStruct.screenGeometry, queries[sourceCacheId], this._availableImages, this.placement.collisionIndex, this.placement.retainedQueryData);
                if (Object.keys(queryResult).length)
                    queryResults.push(queryResult);
            }
        }
        return queryResults;
    }
    querySourceFeatures(sourceId, params) {
        const filter = params && params.filter;
        if (filter) {
            this._validate(validateFilter, 'querySourceFeatures.filter', filter, null, params);
        }
        let results = [];
        const sourceCaches = this.getOwnSourceCaches(sourceId);
        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 (!index.bn(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);
    }
    checkCanvasFingerprintNoise() {
        if (this.disableElevatedTerrain === void 0) {
            this.disableElevatedTerrain = index.q.hasCanvasFingerprintNoise();
            if (this.disableElevatedTerrain)
                index.w('Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode).');
        }
    }
    // 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();
        if (!terrainOptions) {
            if (!this.terrainSetForDrapingOnly()) {
                delete this.terrain;
                if (this.map.transform.projection.requiresDraping) {
                    this.setTerrainForDraping();
                }
            }
            if (drapeRenderMode === DrapeRenderMode.deferred) {
                delete this.terrain;
            }
            if (terrainOptions === null) {
                this.stylesheet.terrain = null;
            } else {
                delete this.stylesheet.terrain;
            }
            this._force3DLayerUpdate();
            this._markersNeedUpdate = true;
            return;
        }
        this.checkCanvasFingerprintNoise();
        let options = terrainOptions;
        const isUpdating = terrainOptions.source == null;
        if (drapeRenderMode === DrapeRenderMode.elevated) {
            if (this.disableElevatedTerrain)
                return;
            if (typeof options.source === 'object') {
                const id = 'terrain-dem-src';
                this.addSource(id, options.source);
                options = index.cp(options);
                options = index.l(options, { source: id });
            }
            const validationOptions = index.l({}, options);
            const validationProps = {};
            if (this.terrain && isUpdating) {
                validationOptions.source = this.terrain.get().source;
                const fragmentStyle = this.terrain ? this.getFragmentStyle(this.terrain.scope) : null;
                if (fragmentStyle) {
                    validationProps.style = fragmentStyle.serialize();
                }
            }
            if (this._validate(validateTerrain, 'terrain', validationOptions, validationProps)) {
                return;
            }
        }
        if (!this.terrain || this.terrain.scope !== this.scope && !isUpdating || this.terrain && drapeRenderMode !== this.terrain.drapeRenderMode) {
            if (!options)
                return;
            this._createTerrain(options, drapeRenderMode);
            this.fire(new index.z('data', { dataType: 'style' }));
        } else {
            const terrain = this.terrain;
            const currSpec = terrain.get();
            for (const name of Object.keys(index.a3.terrain)) {
                if (!options.hasOwnProperty(name) && !!index.a3.terrain[name].default) {
                    options[name] = index.a3.terrain[name].default;
                }
            }
            for (const key in terrainOptions) {
                if (!index.bn(terrainOptions[key], currSpec[key])) {
                    terrain.set(terrainOptions, this.options);
                    this.stylesheet.terrain = terrainOptions;
                    const parameters = this._getTransitionParameters({ duration: 0 });
                    terrain.updateTransitions(parameters);
                    this.fire(new index.z('data', { dataType: 'style' }));
                    break;
                }
            }
        }
        this.mergeTerrain();
        this.updateDrapeFirstLayers();
        this._markersNeedUpdate = true;
    }
    _createFog(fogOptions) {
        const fog = this.fog = new Fog(fogOptions, this.map.transform, this.scope, this.options);
        this.stylesheet.fog = fog.get();
        const parameters = this._getTransitionParameters({ duration: 0 });
        fog.updateTransitions(parameters);
    }
    _createSnow(snowOptions) {
        const snow = this.snow = new Snow$1(snowOptions, this.map.transform, this.scope, this.options);
        this.stylesheet.snow = snow.get();
        const parameters = this._getTransitionParameters({ duration: 0 });
        snow.updateTransitions(parameters);
    }
    _createRain(rainOptions) {
        const rain = this.rain = new Rain$1(rainOptions, this.map.transform, this.scope, this.options);
        this.stylesheet.rain = rain.get();
        const parameters = this._getTransitionParameters({ duration: 0 });
        rain.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) {
            delete this.fog;
            delete this.stylesheet.fog;
            this._markersNeedUpdate = true;
            return;
        }
        if (!this.fog) {
            this._createFog(fogOptions);
        } else {
            const fog = this.fog;
            if (!index.bn(fog.get(), fogOptions)) {
                fog.set(fogOptions, this.options);
                this.stylesheet.fog = fog.get();
                const parameters = this._getTransitionParameters({ duration: 0 });
                fog.updateTransitions(parameters);
            }
        }
        this._markersNeedUpdate = true;
    }
    getSnow() {
        return this.snow ? this.snow.get() : null;
    }
    setSnow(snowOptions) {
        this._checkLoaded();
        if (!snowOptions) {
            delete this.snow;
            delete this.stylesheet.snow;
            return;
        }
        if (!this.snow) {
            this._createSnow(snowOptions);
        } else {
            const snow = this.snow;
            if (!index.bn(snow.get(), snowOptions)) {
                snow.set(snowOptions, this.options);
                this.stylesheet.snow = snow.get();
                const parameters = this._getTransitionParameters({ duration: 0 });
                snow.updateTransitions(parameters);
            }
        }
        this._markersNeedUpdate = true;
    }
    getRain() {
        return this.rain ? this.rain.get() : null;
    }
    setRain(rainOptions) {
        this._checkLoaded();
        if (!rainOptions) {
            delete this.rain;
            delete this.stylesheet.rain;
            return;
        }
        if (!this.rain) {
            this._createRain(rainOptions);
        } else {
            const rain = this.rain;
            if (!index.bn(rain.get(), rainOptions)) {
                rain.set(rainOptions, this.options);
                this.stylesheet.rain = rain.get();
                const parameters = this._getTransitionParameters({ duration: 0 });
                rain.updateTransitions(parameters);
            }
        }
        this._markersNeedUpdate = true;
    }
    _reloadColorTheme() {
        const updateStyle = () => {
            for (const layerId in this._layers) {
                const layer = this._layers[layerId];
                layer.lut = this._styleColorTheme.lut;
            }
            for (const id in this._sourceCaches) {
                this._sourceCaches[id].clearTiles();
            }
        };
        const colorTheme = this._styleColorTheme.colorThemeOverride ? this._styleColorTheme.colorThemeOverride : this._styleColorTheme.colorTheme;
        if (!colorTheme) {
            this._styleColorTheme.lut = null;
            updateStyle();
            return;
        }
        const data = this._evaluateColorThemeData(colorTheme);
        this._loadColorTheme(data).then(() => {
            this.fire(new index.z('colorthemeset'));
            updateStyle();
        }).catch(e => {
            index.w(`Couldn't set color theme: ${ e }`);
        });
    }
    setColorTheme(colorTheme) {
        this._checkLoaded();
        if (this._styleColorTheme.colorThemeOverride) {
            index.w(`Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible.`);
        }
        this._styleColorTheme.colorTheme = colorTheme;
        this._reloadColorTheme();
    }
    setImportColorTheme(importId, colorTheme) {
        const fragmentStyle = this.getFragmentStyle(importId);
        if (!fragmentStyle)
            return;
        fragmentStyle._styleColorTheme.colorThemeOverride = colorTheme;
        fragmentStyle._reloadColorTheme();
    }
    _getTransitionParameters(transition) {
        return {
            now: index.q.now(),
            transition: index.l(this.transition, transition)
        };
    }
    updateDrapeFirstLayers() {
        if (!this.terrain) {
            return;
        }
        const draped = [];
        const nonDraped = [];
        for (const layerId of this._mergedOrder) {
            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, this.scope, this.options);
        if (drapeRenderMode === DrapeRenderMode.elevated) {
            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;
        }
        const style = index.l({}, this.serialize());
        return emitValidationErrors(this, validate.call(validateStyle, index.l({
            key,
            style,
            value,
            styleSpec: index.a3
        }, props)));
    }
    _remove() {
        if (this._request) {
            this._request.cancel();
            this._request = null;
        }
        if (this._spriteRequest) {
            this._spriteRequest.cancel();
            this._spriteRequest = null;
        }
        index.cx.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.snow;
        delete this.rain;
        delete this.terrain;
        delete this.ambientLight;
        delete this.directionalLight;
        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();
        }
    }
    reloadSources() {
        for (const source of this.getSources()) {
            if (source.reload)
                source.reload();
        }
    }
    reloadModels() {
        this.modelManager.reloadModels('');
        this.forEachFragmentStyle(style => {
            style.modelManager.reloadModels(style.scope);
        });
    }
    updateSources(transform) {
        let lightDirection;
        if (this.directionalLight) {
            lightDirection = shadowDirectionFromProperties(this.directionalLight);
        }
        for (const id in this._mergedSourceCaches) {
            this._mergedSourceCaches[id].update(transform, void 0, void 0, lightDirection);
        }
    }
    _generateCollisionBoxes() {
        for (const id in this._sourceCaches) {
            const sourceCache = this._sourceCaches[id];
            sourceCache.resume();
            sourceCache.reload();
        }
    }
    _updatePlacement(painter, transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, replacementSource, 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 = index.aC(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);
        forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0;
        if (this._layerOrderChanged) {
            this.fire(new index.z('neworder'));
        }
        if (forceFullPlacement || !this.pauseablePlacement || this.pauseablePlacement.isDone() && !this.placement.stillRecent(index.q.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()) {
            this.placement.setStale();
        } else {
            this.pauseablePlacement.continuePlacement(this._mergedOrder, this._mergedLayers, layerTiles, layerTilesInYOrder, this.map.painter.scaleFactor);
            if (this.pauseablePlacement.isDone()) {
                this.placement = this.pauseablePlacement.commit(index.q.now());
                placementCommitted = true;
            }
            if (symbolBucketsChanged) {
                this.pauseablePlacement.placement.setStale();
            }
        }
        if (placementCommitted || symbolBucketsChanged) {
            this._buildingIndex.onNewFrame(transform.zoom);
            for (let i = 0; i < this._mergedOrder.length; i++) {
                const layerId = this._mergedOrder[i];
                const styleLayer = this._mergedLayers[layerId];
                if (styleLayer.type !== 'symbol')
                    continue;
                const checkAgainstClipLayer = this.isLayerClipped(styleLayer);
                this.placement.updateLayerOpacities(styleLayer, layerTiles[index.aC(styleLayer.source, styleLayer.scope)], i, checkAgainstClipLayer ? replacementSource : null);
            }
        }
        const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(index.q.now());
        return { needsRerender };
    }
    _releaseSymbolFadeTiles() {
        for (const id in this._sourceCaches) {
            this._sourceCaches[id].releaseSymbolFadeTiles();
        }
    }
    // Fragments and merging
    addImport(importSpec, beforeId) {
        this._checkLoaded();
        const imports = this.stylesheet.imports = this.stylesheet.imports || [];
        const index$1 = imports.findIndex(({id}) => id === importSpec.id);
        if (index$1 !== -1) {
            this.fire(new index.y(new Error(`Import with id '${ importSpec.id }' already exists in the map's style.`)));
            return;
        }
        if (!beforeId) {
            imports.push(importSpec);
            return this._loadImports([importSpec], true);
        }
        const beforeIndex = imports.findIndex(({id}) => id === beforeId);
        if (beforeIndex === -1) {
            this.fire(new index.y(new Error(`Import with id "${ beforeId }" does not exist on this map.`)));
        }
        this.stylesheet.imports = imports.slice(0, beforeIndex).concat(importSpec).concat(imports.slice(beforeIndex));
        return this._loadImports([importSpec], true, beforeId);
    }
    updateImport(importId, importSpecification) {
        this._checkLoaded();
        const imports = this.stylesheet.imports || [];
        const index$1 = this.getImportIndex(importId);
        if (index$1 === -1)
            return this;
        if (typeof importSpecification === 'string') {
            this.setImportUrl(importId, importSpecification);
            return this;
        }
        if (importSpecification.url && importSpecification.url !== imports[index$1].url) {
            this.setImportUrl(importId, importSpecification.url);
        }
        if (!index.bn(importSpecification.config, imports[index$1].config)) {
            this.setImportConfig(importId, importSpecification.config, importSpecification.data.schema);
        }
        if (!index.bn(importSpecification.data, imports[index$1].data)) {
            this.setImportData(importId, importSpecification.data);
        }
        return this;
    }
    moveImport(importId, beforeId) {
        this._checkLoaded();
        let imports = this.stylesheet.imports || [];
        const index = this.getImportIndex(importId);
        if (index === -1)
            return this;
        const beforeIndex = this.getImportIndex(beforeId);
        if (beforeIndex === -1)
            return this;
        const importSpec = imports[index];
        const fragment = this.fragments[index];
        imports = imports.filter(({id}) => id !== importId);
        this.fragments = this.fragments.filter(({id}) => id !== importId);
        this.stylesheet.imports = imports.slice(0, beforeIndex).concat(importSpec).concat(imports.slice(beforeIndex));
        this.fragments = this.fragments.slice(0, beforeIndex).concat(fragment).concat(this.fragments.slice(beforeIndex));
        this.mergeLayers();
        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;
        const fragment = this.fragments[index];
        fragment.style = this._createFragmentStyle(imports[index]);
        fragment.style.on('style.import.load', () => this.mergeAll());
        fragment.style.loadURL(url);
        return this;
    }
    setImportData(importId, stylesheet) {
        this._checkLoaded();
        const index = this.getImportIndex(importId);
        const imports = this.stylesheet.imports || [];
        if (index === -1)
            return this;
        if (!stylesheet) {
            delete imports[index].data;
            return this.setImportUrl(importId, imports[index].url);
        }
        const fragment = this.fragments[index];
        fragment.style.setState(stylesheet);
        this._reloadImports();
        return this;
    }
    setImportConfig(importId, config, importSchema) {
        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;
        }
        const fragment = this.fragments[index];
        if (importSchema && fragment.style.stylesheet) {
            fragment.style.stylesheet.schema = importSchema;
        }
        const schema = fragment.style.stylesheet && fragment.style.stylesheet.schema;
        fragment.config = config;
        fragment.style.updateConfig(config, schema);
        this.updateConfigDependencies();
        return this;
    }
    removeImport(importId) {
        this._checkLoaded();
        const imports = this.stylesheet.imports || [];
        const index = this.getImportIndex(importId);
        if (index === -1)
            return;
        imports.splice(index, 1);
        const fragment = this.fragments[index];
        fragment.style._remove();
        this.fragments.splice(index, 1);
        this._reloadImports();
    }
    getImportIndex(importId) {
        const imports = this.stylesheet.imports || [];
        const index$1 = imports.findIndex(importSpec => importSpec.id === importId);
        if (index$1 === -1) {
            this.fire(new index.y(new Error(`Import '${ importId }' does not exist in the map's style and cannot be updated.`)));
        }
        return index$1;
    }
    /**
   * 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 = index.aC(id, scope);
        return this._mergedOtherSourceCaches[fqid];
    }
    getLayerSourceCache(layer) {
        const fqid = index.aC(layer.source, layer.scope);
        return layer.type === 'symbol' ? this._mergedSymbolSourceCaches[fqid] : this._mergedOtherSourceCaches[fqid];
    }
    /**
   * Returns all source caches for a given style FQID.
   * If no FQID is provided, returns all source caches,
   * including source caches in imported styles.
   * @param {string} fqid Style FQID.
   * @returns {Array<SourceCache>} List of source caches.
   */
    getSourceCaches(fqid) {
        if (fqid == null)
            return Object.values(this._mergedSourceCaches);
        const sourceCaches = [];
        if (this._mergedOtherSourceCaches[fqid]) {
            sourceCaches.push(this._mergedOtherSourceCaches[fqid]);
        }
        if (this._mergedSymbolSourceCaches[fqid]) {
            sourceCaches.push(this._mergedSymbolSourceCaches[fqid]);
        }
        return sourceCaches;
    }
    updateSourceCaches() {
        const updatedSourceCaches = this._changes.getUpdatedSourceCaches();
        for (const fqid in updatedSourceCaches) {
            const action = updatedSourceCaches[fqid];
            if (action === 'reload') {
                this.reloadSource(fqid);
            } else if (action === 'clear') {
                this.clearSource(fqid);
            }
        }
    }
    updateLayers(parameters) {
        const updatedPaintProps = this._changes.getUpdatedPaintProperties();
        for (const id of 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);
        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]);
    }
    rasterizeImages(mapId, params, callback) {
        this.imageManager.rasterizeImages(params, callback);
    }
    getGlyphs(mapId, params, callback) {
        this.glyphManager.getGlyphs(params.stacks, params.scope, callback);
    }
    getResource(mapId, params, callback) {
        return index.cy(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 index.y(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;
    }
    isLayerClipped(layer, source) {
        if (!this._clipLayerPresent && layer.type !== 'fill-extrusion')
            return false;
        const isFillExtrusion = layer.type === 'fill-extrusion' && layer.sourceLayer === 'building';
        if (layer.is3D()) {
            if (isFillExtrusion || !!source && source.type === 'batched-model')
                return true;
            if (layer.type === 'model') {
                return true;
            }
        } else if (layer.type === 'symbol') {
            return true;
        }
        return false;
    }
    _clearWorkerCaches() {
        this.dispatcher.broadcast('clearCaches');
    }
    destroy() {
        this._clearWorkerCaches();
        this.fragments.forEach(fragment => {
            fragment.style._remove();
        });
        if (this.terrainSetForDrapingOnly()) {
            delete this.terrain;
            delete this.stylesheet.terrain;
        }
    }
}
Style.getSourceType = getType;
Style.setSourceType = setType;
Style.registerForPluginStateChange = index.ch;

var preludeCommon = "\n#define EPSILON 0.0000001\n#define PI 3.141592653589793\n#ifdef RENDER_CUTOFF\nfloat cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);}\n#endif";

var preludeFrag = "\nout vec4 glFragColor;highp float unpack_depth(highp vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\n#ifdef INDICATOR_CUTOUT\nuniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params;\n#endif\nvec4 applyCutout(vec4 color,float height) {\n#ifdef INDICATOR_CUTOUT\nfloat verticalFadeRange=u_indicator_cutout_centers.z*0.25;float holeMinOpacity=mix(1.0,u_indicator_cutout_params.x,smoothstep(u_indicator_cutout_centers.z,u_indicator_cutout_centers.z+verticalFadeRange,height));float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0);\n#else\nreturn color;\n#endif\n}\n#ifdef DEBUG_WIREFRAME\n#define HANDLE_WIREFRAME_DEBUG \\\nglFragColor=vec4(0.7,0.0,0.0,0.7); \\\ngl_FragDepth=gl_FragCoord.z-0.0001;\n#else\n#define HANDLE_WIREFRAME_DEBUG\n#endif\n#ifdef RENDER_CUTOFF\nuniform highp vec4 u_cutoff_params;in float v_cutoff_opacity;\n#endif\nvec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 applyLUT(highp sampler3D lut,vec4 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return vec4(texture(lut,uvw).rgb,col.a);}vec3 applyLUT(highp sampler3D lut,vec3 col) {return applyLUT(lut,vec4(col,1.0)).rgb;}";

var preludeVert = "\n#define EXTENT 8192.0\n#define RAD_TO_DEG 180.0/PI\n#define DEG_TO_RAD PI/180.0\n#define GLOBE_RADIUS EXTENT/PI/2.0\nfloat wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;}\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) {\n#ifndef PROJECTED_POS_ON_VIEWPORT\nfloat tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz;\n#else\nreturn vec3(0.0);\n#endif\n}vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);}\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(\nunpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const vec2 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 (units_to_pixels*pos+offset)/pattern_size;}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) {return get_pattern_pos(pixel_coord_upper,pixel_coord_lower,pattern_size,vec2(tile_units_to_pixels),pos);}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);}\n#ifdef RENDER_CUTOFF\nuniform vec4 u_cutoff_params;out float v_cutoff_opacity;\n#endif\nconst vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(vec2 posWithComposedSkirt)\n{float skirt=float(posWithComposedSkirt.x >=skirtOffset);vec2 pos=posWithComposedSkirt-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);}";

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\nin vec4 v_color;\n#endif\nvoid main() {vec4 out_color;\n#ifdef LIGHTING_3D_MODE\nout_color=v_color;\n#else\nout_color=u_color;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

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

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;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

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 vec2 u_pattern_units_to_pixels;in vec2 a_pos;out highp 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_pattern_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\"\nin vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nuniform float u_emissive_strength;void main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float blur_positive=blur < 0.0 ? 0.0 : 1.0;lowp float antialiasblur=v_data.z;float extrude_length=length(extrude)+antialiasblur*(1.0-blur_positive);float antialiased_blur=-max(abs(blur),antialiasblur);float antialiase_blur_opacity=smoothstep(0.0,antialiasblur,extrude_length-1.0);float opacity_t=blur_positive==1.0 ? \nsmoothstep(0.0,-antialiased_blur,1.0-extrude_length) : \nsmoothstep(antialiased_blur,0.0,extrude_length-1.0)-antialiase_blur_opacity;float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(\nantialiased_blur,0.0,extrude_length-radius/(radius+stroke_width)\n);vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_apply_premultiplied(out_color,v_fog_pos);\n#endif\nglFragColor=out_color*(v_visibility*opacity_t);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}";

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;in vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\n#ifdef ELEVATED_ROADS\nin float a_circle_z_offset;\n#endif\nout vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1,-1),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1,-1),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1,1),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1,1),radius,stroke_width,view_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) {\n#if defined(TERRAIN)\nreturn elevation(pos)+ELEVATION_BIAS;\n#else\nreturn 0.0;\n#endif\n}vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_scale);\n#ifdef PITCH_WITH_MAP\n#ifdef PROJECTION_GLOBE_VIEW\nreturn u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) );\n#else\nreturn u_matrix*( world_center+vec4(sample_offset,0,0) );\n#endif\n#else\nreturn projected_center+vec4(sample_offset,0,0);\n#endif\n}float get_sample_step() {\n#ifdef PITCH_WITH_MAP\nreturn 2.0*PI/float(NUM_SAMPLES_PER_RING);\n#else\nreturn PI/float(NUM_SAMPLES_PER_RING);\n#endif\n}void main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);vec4 world_center;mat3 surface_vectors;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=a_pos_normal_3/16384.0;surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*circle_elevation(circle_center);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*circle_elevation(circle_center);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1);\n#else \nsurface_vectors=mat3(1.0);float height=circle_elevation(circle_center);world_center=vec4(circle_center,height,1);\n#endif\n#ifdef ELEVATED_ROADS\nworld_center.z+=a_circle_z_offset+ELEVATION_BIAS;\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() {glFragColor=vec4(1.0);}";

var clippingMaskVert = "in 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;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0);\n#ifdef FOG\nif (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

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

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

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

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

var collisionBoxVert = "#include \"_prelude_terrain.vertex.glsl\"\nin vec3 a_pos;in vec2 a_anchor_pos;in vec2 a_extrude;in vec2 a_placed;in vec2 a_shift;in vec2 a_elevation_from_sea;in float a_size_scale;in vec2 a_padding;in float a_auto_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;out float v_placed;out float v_notUsed;void main() {float feature_elevation=a_elevation_from_sea.x+a_auto_z_offset;float terrain_elevation=(a_elevation_from_sea.y==1.0 ? 0.0 : elevation(a_anchor_pos));vec4 projectedPoint=u_matrix*vec4(a_pos+elevationVector(a_anchor_pos)*(feature_elevation+terrain_elevation),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 = "in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}";

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

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

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

var fillFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nuniform float u_emissive_strength;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef INDICATOR_CUTOUT\nin highp float v_z_offset;\n#endif\nvoid 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#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nout_color*=opacity;\n#ifdef INDICATOR_CUTOUT\nif (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);}\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\nin vec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#ifdef INDICATOR_CUTOUT\nout highp float v_z_offset;\n#endif\nuniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp float z_offset\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));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\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n#ifdef INDICATOR_CUTOUT\nv_z_offset=z_offset;\n#endif\n}";

var fillOutlineFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\nin highp vec2 v_pos;uniform float u_emissive_strength;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\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#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillOutlineVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\nin vec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nuniform mat4 u_matrix;uniform vec2 u_world;out highp vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp float z_offset\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));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\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\"\n#include \"_prelude_shadow.fragment.glsl\"\nuniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_emissive_strength;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\nin highp vec2 v_pos;in highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillOutlinePatternVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\nuniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nout highp vec2 v_pos;out highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\n#pragma mapbox: define lowp float pixel_ratio\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);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 RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));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\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\"\n#include \"_prelude_shadow.fragment.glsl\"\nuniform vec2 u_texsize;uniform sampler2D u_image;in highp vec2 v_pos;uniform float u_emissive_strength;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\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;highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var fillPatternVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nout highp 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\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));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\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\"\nin vec4 v_color;in vec4 v_flat;\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;\n#endif\nuniform lowp float u_opacity;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;in vec2 v_ao;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nin vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nin highp vec3 v_normal;\n#endif\nuniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor;\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nin float v_flood_radius;in float v_has_floodlight;\n#endif\nin float v_height;\n#pragma mapbox: define highp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp float emissive_strength\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,1.0/gl_FragCoord.w);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;\n#ifdef RENDER_CUTOFF\nshadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;}\n#else\nshadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);\n#endif\ncolor.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor);\n#endif\n#else\ncolor.rgb=apply_lighting(color.rgb,normal);\n#ifdef FLOOD_LIGHT\ncolor.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance);\n#endif\n#endif\ncolor.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity;\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h));\n#endif\n#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color,h);\n#endif\nglFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=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\"\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;uniform float u_width_scale;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\n#ifdef RENDER_WALL_MODE\nin vec3 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nuniform highp float u_vertical_scale;out vec4 v_color;out vec4 v_flat;\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nout vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nout highp vec3 v_normal;\n#endif\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;out vec2 v_ao;\n#endif\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nout float v_flood_radius;out float v_has_floodlight;\n#endif\nout float v_height;vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}\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\n#pragma mapbox: define highp float line_width\n#pragma mapbox: define highp float emissive_strength\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\n#pragma mapbox: initialize highp float line_width\n#pragma mapbox: initialize highp float emissive_strength\nbase*=u_vertical_scale;height*=u_vertical_scale;vec4 pos_nx=floor(a_pos_normal_ed*0.5);vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nv_normal=normal;\n#endif\nbase=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=a_centroid_pos;\n#endif\nfloat ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos;\n#ifdef TERRAIN\nbool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h);\n#else\nh=t > 0.0 ? height : base;pos=vec3(pos_nx.xy,h);\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\nfloat cutoff=1.0;vec3 scaled_pos=pos;\n#ifdef RENDER_CUTOFF\nvec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_pos.x==0.0 ? pos.xyz : (centroid_random/8.0);vec4 ground=u_matrix*vec4(ground_pos.xy,ele,1.0);cutoff=cutoff_opacity(u_cutoff_params,ground.z);if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale);\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0));\n#ifdef RENDER_WALL_MODE\nvec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=a_join_normal_inside.z*wall_offset*0.5;\n#endif\ngl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=pos;vec3 shd_pos1=pos;\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);\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);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.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}";

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;in vec3 v_ao;\n#endif\n#ifdef LIGHTING_3D_MODE\nin vec3 v_normal;\n#endif\nin highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define mediump vec4 pattern\n#pragma mapbox: define highp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize highp float pixel_ratio\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting(out_color,normalize(v_normal))*u_opacity;\n#else\nout_color=out_color*v_lighting;\n#endif\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color,height);\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=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 float u_width_scale;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\n#ifdef RENDER_WALL_MODE\nin vec3 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nout highp vec2 v_pos;out vec4 v_lighting;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;out vec3 v_ao;\n#endif\n#ifdef LIGHTING_3D_MODE\nout vec3 v_normal;\n#endif\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump vec4 pattern\n#pragma mapbox: define highp float pixel_ratio\n#pragma mapbox: define highp float line_width\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 mediump vec4 pattern\n#pragma mapbox: initialize highp float pixel_ratio\n#pragma mapbox: initialize highp float line_width\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 is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_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\n#ifdef RENDER_WALL_MODE\nvec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);p.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;p.xy-=a_join_normal_inside.z*wall_offset*0.5;\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.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 = "precision highp float;uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2(\n(c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c)\n)/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4(\nderiv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}";

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\nin highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);}\n#ifdef FOG\nin highp float v_fog;\n#endif\n#endif\nvoid main() {\n#ifdef CLEAR_SUBPASS\nvec4 color=vec4(1.0);\n#ifdef CLEAR_FROM_TEXTURE\ncolor=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size));\n#endif\nglFragColor=color;\n#else\n#ifdef SDF_SUBPASS\nhighp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0;\n#ifdef FOG\nfog=v_fog;\n#endif\n#ifdef RENDER_CUTOFF\nfog*=v_cutoff_opacity;\n#endif\nglFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog));\n#else\nvec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass);\n#ifdef OVERDRAW_INSPECTOR\ncolor=vec4(1.0);\n#endif\nglFragColor=color;\n#endif\nHANDLE_WIREFRAME_DEBUG;\n#endif\n}";

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

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

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

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

var lineFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\nuniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv;\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef RENDER_LINE_DASH\nuniform sampler2D u_dash_image;in vec2 v_tex;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform sampler2D u_gradient_image;\n#endif\n#ifdef INDICATOR_CUTOUT\nin highp float v_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\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=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);\n#ifdef RENDER_LINE_DASH\nfloat sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/dash.z;float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist);\n#endif\nhighp vec4 out_color;\n#ifdef RENDER_LINE_GRADIENT\nout_color=texture(u_gradient_image,v_uv.xy);\n#else\nout_color=color;\n#endif\nfloat trim_alpha=1.0;\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);out_color=mix(out_color,u_trim_color,transition_factor);trim_alpha=1.0-transition_factor;}\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*u_width_scale)+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) {float 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=mix(border_color*trim_alpha,out_color,smoothAlpha);}}\n#endif\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);\n#ifdef ELEVATED_ROADS\nout_color.rgb*=mix(v_road_z_offset > 0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\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,v_z_offset);\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var lineVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\n#define EXTRUDE_SCALE 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH)\nin vec3 a_z_offset_width;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nin highp vec3 a_packed;\n#endif\n#ifdef RENDER_LINE_DASH\nin float a_linesofar;\n#endif\nuniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform highp float u_floor_width_scale;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) {\n#ifdef ELEVATION_REFERENCE_SEA\nreturn 0.0;\n#else\nreturn elevation(apos);\n#endif\n}\n#endif\nout vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec3 v_uv;\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef RENDER_LINE_DASH\nuniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform float u_image_height;\n#endif\n#ifdef INDICATOR_CUTOUT\nout highp float v_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\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 a_z_offset;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\na_z_offset=a_z_offset_width.x;\n#endif\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;\n#ifdef VARIABLE_LINE_WIDTH\nfloat left=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);halfwidth=(u_width_scale*(left==1.0 ? a_z_offset_width.y : a_z_offset_width.z))/2.0;\n#else\nhalfwidth=(u_width_scale*width)/2.0;\n#endif\noffset=-1.0*offset*u_width_scale;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);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy;\n#ifdef ELEVATED_ROADS\nv_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude;\n#else\n#ifdef ELEVATED\nvec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+a_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0);\n#else\n#ifdef CROSS_SLOPE_HORIZONTAL\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+a_z_offset;\n#else\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+a_z_offset;\n#endif\n#endif\ngl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden);\n#else\ngl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden);\n#endif\n#endif\n#ifdef ELEVATED_ROADS\n#ifdef RENDER_SHADOWS\nvec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_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\n#endif\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=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur));\n#else\nv_gamma_scale=1.0;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nhighp float a_uv_x=a_packed[0];float a_split_index=a_packed[1];highp float line_progress=a_packed[2];\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=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress);\n#else\nv_uv=vec3(a_uv_x,0.0,line_progress);\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*u_floor_width_scale),(-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#ifdef INDICATOR_CUTOUT\nv_z_offset=a_z_offset;\n#endif\n}";

var linePatternFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\nuniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef RENDER_LINE_TRIM_OFFSET\nin highp vec3 v_uv;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef LINE_JOIN_NONE\nin vec2 v_pattern_data;\n#endif\n#ifdef INDICATOR_CUTOUT\nin highp float v_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\nuniform float u_emissive_strength;\n#pragma mapbox: define mediump vec4 pattern\n#pragma mapbox: define mediump float pixel_ratio\n#pragma mapbox: define mediump float blur\n#pragma mapbox: define mediump float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize mediump float pixel_ratio\n#pragma mapbox: initialize mediump float blur\n#pragma mapbox: initialize mediump float opacity\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*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);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);}\n#endif\n#ifdef LINE_JOIN_NONE\nhighp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);}\n#endif\n#ifdef LIGHTING_3D_MODE\ncolor=apply_lighting_with_emission_ground(color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);\n#ifdef ELEVATED_ROADS\ncolor.rgb*=mix(v_road_z_offset > 0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\ncolor.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ncolor*=(alpha*opacity);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}}\n#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color,v_z_offset);\n#endif\nglFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var linePatternVert = "#include \"_prelude_fog.vertex.glsl\"\n#include \"_prelude_shadow.vertex.glsl\"\n#include \"_prelude_terrain.vertex.glsl\"\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\nin vec3 a_z_offset_width;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nin highp vec3 a_packed;\n#endif\nin highp float a_linesofar;\n#ifdef LINE_JOIN_NONE\nin highp vec3 a_pattern_data;out vec2 v_pattern_data;\n#endif\n#ifdef INDICATOR_CUTOUT\nout highp float v_z_offset;\n#endif\nuniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) {\n#ifdef ELEVATION_REFERENCE_SEA\nreturn 0.0;\n#else\nreturn elevation(apos);\n#endif\n}\n#endif\nout vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef RENDER_LINE_TRIM_OFFSET\nout highp vec3 v_uv;\n#endif\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#pragma mapbox: define mediump float blur\n#pragma mapbox: define mediump float opacity\n#pragma mapbox: define mediump float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define mediump float floorwidth\n#pragma mapbox: define mediump vec4 pattern\n#pragma mapbox: define mediump float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize mediump float blur\n#pragma mapbox: initialize mediump float opacity\n#pragma mapbox: initialize mediump float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize mediump float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern\n#pragma mapbox: initialize mediump float pixel_ratio\nfloat a_z_offset;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\na_z_offset=a_z_offset_width.x;\n#endif\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);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=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;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);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy;\n#ifdef ELEVATED_ROADS\nv_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude;\n#else\n#ifdef ELEVATED\nvec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+a_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0);\n#else\n#ifdef CROSS_SLOPE_HORIZONTAL\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+a_z_offset;\n#else\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+a_z_offset;\n#endif\n#endif\ngl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden);\n#else\ngl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden);\n#endif\n#endif\n#ifdef ELEVATED_ROADS\n#ifdef RENDER_SHADOWS\nvec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_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\n#endif\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=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur));\n#else\nv_gamma_scale=1.0;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress);\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale);\n#ifdef LINE_JOIN_NONE\nv_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/((pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n#ifdef INDICATOR_CUTOUT\nv_z_offset=a_z_offset;\n#endif\n}";

var rasterFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\n#include \"_prelude_raster_array.glsl\"\nuniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth;\n#ifdef PROJECTION_GLOBE_VIEW\nin float v_split_fade;\n#endif\nuniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength;\n#ifndef RASTER_ARRAY\nuniform highp sampler2D u_image0;uniform sampler2D u_image1;\n#endif\n#ifdef RASTER_COLOR\nuniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res;\n#endif\nvoid main() {vec4 color0,color1,color;vec2 value;\n#ifdef RASTER_COLOR\n#ifdef RASTER_ARRAY\n#ifdef RASTER_ARRAY_LINEAR\nvalue=mix(\nraTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\n);\n#else\nvalue=mix(\nraTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\n);\n#endif\nif (value.y > 0.0) value.x/=value.y;\n#else\ncolor=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a);\n#endif\ncolor=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y;\n#else\ncolor0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);\n#endif\ncolor.a*=u_opacity;\n#ifdef GLOBE_POLES\ncolor.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition);\n#endif\nvec3 rgb=color.rgb;rgb=vec3(\ndot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb;\n#endif\n#ifdef FOG\nhighp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit));\n#endif\nglFragColor=vec4(out_color*color.a,color.a);\n#ifdef PROJECTION_GLOBE_VIEW\nglFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade));\n#endif\n#ifdef RENDER_CUTOFF\nglFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth);\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var rasterVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center;\n#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8\n#ifdef GLOBE_POLES\nin vec3 a_globe_pos;in vec2 a_uv;\n#else\nin vec2 a_pos;in vec2 a_texture_pos;\n#endif\nout vec2 v_pos0;out vec2 v_pos1;out float v_depth;\n#ifdef PROJECTION_GLOBE_VIEW\nout float v_split_fade;\n#endif\nvoid main() {vec2 uv;\n#ifdef GLOBE_POLES\nvec3 globe_pos=a_globe_pos;globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos   ,1.0);uv=a_uv;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz);\n#endif\n#else\nfloat w=1.0+dot(a_texture_pos,u_perspective_transform);uv=a_texture_pos/8192.0;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);    \nv_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n#else\ngl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n#endif\n#endif\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1;\n#ifdef RENDER_CUTOFF\nv_depth=gl_Position.z;\n#endif\n}";

var rasterParticleFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 out_color=color.rgb;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),0.0).rgb;\n#endif\n#ifdef FOG\nhighp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit));\n#endif\nglFragColor=vec4(out_color*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var rasterParticleVert = "#include \"_prelude_fog.vertex.glsl\"\nuniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center;\n#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8\nin vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n#else\nuv=a_texture_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n#endif\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}";

var rasterParticleDrawFrag = "uniform sampler2D u_color_ramp;in float v_particle_speed;void main() {glFragColor=texture(u_color_ramp,vec2(v_particle_speed,0.5));}";

var rasterParticleDrawVert = "#include \"_prelude_raster_particle.glsl\"\nin float a_index;uniform sampler2D u_particle_texture;uniform float u_particle_texture_side_len;uniform vec2 u_tile_offset;out float v_particle_speed;void main() {ivec2 pixel_coord=ivec2(\nmod(a_index,u_particle_texture_side_len),a_index/u_particle_texture_side_len);vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);vec2 pos=unpack_pos_from_rgba(pixel)+u_tile_offset;vec2 tex_coord=fract(pos);vec2 velocity=lookup_velocity(tex_coord);if (velocity==INVALID_VELOCITY) {gl_Position=AWAY;v_particle_speed=0.0;} else {gl_Position=vec4(2.0*pos-1.0,0,1);v_particle_speed=length(velocity);}gl_PointSize=1.0;}";

var rasterParticleTextureFrag = "uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}";

var rasterParticleTextureVert = "in vec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*a_pos+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}";

var rasterParticleUpdateFrag = "#include \"_prelude_raster_particle.glsl\"\nuniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return  clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow(\nlinearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4)\n);highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}";

var rasterParticleUpdateVert = "in vec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*(a_pos+vec2(1.0));gl_Position=vec4(a_pos,0.0,1.0);}";

var symbolFrag = "#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_text;uniform bool u_is_halo;uniform lowp float u_scale_factor;\n#ifdef ICON_TRANSITION\nuniform float u_icon_transition;\n#endif\n#ifdef COLOR_ADJUSTMENT\nuniform mat4 u_color_adj_mat;\n#endif\n#ifdef INDICATOR_CUTOUT\nin highp float v_z_offset;\n#endif\nin vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nin vec2 v_tex_b;\n#endif\nin float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity;\n#ifdef RENDER_TEXT_AND_SYMBOL\nin float is_sdf;in vec2 v_tex_a_icon;\n#endif\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\nvec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2];\n#ifdef RENDER_TEXT_AND_SYMBOL\nif (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity;glFragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nreturn;}\n#endif\n#ifdef RENDER_SDF\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha;\n#else\n#ifdef ICON_TRANSITION\nvec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b);\n#else\nout_color=texture(u_texture,v_tex_a);\n#endif\n#ifdef COLOR_ADJUSTMENT\nout_color=u_color_adj_mat*out_color;\n#endif\n#endif\nout_color*=opacity*fade_opacity;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#endif\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color,v_z_offset);\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var symbolVert = "#include \"_prelude_terrain.vertex.glsl\"\nin vec4 a_pos_offset;in vec4 a_tex_size;in vec4 a_pixeloffset;in vec4 a_projected_pos;in float a_fade_opacity;\n#ifdef Z_OFFSET\nin float a_auto_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_globe_anchor;in vec3 a_globe_normal;\n#endif\n#ifdef ICON_TRANSITION\nin vec2 a_texb;\n#endif\n#ifdef OCCLUSION_QUERIES\nin float a_occlusion_query_opacity;\n#endif\n#ifdef INDICATOR_CUTOUT\nout highp float v_z_offset;\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_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\n#endif\nout vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nout vec2 v_tex_b;\n#endif\nout float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity;\n#ifdef RENDER_TEXT_AND_SYMBOL\nout float is_sdf;out vec2 v_tex_a_icon;\n#endif\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\n#pragma mapbox: define lowp float occlusion_opacity\n#pragma mapbox: define lowp float z_offset\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\n#pragma mapbox: initialize lowp float occlusion_opacity\n#pragma mapbox: initialize lowp float z_offset\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=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor);\n#ifdef Z_OFFSET\ne+=a_auto_z_offset;\n#endif\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe;\n#ifdef PROJECTION_GLOBE_VIEW\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=a_globe_anchor+h;world_pos=mix_globe_mercator(world_pos_globe,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;vec2 a;\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);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w;\n#else\noffsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w;\n#endif\nvec2 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\n#ifdef PROJECTED_POS_ON_VIEWPORT\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0);\n#else\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);    \n#endif\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\n#ifdef Z_OFFSET\nz+=u_pitch_with_map ? a_auto_z_offset+(u_elevation_from_sea ? z_offset : z_offset) : 0.0;\n#else\nz+=u_pitch_with_map ? (u_elevation_from_sea ? z_offset : z_offset) : 0.0;\n#endif\nfloat occlusion_fade=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 out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));\n#ifdef DEPTH_OCCLUSION\nfloat depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier;\n#endif\n#ifdef OCCLUSION_QUERIES\nfloat occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier;\n#endif\nfloat alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\n#else\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\n#endif\nfloat gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize;\n#ifdef RENDER_TEXT_AND_SYMBOL\nis_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon;\n#endif\n#ifdef ICON_TRANSITION\nv_tex_b=a_texb/u_texsize;\n#endif\n#ifdef INDICATOR_CUTOUT\nv_z_offset=e;\n#endif\n}";

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

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

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

var terrainRasterFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_shadow.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform sampler2D u_image0;in vec2 v_pos0;\n#ifdef FOG\nin float v_fog_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nin vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;\n#endif\nuniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color;\n#ifdef LIGHTING_3D_MODE\nconst vec3 normal=vec3(0.0,0.0,1.0);\n#ifdef RENDER_SHADOWS\nfloat cutoffOpacity=1.0;\n#ifdef RENDER_CUTOFF\ncutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w);\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,1.0/gl_FragCoord.w,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,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity));\n#endif\n#else\nfloat lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor);\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\ncolor.rgb=mix(color.rgb,image_color.rgb,image_color.a);color.a=1.0;\n#endif\n#endif\n#else\ncolor=image_color;\n#endif\n#ifdef FOG\n#ifdef ZERO_EXAGGERATION\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#else\ncolor=fog_dither(fog_apply_from_vert(color,v_fog_opacity));\n#endif\n#endif\nglFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

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

var terrainDepthFrag = "precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}";

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

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\n#ifdef TERRAIN\nuniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}float prevElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}\n#ifdef TERRAIN_VERTEX_MORPHING\nfloat elevation(vec2 apos) {\n#ifdef ZERO_EXAGGERATION\nreturn 0.0;\n#endif\nfloat nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);}\n#else\nfloat elevation(vec2 apos) {\n#ifdef ZERO_EXAGGERATION\nreturn 0.0;\n#endif\nreturn currentElevation(apos);}\n#endif\nvec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);}\n#else\nfloat elevation(vec2 pos) { return 0.0; }\n#endif\n#ifdef DEPTH_OCCLUSION\nuniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset;\n#ifdef DEPTH_D24\nfloat unpack_depth(float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;}vec4 unpack_depth4(vec4 depth) {return depth*u_depth_range_unpack.x+vec4(u_depth_range_unpack.y);}\n#else\nhighp float unpack_depth_rgba(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;}\n#endif\nbool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;\n#ifdef DEPTH_D24\nfloat depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5).r);\n#else\nfloat depth=unpack_depth_rgba(texture(u_depth,(coord.xy+1.0)*0.5));\n#endif\nreturn coord.z+u_occlusion_depth_offset > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=0.5*coord.xy+0.5;\n#ifdef DEPTH_D24\nhighp vec4 depth=vec4(\ntexture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r\n);depth=unpack_depth4(depth);\n#else\nhighp vec4 depth=vec4(\nunpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy))\n);\n#endif\nreturn depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=0.5*coord.xy+0.5;int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) {\n#ifdef DEPTH_D24\nhighp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r);\n#else\nhighp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)));\n#endif\nres+=1.0-clamp(300.0*(coord.z+u_occlusion_depth_offset-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z+u_occlusion_depth_offset)-depth),0.0,1.0));}\n#else\nbool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; }\n#endif//DEPTH_OCCLUSION";

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;out vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);}\n#endif";

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;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=gl_FragCoord.xy/u_viewport;highp vec3 ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}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 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);}\n#endif//LIGHTING_3D_MODE";

var preludeRasterArrayFrag = "#ifdef RASTER_ARRAY\nuniform highp sampler2D u_image0;uniform sampler2D u_image1;const vec4 NODATA=vec4(1);ivec4 _raTexLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}vec2 _raTexLinearMix(highp vec2 fxy,highp vec4 colorMix,highp float colorOffset,highp vec4 t00,highp vec4 t10,highp vec4 t01,highp vec4 t11) {vec2 c00=t00==NODATA ? vec2(0) : vec2(colorOffset+dot(t00,colorMix),1);vec2 c10=t10==NODATA ? vec2(0) : vec2(colorOffset+dot(t10,colorMix),1);vec2 c01=t01==NODATA ? vec2(0) : vec2(colorOffset+dot(t01,colorMix),1);vec2 c11=t11==NODATA ? vec2(0) : vec2(colorOffset+dot(t11,colorMix),1);return mix(mix(c01,c11,fxy.x),mix(c00,c10,fxy.x),fxy.y);}vec2 raTexture2D_image0_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image0,c.yz,0),texelFetch(u_image0,c.xz,0),texelFetch(u_image0,c.yw,0),texelFetch(u_image0,c.xw,0)\n);}vec2 raTexture2D_image1_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image1,c.yz,0),texelFetch(u_image1,c.xz,0),texelFetch(u_image1,c.yw,0),texelFetch(u_image1,c.xw,0)\n);}vec2 raTexture2D_image0_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image0,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}vec2 raTexture2D_image1_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image1,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}\n#endif";

var preludeRasterParticleFrag = "#ifdef RASTER_ARRAY\nuniform sampler2D u_velocity;uniform mediump vec2 u_velocity_res;uniform mediump float u_max_speed;const vec4 NO_DATA=vec4(1);const vec2 INVALID_VELOCITY=vec2(-1);uniform highp vec2 u_uv_offset;uniform highp float u_data_offset;uniform highp vec2 u_data_scale;ivec4 rasterArrayLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}highp vec2 lookup_velocity(highp vec2 uv) {uv=u_uv_offset.x+u_uv_offset.y*uv;highp vec2 fxy;ivec4 c=rasterArrayLinearCoord(uv,u_velocity_res,fxy);highp vec4 tl=texelFetch(u_velocity,c.yz,0);highp vec4 tr=texelFetch(u_velocity,c.xz,0);highp vec4 bl=texelFetch(u_velocity,c.yw,0);highp vec4 br=texelFetch(u_velocity,c.xw,0);if (tl==NO_DATA) {return INVALID_VELOCITY;}if (tr==NO_DATA) {return INVALID_VELOCITY;}if (bl==NO_DATA) {return INVALID_VELOCITY;}if (br==NO_DATA) {return INVALID_VELOCITY;}highp vec4 t=mix(mix(bl,br,fxy.x),mix(tl,tr,fxy.x),fxy.y);highp vec2 velocity=u_data_offset+vec2(dot(t.rg,u_data_scale),dot(t.ba,u_data_scale));velocity.y=-velocity.y;velocity/=max(u_max_speed,length(velocity));return velocity;}\n#endif\nuniform highp float u_particle_pos_scale;uniform highp vec2 u_particle_pos_offset;highp vec4 pack_pos_to_rgba(highp vec2 p) {highp vec2 v=(p+u_particle_pos_offset)/u_particle_pos_scale;highp vec4 r=vec4(v.x,fract(v.x*255.0),v.y,fract(v.y*255.0));return vec4(r.x-r.y/255.0,r.y,r.z-r.w/255.0,r.w);}highp vec2 unpack_pos_from_rgba(highp vec4 v) {v=floor(v*255.0+0.5)/255.0;highp vec2 p=vec2(v.x+(v.y/255.0),v.z+(v.w/255.0));return u_particle_pos_scale*p-u_particle_pos_offset;}";

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

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

var globeFrag = "#include \"_prelude_fog.fragment.glsl\"\n#include \"_prelude_lighting.glsl\"\nuniform sampler2D u_image0;uniform float u_far_z_cutoff;in vec2 v_pos0;\n#ifndef FOG\nuniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport;\n#endif\nvoid main() {vec4 color;\n#ifdef CUSTOM_ANTIALIASING\nhighp 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 norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0);\n#ifdef LIGHTING_3D_MODE\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nraster=apply_lighting_with_emission_ground(raster,raster.a);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias);\n#else\nraster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias);\n#endif\n#else\ncolor=vec4(raster.rgb*antialias,raster.a*antialias);\n#endif\n#else\ncolor=texture(u_image0,v_pos0);\n#ifdef LIGHTING_3D_MODE\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\ncolor=apply_lighting_with_emission_ground(color,color.a);color.a=1.0;\n#else\ncolor=apply_lighting_ground(color);\n#endif\n#endif\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ncolor*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=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\nin vec3 a_globe_pos;in vec2 a_uv;\n#else\nin vec2 a_pos;\n#endif\nout vec2 v_pos0;void main() {\n#ifdef GLOBE_POLES\nvec3 globe_pos=a_globe_pos;vec2 uv=a_uv;\n#else\nfloat tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY);\n#endif\nv_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale;\n#ifdef GLOBE_POLES\nvec3 up_vector=globe_derived_up_vector;\n#else\nvec3 up_vector=elevationVector(tile_pos);\n#endif\nfloat height=elevation(tile_pos);globe_pos+=up_vector*height;\n#ifndef GLOBE_POLES\nglobe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z;\n#endif\n#ifdef GLOBE_POLES\nvec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0);\n#else\nvec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0);\n#endif\ngl_Position=u_proj_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n}";

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;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir;\n#ifdef PROJECTION_GLOBE_VIEW\nglobe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) {\n#ifdef ALPHA_PASS\nglFragColor=vec4(0,0,0,0);return;\n#else\n#ifdef NATIVE\nglFragColor=vec4(1,1,1,1);\n#else\nglFragColor=vec4(0,0,0,1);\n#endif\nreturn;\n#endif\n}\n#endif\nhighp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ?\n0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle;\n#ifdef PROJECTION_GLOBE_VIEW\nhighp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ?\nPI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t);\n#else\nhorizon_angle=horizon_angle_mercator;\n#endif\nhorizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb;\n#ifdef ALPHA_PASS\nfloat a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a);\n#else\nvec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t);\n#endif\n}";

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

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

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

var snowFrag = "in highp vec2 uv;in highp float alphaMultiplier;uniform vec4 u_particleColor;uniform vec2 u_simpleShapeParameters;void main() {float t=clamp((length(uv)-u_simpleShapeParameters.x)/(1.0-u_simpleShapeParameters.x),0.0,1.0);float alpha=1.0-pow(t,pow(10.0,u_simpleShapeParameters.y));alpha*=alphaMultiplier;alpha*=u_particleColor.a;vec3 color=u_particleColor.rgb*alpha;glFragColor=vec4(color,alpha) ;HANDLE_WIREFRAME_DEBUG;}";

var snowVert = "\nin highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_snowParticleData;in highp vec4 a_snowParticleDataHorizontalOscillation;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform vec2 u_screenSize;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; \nuniform float u_velocity;uniform vec3 u_direction;uniform float u_horizontalOscillationRadius; \nuniform float u_horizontalOscillationRate; \nuniform float u_billboardSize;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;out highp vec2 uv;out highp float alphaMultiplier;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos.xyz*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_snowParticleData.z;float coneAngleHeadingRad=a_snowParticleData.w*radians(360.0);vec3 localZ=normalize(u_direction);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 direction;direction.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.z=cos(coneAnglePichRad);direction=normalize(direction);vec3 simPosLocal=vec3(0,0,0);float velocityScale=(1.0+3.0*a_snowParticleData.y)*u_velocity;simPosLocal+=direction*velocityScale*u_time;float horizontalOscillationRadius=u_horizontalOscillationRadius*a_snowParticleDataHorizontalOscillation.x;float horizontalOscillationAngle=u_horizontalOscillationRate*u_time*(-1.0+2.0*a_snowParticleDataHorizontalOscillation.y);simPosLocal.xy+=horizontalOscillationRadius*vec2(cos(horizontalOscillationAngle),sin(horizontalOscillationAngle));vec3 simPos=localX*simPosLocal.x+\nlocalY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);float clipZ=-u_cam_pos.z+pos.z;vec4 posView=u_modelview*vec4(pos,1.0);float size=u_billboardSize;alphaMultiplier=1.0;vec4 posScreen=u_projection*posView;posScreen/=posScreen.w;posScreen.xy=vec2(0.5)+posScreen.xy*0.5;posScreen.xy*=u_screenSize;vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=u_screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-posScreen.xy)/(0.5*u_screenSize));screenDist+=a_snowParticleData.x*u_thinningParticleOffset;float scaleFactorMode=0.0;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);if (a_snowParticleData.x < u_thinningAffectedRatio) {scaleFactorMode=1.0-thinningFadeRatio;alphaMultiplier=thinningFadeRatio;}}vec4 posScreen1=u_projection*vec4(posView.x-size,posView.yzw);posScreen1/=posScreen1.w;vec4 posScreen2=u_projection*vec4(posView.x+size,posView.yzw);posScreen2/=posScreen2.w;posScreen1.xy=vec2(0.5)+posScreen1.xy*0.5;posScreen1.xy*=u_screenSize;posScreen2.xy=vec2(0.5)+posScreen2.xy*0.5;posScreen2.xy*=u_screenSize;float screenLength=length(posScreen1.xy-posScreen2.xy);float screenEpsilon=3.0;float scaleFactor=1.0;if (screenLength < screenEpsilon) {scaleFactor=screenEpsilon/max(screenLength,0.01);scaleFactor=mix(scaleFactor,1.0,scaleFactorMode);}float screenEpsilon2=15.0;if (screenLength > screenEpsilon2) {scaleFactor=screenEpsilon2/max(screenLength,0.01);}size*=scaleFactor;vec2 right=size*vec2(1,0);vec2 up=size*vec2(0,1);posView.xy+=right*a_uv.x;posView.xy+=up*a_uv.y;uv=a_uv;gl_Position=u_projection*posView;}";

var rainFrag = "in highp vec2 uv;in highp float particleRandomValue;uniform sampler2D u_texScreen;uniform float u_distortionStrength;uniform vec4 u_color;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;uniform float u_shapeDirectionalPower;uniform float u_mode;void main() {vec2 st=uv*0.5+vec2(0.5);vec2 uvm=uv;uvm.y=-1.0+2.0*pow(st.y,u_shapeDirectionalPower);float shape=clamp(1.0-length(uvm),0.0,1.0);float alpha=abs(shape)*u_color.a;vec2 screenSize=vec2(textureSize(u_texScreen,0));vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-gl_FragCoord.xy)/(0.5*screenSize));screenDist+=(0.5+0.5*particleRandomValue)*u_thinningParticleOffset;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;float thinningAlpha=1.0;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);thinningAlpha*=thinningFadeRatio;}vec2 offsetXY=normalize(uvm)*abs(shape);vec2 stScreen=(gl_FragCoord.xy+offsetXY*u_distortionStrength*thinningAlpha)/screenSize;vec3 colorScreen=texture(u_texScreen,stScreen).rgb;alpha*=thinningAlpha;glFragColor=mix(vec4(colorScreen,1.0),vec4(u_color.rgb*alpha,alpha),u_mode);HANDLE_WIREFRAME_DEBUG;}";

var rainVert = "\nin highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_rainParticleData;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; \nuniform float u_velocity; \nuniform vec2 u_rainDropletSize;uniform vec3 u_rainDirection;out highp vec2 uv;out highp float particleRandomValue;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos*=halfBoxSize; \npos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_rainParticleData.z;float coneAngleHeadingRad=a_rainParticleData.w*radians(360.0);vec3 localZ=normalize(u_rainDirection);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 directionLocal;directionLocal.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.z=cos(coneAnglePichRad);directionLocal=normalize(directionLocal);vec3 directionWorld=localX*directionLocal.x+localY*directionLocal.y+localZ*directionLocal.z;float velocityScale=(1.0+3.0*a_rainParticleData.y)*u_velocity;vec3 simPosLocal=vec3(0,0,0);simPosLocal+=directionLocal*velocityScale*u_time;vec3 simPos=localX*simPosLocal.x+\nlocalY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);vec4 posView=u_modelview*vec4(pos,1.0);vec3 directionView=normalize((u_modelview*vec4(directionWorld,0.0)).xyz);vec3 side=cross(directionView,normalize(posView.xyz));posView.xyz+=side*a_uv.x*u_rainDropletSize.x;posView.xyz+=directionView*a_uv.y*u_rainDropletSize.y;uv=a_uv;particleRandomValue=a_rainParticleData.x;gl_Position=u_projection*posView;}";

var vignetteFrag = "uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}";

var vignetteVert = "in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}";

var occlusionFrag = "uniform vec4 u_color;void main() {glFragColor=u_color;}";

var occlusionVert = "#include \"_prelude_terrain.vertex.glsl\"\nin highp vec2 a_offset_xy;uniform highp vec3 u_anchorPos;uniform mat4 u_matrix;uniform vec2 u_screenSizePx;uniform vec2 u_occluderSizePx;void main() {vec3 world_pos=u_anchorPos;\n#ifdef TERRAIN\nfloat e=elevation(world_pos.xy);world_pos.z+=e;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1.0);projected_point.xy+=projected_point.w*a_offset_xy*0.5*u_occluderSizePx/u_screenSizePx;gl_Position=projected_point;}";

var fillExtrusionDepthFrag = "in highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\nglFragColor=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_width_scale;uniform float u_vertical_scale;\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nin vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\n#ifdef RENDER_WALL_MODE\nin vec3 a_join_normal_inside;\n#endif\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp float line_width\n#pragma mapbox: define highp vec4 color\nout highp float v_depth;void main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp float line_width\n#pragma mapbox: initialize highp vec4 color\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 is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;float ele=elevation(pos_nx.xy);float c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h);\n#else\npos=vec3(pos_nx.xy,t > 0.0 ? height : base);\n#endif\n#ifdef RENDER_WALL_MODE\nvec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);pos.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;pos.xy-=a_join_normal_inside.z*wall_offset*0.5;\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.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\"\nprecision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;\n#ifdef FOG\nin float v_fog_opacity;\n#endif\nvoid main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);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,1.0/gl_FragCoord.w));\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),0.0).r);\n#endif\nglFragColor=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;in vec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1;\n#ifdef FOG\nout float v_fog_opacity;\n#endif\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0);\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\"\nin vec3 a_pos_3f;\n#pragma mapbox: define-attribute highp vec3 normal_3f\n#pragma mapbox: define-attribute highp vec2 uv_2f\n#pragma mapbox: define-attribute highp vec3 color_3f\n#pragma mapbox: define-attribute highp vec4 color_4f\n#pragma mapbox: define-attribute-vertex-shader-only highp vec4 pbr\n#pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength\nuniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix;\n#ifdef INSTANCED_ARRAYS\nin vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3;\n#else\nuniform highp mat4 u_normal_matrix;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth_shadows;\n#endif\nout vec4 v_position_height;out lowp vec4 v_color_mix;\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nout highp float v_depth;\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\nout lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params;\n#endif\nvec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() {\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\n#pragma mapbox: initialize-attribute highp vec3 color_3f\n#pragma mapbox: initialize-attribute highp vec4 color_4f\n#pragma mapbox: initialize-attribute-custom highp vec4 pbr\n#pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength\nhighp mat4 normal_matrix;\n#ifdef INSTANCED_ARRAYS\nnormal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\n#else\nnormal_matrix=u_normal_matrix;\n#endif\nvec3 local_pos;mat3 rs;\n#ifdef MODEL_POSITION_ON_GPU\nvec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);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=mix(u_matrix*pos,AWAY,hidden);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\nvec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0);\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.xyz+=offset*shadow_normal_offset_multiplier0();\n#else\nvec3 offset=shadow_normal_offset_model(normal_3f);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0();\n#endif\n#endif\n#endif\nv_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;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;in highp vec4 v_position_height;in lowp vec4 v_color_mix;\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows;\n#endif\n#ifdef OCCLUSION_TEXTURE_TRANSFORM\nuniform vec4 u_occlusionTextureTransform;\n#endif\n#pragma mapbox: define-attribute highp vec3 normal_3f\n#pragma mapbox: define-attribute highp vec3 color_3f\n#pragma mapbox: define-attribute highp vec4 color_4f\n#pragma mapbox: define-attribute highp vec2 uv_2f\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\n#pragma mapbox: initialize-attribute highp vec3 color_3f\n#pragma mapbox: initialize-attribute highp vec4 color_4f\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\n#ifdef HAS_ATTRIBUTE_a_pbr\nin lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params;\n#endif\n#ifdef HAS_TEXTURE_u_baseColorTexture\nuniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff;\n#endif\n#ifdef HAS_TEXTURE_u_metallicRoughnessTexture\nuniform sampler2D u_metallicRoughnessTexture;\n#endif\n#ifdef HAS_TEXTURE_u_occlusionTexture\nuniform sampler2D u_occlusionTexture;uniform float u_aoIntensity;\n#endif\n#ifdef HAS_TEXTURE_u_normalTexture\nuniform sampler2D u_normalTexture;\n#endif\n#ifdef HAS_TEXTURE_u_emissionTexture\nuniform sampler2D u_emissionTexture;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nin highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack;\n#ifdef DEPTH_D24\nhighp float unpack_depth(highp float depth) {return  depth*u_depth_range_unpack.x+u_depth_range_unpack.y;}\n#else\nhighp float unpack_depth_rgba(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;}\n#endif\nbool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size;\n#ifdef DEPTH_D24\nhighp float depth=unpack_depth(texture(u_depthTexture,coord).r);\n#else\nhighp float depth=unpack_depth_rgba(texture(u_depthTexture,coord));\n#endif\nreturn v_depth > depth+0.0005;}\n#endif\n#define saturate(_x) clamp(_x,0.,1.)\nvec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor)\n{\n#ifdef LIGHTING_3D_MODE\nvec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor;\n#ifdef RENDER_SHADOWS\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\n#else\nlighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir));\n#endif\nreturn apply_lighting(albedo,transformed_normal,lighting_factor);\n#else\nvec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3;\n#endif\n}vec4 getBaseColor() {vec4 albedo=u_baseColorFactor;\n#ifdef HAS_ATTRIBUTE_a_color_3f\nalbedo*=vec4(color_3f,1.0);\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\n#else\n#ifdef HAS_ATTRIBUTE_a_color_4f\nalbedo*=color_4f;\n#endif\n#endif\n#if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f)\nvec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}}\n#ifdef UNPREMULT_TEXTURE_IN_SHADER\nif(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0;\n#endif\nif(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;}\n#endif\nvec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a);\n#ifdef APPLY_LUT_ON_GPU\ncolor=applyLUT(u_lutTexture,color);\n#endif\nreturn color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) {\n#ifdef HAS_TEXTURE_u_normalTexture\nhighp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res;\n#else\nreturn mat3(1.0);\n#endif\n}highp vec3 getNormal(){highp vec3 n;\n#ifdef HAS_ATTRIBUTE_a_normal_3f\nn=normalize(normal_3f);\n#else\nhighp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z));n=normalize(cross(fdx,fdy))*-1.0;\n#endif\n#if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nvec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap);\n#endif\nreturn n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor;\n#ifdef HAS_ATTRIBUTE_a_pbr\nmat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w;\n#endif\n#if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) \nvec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b;\n#endif\nconst float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness)\n{float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH)\n{return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH)\n{float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness)\n{highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV)\n{float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat)\n{\n#ifdef LIGHTING_3D_MODE\nreturn mat.diffuseColor;\n#else\nreturn mat.diffuseColor/PI;\n#endif\n}vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV)\n{vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal)\n{vec3 env_light=vec3(0.65,0.65,0.65);\n#ifdef LIGHTING_3D_MODE\nfloat ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor;\n#endif\nvec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor)\n{highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor;\n#ifdef RENDER_SHADOWS\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\n#else\nlighting_factor=NdotL;\n#endif\nvec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0;\n#if !defined(LIGHTING_3D_MODE)\nconst vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL);\n#endif\ncolor*=intensityFactor;return color;}void main() {\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nif (isOccluded()) {discard;}\n#endif\nvec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor;\n#ifdef LIGHTING_3D_MODE\nlightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color;\n#endif\nvec4 finalColor;\n#ifdef DIFFUSE_SHADED\nvec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor);\n#ifdef HAS_TEXTURE_u_occlusionTexture\nfloat ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao;\n#endif\nfinalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity;\n#else\nMaterial mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0;\n#if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\n#ifdef OCCLUSION_TEXTURE_TRANSFORM\nvec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy;\n#else\nvec2 uv=uv_2f;\n#endif\nao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao;\n#endif\nvec4 emissive=u_emissiveFactor;\n#if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nemissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb);\n#endif\n#ifdef APPLY_LUT_ON_GPU\nfloat emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength;\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);vec3 color_mix=v_color_mix.rgb;\n#ifdef APPLY_LUT_ON_GPU\ncolor_mix=applyLUT(u_lutTexture,color_mix);\n#endif\ncolor=mix(color,color_mix,min(1.0,resEmission));\n#ifdef HAS_ATTRIBUTE_a_color_4f\nfloat distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance);\n#endif\n#endif\nvec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity);\n#endif\n#ifdef FOG\nfinalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w));\n#endif\n#ifdef RENDER_CUTOFF\nfinalColor*=v_cutoff_opacity;\n#endif\n#ifdef INDICATOR_CUTOUT\nfinalColor=applyCutout(finalColor,v_position_height.w);\n#endif\nglFragColor=finalColor;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}";

var modelDepthVert = "in vec3 a_pos_3f;uniform mat4 u_matrix;out highp float v_depth;\n#ifdef MODEL_POSITION_ON_GPU\n#ifdef INSTANCED_ARRAYS\nin vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3;\n#else\nuniform highp mat4 u_instance;\n#endif\nuniform highp mat4 u_node_matrix;\n#endif\nvoid main() {\n#ifdef MODEL_POSITION_ON_GPU\nhighp mat4 instance;\n#ifdef INSTANCED_ARRAYS\ninstance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\n#else\ninstance=u_instance;\n#endif\nvec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);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=mix(u_matrix*pos,AWAY,hidden);\n#else\ngl_Position=u_matrix*vec4(a_pos_3f,1);\n#endif\nv_depth=gl_Position.z/gl_Position.w;}";

var modelDepthFrag = "in highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\nglFragColor=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) {vec3 transformed_normal=vec3(-normal.xy,normal.z);float NDotL=dot(normalize(transformed_normal),u_shadow_direction);float dotScale=min(1.0-NDotL,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#ifdef DEPTH_TEXTURE\nuniform highp sampler2D u_shadowmap_0;uniform highp sampler2D u_shadowmap_1;\n#else\nuniform sampler2D u_shadowmap_0;uniform sampler2D u_shadowmap_1;\n#endif\nuniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;highp float shadow_sample_1(highp vec2 uv,highp float compare) {highp float shadow_depth;\n#ifdef DEPTH_TEXTURE\nshadow_depth=texture(u_shadowmap_1,uv).r;\n#else\nshadow_depth=unpack_depth(texture(u_shadowmap_1,uv))*0.5+0.5;\n#endif\nreturn step(shadow_depth,compare);}highp float shadow_sample_0(highp vec2 uv,highp float compare) {highp float shadow_depth;\n#ifdef DEPTH_TEXTURE\nshadow_depth=texture(u_shadowmap_0,uv).r;\n#else\nshadow_depth=unpack_depth(texture(u_shadowmap_0,uv))*0.5+0.5;\n#endif\nreturn step(shadow_depth,compare);}float shadow_occlusion_1(highp vec4 pos,highp float bias) {highp vec2 uv=pos.xy;return shadow_sample_1(uv,pos.z-bias);}float shadow_occlusion_0(highp vec4 pos,highp float bias) {highp float compare0=pos.z-bias;\n#ifdef 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.w;vec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}light_view_pos0.xyz=light_view_pos0.xyz*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_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {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)*shadow_opacity;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));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy)\n{highp vec2 biasUV=vec2(\npos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);}\n#endif";

const commonDefines = [];
parseUsedPreprocessorDefines(preludeCommon, commonDefines);
parseUsedPreprocessorDefines(preludeVert, commonDefines);
parseUsedPreprocessorDefines(preludeFrag, 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,
    '_prelude_raster_array.glsl': preludeRasterArrayFrag,
    '_prelude_raster_particle.glsl': preludeRasterParticleFrag
};
const defineMap = {};
compile('', preludeTerrainVert);
compile(preludeFogFrag, preludeFogVert);
compile(preludeShadowFrag, preludeShadowVert);
compile(preludeRasterArrayFrag, '');
compile(preludeRasterParticleFrag, '');
const prelude = compile(preludeFrag, preludeVert);
const preludeCommonSource = preludeCommon;
const preludeVertPrecisionQualifiers = `precision highp float;`;
const preludeFragPrecisionQualifiers = `precision mediump float;`;
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),
    rasterParticle: compile(rasterParticleFrag, rasterParticleVert),
    rasterParticleDraw: compile(rasterParticleDrawFrag, rasterParticleDrawVert),
    rasterParticleTexture: compile(rasterParticleTextureFrag, rasterParticleTextureVert),
    rasterParticleUpdate: compile(rasterParticleUpdateFrag, rasterParticleUpdateVert),
    symbol: compile(symbolFrag, symbolVert),
    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),
    snowParticle: compile(snowFrag, snowVert),
    rainParticle: compile(rainFrag, rainVert),
    vignette: compile(vignetteFrag, vignetteVert),
    occlusion: compile(occlusionFrag, occlusionVert)
};
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);
                    }
                }
            }
        }
    }
}
function compile(fragmentSource, vertexSource) {
    const includeRegex = /#include\s+"([^"]+)"/g;
    const pragmaRegex = /#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g;
    const attributeRegex = /(attribute(\S*)|(^\s*|;)in) (highp |mediump |lowp )?([\w]+) ([\w]+)/gm;
    let staticAttributes = vertexSource.match(attributeRegex);
    if (staticAttributes) {
        staticAttributes = staticAttributes.map(str => {
            const tokens = str.split(' ');
            return tokens[tokens.length - 1];
        });
        staticAttributes = [...new Set(staticAttributes)];
    }
    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 '';
    });
    if (vertexSource.includes('flat out')) {
        console.error(`The usage of "flat" qualifier is disallowed, see: https://bugs.webkit.org/show_bug.cgi?id=268071`);
        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 }
in ${ 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 }
    in ${ 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 }
in ${ precision } ${ type } a_${ name };
#endif
`;
        } else if (fragmentPragmas[name]) {
            if (operation === 'define') {
                return `
#ifndef HAS_UNIFORM_u_${ name }
uniform lowp float u_${ name }_t;
in ${ precision } ${ attrType } a_${ name };
out ${ precision } ${ type } ${ name };
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
            } else if (operation === 'initialize') {
                if (unpackType === 'vec4') {
                    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 }
    in ${ precision } ${ type } a_${ name };
    out ${ 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;
in ${ precision } ${ attrType } a_${ name };
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
            } else if (operation === 'define-instanced') {
                if (unpackType === 'mat4') {
                    return `
#ifdef INSTANCED_ARRAYS
in vec4 a_${ name }0;
in vec4 a_${ name }1;
in vec4 a_${ name }2;
in vec4 a_${ name }3;
#else
uniform ${ precision } ${ type } u_${ name };
#endif
`;
                } else {
                    return `
#ifdef INSTANCED_ARRAYS
in ${ 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 (unpackType === 'vec4') {
                    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);
        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 index.bJ(context),
    'u_image': new index.bN(context),
    'u_latrange': new index.bK(context),
    'u_light': new index.bK(context),
    'u_shadow': new index.cz(context),
    'u_highlight': new index.cz(context),
    'u_emissive_strength': new index.bM(context),
    'u_accent': new index.cz(context)
});
const hillshadePrepareUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_image': new index.bN(context),
    'u_dimension': new index.bK(context),
    'u_zoom': new index.bM(context)
});
const hillshadeUniformValues = (painter, tile, layer, matrix) => {
    const shadow = layer.paint.get('hillshade-shadow-color');
    const shadowIgnoreLut = layer.paint.get('hillshade-shadow-color-use-theme').constantOr('default') === 'none';
    const highlight = layer.paint.get('hillshade-highlight-color');
    const highlightIgnoreLut = layer.paint.get('hillshade-highlight-color-use-theme').constantOr('default') === 'none';
    const accent = layer.paint.get('hillshade-accent-color');
    const accentIgnoreLut = layer.paint.get('hillshade-accent-color-use-theme').constantOr('default') === 'none';
    const emissiveStrength = layer.paint.get('hillshade-emissive-strength');
    let azimuthal = index.ai(layer.paint.get('hillshade-illumination-direction'));
    if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') {
        azimuthal -= painter.transform.angle;
    } else if (painter.style && painter.style.enable3dLights()) {
        if (painter.style.directionalLight) {
            const direction = painter.style.directionalLight.properties.get('direction');
            const spherical = index.cb(direction.x, direction.y, direction.z);
            azimuthal = index.ai(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.toRenderColor(shadowIgnoreLut ? null : layer.lut),
        'u_highlight': highlight.toRenderColor(highlightIgnoreLut ? null : layer.lut),
        'u_emissive_strength': emissiveStrength,
        'u_accent': accent.toRenderColor(accentIgnoreLut ? null : layer.lut)
    };
};
const hillshadeUniformPrepareValues = (tileID, dem) => {
    const stride = dem.stride;
    const matrix = index.ab.mat4.create();
    index.ab.mat4.ortho(matrix, 0, index.ag, -index.ag, 0, 0, 1);
    index.ab.mat4.translate(matrix, matrix, [
        0,
        -index.ag,
        0
    ]);
    return {
        'u_matrix': matrix,
        'u_image': 1,
        'u_dimension': [
            stride,
            stride
        ],
        'u_zoom': tileID.overscaledZ
    };
};
function getTileLatRange(painter, tileID) {
    const tilesAtZoom = Math.pow(2, tileID.canonical.z);
    const y = tileID.canonical.y;
    return [
        new index.aa(0, y / tilesAtZoom).toLngLat().lat,
        new index.aa(0, (y + 1) / tilesAtZoom).toLngLat().lat
    ];
}

function drawHillshade(painter, sourceCache, layer, tileIDs) {
    if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent')
        return;
    if (painter.style.disableElevatedTerrain)
        return;
    const context = painter.context;
    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 index.T(context, demImage, gl.R32F, { premultiply: false });
    }
    tile.needsDEMTextureUpload = false;
}
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;
    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 index.T(context, {
            width: tileSize,
            height: tileSize,
            data: null
        }, gl.RGBA8);
        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.linearFloatFilteringSupported())
        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;
}

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;
    }
    setDefault() {
        this.set(this.default);
    }
}
class ClearColor extends BaseValue {
    getDefault() {
        return index.aj.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 index.aj.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) {
        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);
        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;
    }
}

const terrainRasterUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_image0': new index.bN(context),
    'u_skirt_height': new index.bM(context),
    'u_ground_shadow_factor': new index.bL(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 index.bJ(context),
    'u_globe_matrix': new index.bJ(context),
    'u_normalize_matrix': new index.bJ(context),
    'u_merc_matrix': new index.bJ(context),
    'u_zoom_transition': new index.bM(context),
    'u_merc_center': new index.bK(context),
    'u_image0': new index.bN(context),
    'u_grid_matrix': new index.cA(context),
    'u_skirt_height': new index.bM(context),
    'u_far_z_cutoff': new index.bM(context),
    'u_frustum_tl': new index.bL(context),
    'u_frustum_tr': new index.bL(context),
    'u_frustum_br': new index.bL(context),
    'u_frustum_bl': new index.bL(context),
    'u_globe_pos': new index.bL(context),
    'u_globe_radius': new index.bM(context),
    'u_viewport': new index.bK(context)
});
const atmosphereUniforms = context => ({
    'u_frustum_tl': new index.bL(context),
    'u_frustum_tr': new index.bL(context),
    'u_frustum_br': new index.bL(context),
    'u_frustum_bl': new index.bL(context),
    'u_horizon': new index.bM(context),
    'u_transition': new index.bM(context),
    'u_fadeout_range': new index.bM(context),
    'u_color': new index.ca(context),
    'u_high_color': new index.ca(context),
    'u_space_color': new index.ca(context),
    'u_temporal_offset': new index.bM(context),
    'u_horizon_angle': new index.bM(context)
});
const globeRasterUniformValues = (projMatrix, globeMatrix, globeMercatorMatrix, normalizeMatrix, zoomTransition, mercCenter, frustumDirTl, frustumDirTr, frustumDirBr, frustumDirBl, globePosition, globeRadius, viewport, skirtHeight, farZCutoff, 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,
    'u_far_z_cutoff': farZCutoff
});
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
});

class VertexMorphing {
    constructor() {
        this.operations = {};
    }
    newMorphing(key, from, to, now, duration) {
        if (key in this.operations) {
            const op = this.operations[key];
            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;
            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 = index.cC(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 = index.cD(tr);
    const mercatorCenter = [
        index.at(tr.center.lng),
        index.aA(tr.center.lat)
    ];
    const sharedBuffers = painter.globeSharedBuffers;
    const viewport = [
        tr.width * index.q.devicePixelRatio,
        tr.height * index.q.devicePixelRatio
    ];
    const globeMatrix = Float32Array.from(tr.globeMatrix);
    const elevationOptions = { useDenormalizedUpVectorScale: true };
    {
        const tr2 = painter.transform;
        const skirtHeightValue = skirtHeight(tr2.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);
            }
            context.activeTexture.set(gl.TEXTURE0);
            if (tile.texture) {
                tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            }
            const morph = vertexMorphing.getMorphValuesForProxy(coord.key);
            const shaderMode = morph ? SHADER_MORPHING : SHADER_DEFAULT;
            if (morph) {
                index.J(elevationOptions, {
                    morphing: {
                        srcDemTile: morph.from,
                        dstDemTile: morph.to,
                        phase: index.cB(morph.phase)
                    }
                });
            }
            const tileBounds = index.cE(coord.canonical);
            const latitudinalLod = index.cF(tileBounds.getCenter().lat);
            const gridMatrix = index.cG(coord.canonical, tileBounds, latitudinalLod, tr2.worldSize / tr2._pixelsPerMercatorPixel);
            const normalizeMatrix = index.bb(index.cH(coord.canonical));
            const uniformValues = globeRasterUniformValues(tr2.expandedFarZProjMatrix, globeMatrix, globeMercatorMatrix, normalizeMatrix, index.ae(tr2.zoom), mercatorCenter, tr2.frustumCorners.TL, tr2.frustumCorners.TR, tr2.frustumCorners.BR, tr2.frustumCorners.BL, tr2.globeCenterInViewSpace, tr2.globeRadius, viewport, skirtHeightValue, tr2._farZ, 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);
            }
        }
    }
    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) {
            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);
                context.activeTexture.set(gl.TEXTURE0);
                if (tile.texture) {
                    tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
                }
                let poleMatrix = index.cI(z, x, tr);
                const normalizeMatrix = index.bb(index.cH(coord.canonical));
                const drawPole = (program2, vertexBuffer) => program2.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, globeRasterUniformValues(tr.expandedFarZProjMatrix, poleMatrix, poleMatrix, normalizeMatrix, 0, mercatorCenter, tr.frustumCorners.TL, tr.frustumCorners.TR, tr.frustumCorners.BR, tr.frustumCorners.BL, tr.globeCenterInViewSpace, tr.globeRadius, viewport, 0, tr._farZ), '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 = index.ab.mat4.scale(index.ab.mat4.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');
            }
            if (shadowRenderer) {
                modes.push('RENDER_SHADOWS', 'DEPTH_TEXTURE');
                if (shadowRenderer.useNormalOffset) {
                    modes.push('NORMAL_OFFSET');
                }
            }
            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(painter.style, 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);
                }
                context.activeTexture.set(gl.TEXTURE0);
                if (tile.texture) {
                    tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
                }
                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: index.cB(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 skirtHeight(zoom, terrainExaggeration, tileSize) {
    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 index.bJ(context) });
const clippingMaskUniformValues = matrix => ({ 'u_matrix': matrix });

function rasterFade(tile, parentTile, sourceCache, transform, fadeDuration) {
    if (fadeDuration > 0) {
        const now = index.q.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
        });
        const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ);
        const childOpacity = fadeIn && tile.refreshedUponExpiration ? 1 : index.aw(fadeIn ? sinceTile : 1 - sinceParent, 0, 1);
        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 index.D(index.ci(), 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);
    }
}
class ProxySourceCache extends SourceCache {
    constructor(map) {
        const source = create('proxy', {
            type: 'geojson',
            maxzoom: map.transform.maxZoom
        }, new index.D(index.ci(), null), map.style);
        super('proxy', source, false);
        source.setEventedParent(this);
        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) {
        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 !== void 0) {
            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 = {};
    }
}
class ProxiedTileID extends index.aG {
    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 index.cJ {
    constructor(painter, style) {
        super();
        this._debugParams = {
            sortTilesHiZFirst: true,
            disableRenderCache: false
        };
        painter.tp.registerParameter(this._debugParams, ['Terrain'], 'sortTilesHiZFirst', {}, () => {
            this._style.map.triggerRepaint();
        });
        painter.tp.registerParameter(this._debugParams, ['Terrain'], 'disableRenderCache', {}, () => {
            this._style.map.triggerRepaint();
        });
        painter.tp.registerButton(['Terrain'], 'Invalidate Render Cache', () => {
            this.invalidateRenderCache = true;
            this._style.map.triggerRepaint();
        });
        this.painter = painter;
        this.terrainTileForTile = {};
        this.prevTerrainTileForTile = {};
        const [triangleGridArray, triangleGridIndices, skirtIndicesOffset] = createGrid(GRID_DIM + 1);
        const context = painter.context;
        this.gridBuffer = context.createVertexBuffer(triangleGridArray, index.b6.members);
        this.gridIndexBuffer = context.createIndexBuffer(triangleGridIndices);
        this.gridSegments = index.b7.simpleSegment(0, 0, triangleGridArray.length, triangleGridIndices.length);
        this.gridNoSkirtSegments = index.b7.simpleSegment(0, 0, triangleGridArray.length, skirtIndicesOffset);
        this.proxyCoords = [];
        this.proxiedCoords = {};
        this._visibleDemTiles = [];
        this._drapedRenderBatches = [];
        this._sourceTilesOverlap = {};
        this.proxySourceCache = new ProxySourceCache(style.map);
        this.orthoMatrix = index.ab.mat4.create();
        const epsilon = this.painter.transform.projection.name === 'globe' ? 0.015 : 0;
        index.ab.mat4.ortho(this.orthoMatrix, epsilon, index.ag, 0, index.ag, 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) {
        style.on('data', this._onStyleDataEvent.bind(this));
        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 = void 0;
            }
            const terrainProps = style.terrain.properties;
            const isDrapeModeDeferred = style.terrain.drapeRenderMode === DrapeRenderMode.deferred;
            const zoomDependentExaggeration = style.terrain.isZoomDependent();
            this._previousUpdateTimestamp = this.enabled ? this._updateTimestamp : void 0;
            this._updateTimestamp = index.q.now();
            const scope = style.terrain && style.terrain.scope;
            const sourceCacheId = terrainProps.get('source');
            const sourceCache = isDrapeModeDeferred ? this._mockSourceCache : style.getSourceCache(sourceCacheId, scope);
            if (!sourceCache) {
                index.w(`Couldn't find terrain source "${ sourceCacheId }".`);
                return;
            }
            this.sourceCache = sourceCache;
            this._attenuationRange = style.terrain.getAttenuationRange();
            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) {
                    index.w(`Raster DEM source '${ this.sourceCache.id }' is used both for terrain and as layer source.
This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.`);
                }
                const scaledDemTileSize = this.getScaledDemTileSize();
                this.sourceCache.update(transform, scaledDemTileSize, true);
                this.resetTileLookupCache(this.sourceCache.id);
            };
            if (!this.sourceCache.usedForTerrain) {
                this.resetTileLookupCache(this.sourceCache.id);
                this.sourceCache.usedForTerrain = true;
                updateSourceCache();
                this._initializing = true;
            }
            updateSourceCache();
            transform.updateElevation(true, adaptCameraAltitude);
            this.resetTileLookupCache(this.proxySourceCache.id);
            this.proxySourceCache.update(transform);
            this._emptyDEMTextureDirty = true;
            this._previousZoom = transform.zoom;
        } else {
            this._disable();
        }
    }
    calculateExaggeration(transform) {
        if (this._attenuationRange && transform.zoom >= Math.ceil(this._attenuationRange[1])) {
            const terrainStyle2 = this._style.terrain;
            return terrainStyle2.getExaggeration(transform.zoom);
        }
        const previousAltitude = this._previousCameraAltitude;
        const altitude = transform.getFreeCameraOptions().position.z / transform.pixelsPerMeter * transform.worldSize;
        this._previousCameraAltitude = altitude;
        const altitudeDelta = previousAltitude != null ? altitude - previousAltitude : Number.MAX_VALUE;
        if (Math.abs(altitudeDelta) < 2) {
            return this._exaggeration;
        }
        const cameraZoom = transform.zoom;
        const terrainStyle = this._style.terrain;
        if (!this._previousUpdateTimestamp) {
            return terrainStyle.getExaggeration(cameraZoom);
        }
        let zoomDelta = cameraZoom - this._previousZoom;
        const previousUpdateTimestamp = this._previousUpdateTimestamp;
        let z = cameraZoom;
        if (this._evaluationZoom != null) {
            z = this._evaluationZoom;
            if (Math.abs(cameraZoom - z) > 0.5) {
                zoomDelta = 0.5 * (cameraZoom - z + zoomDelta);
            }
            if (zoomDelta * altitudeDelta < 0) {
                z += zoomDelta;
            }
        }
        this._evaluationZoom = z;
        const evaluatedExaggeration = terrainStyle.getExaggeration(z);
        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;
        }
        let interpolateStrength = Math.min(0.1, (this._updateTimestamp - previousUpdateTimestamp) * 0.00375);
        if (fixedExaggeration || evaluatedExaggeration < lowExaggerationTreshold || Math.abs(zoomDelta) < 0.0001) {
            interpolateStrength = Math.min(0.2, interpolateStrength * 4);
        }
        return index.af(this._exaggeration, evaluatedExaggeration, interpolateStrength);
    }
    resetTileLookupCache(sourceCacheID) {
        this._findCoveringTileCache[sourceCacheID] = {};
    }
    attenuationRange() {
        return this._attenuationRange;
    }
    getDemUpscale() {
        const proxyTileSize = this.proxySourceCache.getSource().tileSize;
        return proxyTileSize / GRID_DIM;
    }
    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 = void 0;
            this._previousUpdateTimestamp = void 0;
            this._previousCameraAltitude = void 0;
        }
    }
    // Terrain
    _disable() {
        if (!this.enabled)
            return;
        this.enabled = false;
        this._emptyDEMTextureDirty = true;
        this._sharedDepthStencil = void 0;
        this._evaluationZoom = void 0;
        this._previousUpdateTimestamp = void 0;
        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();
        this.pool.forEach(fbo => fbo.fb.destroy());
        this.pool = [];
        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.enabled ? this._exaggeration : 0;
    }
    get visibleDemTiles() {
        return this._visibleDemTiles;
    }
    get drapeBufferSize() {
        const extent = this.proxySourceCache.getSource().tileSize * 2;
        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) {
            this._initializing = tr._centerAltitude === 0 && this.getAtPointOrZero(index.aa.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) {
                this._assignTerrainTiles(coordinates);
            }
        }
        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;
        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 || '';
        uniforms[`u_dem_tl${ suffix }`] = [
            proxyId.x * demScaleBy % 1,
            proxyId.y * demScaleBy % 1
        ];
        uniforms[`u_dem_scale${ suffix }`] = demScaleBy;
        return true;
    }
    get emptyDEMTexture() {
        return !this._emptyDEMTextureDirty && this._emptyDEMTexture ? this._emptyDEMTexture : this._updateEmptyDEMTexture();
    }
    _getLoadedAreaMinimum() {
        if (!this.enabled)
            return 0;
        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 image = new index.cK({
            width: 1,
            height: 1
        }, new Float32Array([min]));
        this._emptyDEMTextureDirty = false;
        let texture = this._emptyDEMTexture;
        if (!texture) {
            texture = this._emptyDEMTexture = new index.T(context, image, gl.R32F, { premultiply: false });
        } else {
            texture.update(image, { premultiply: false });
        }
        return texture;
    }
    // useDepthForOcclusion: Pre-rendered depth texture is used for occlusion
    // 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();
        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 = tile2 => {
            if (!tile2 || !tile2.demTexture) {
                return gl.NEAREST;
            }
            return this.painter.linearFloatFilteringSupported() ? gl.LINEAR : gl.NEAREST;
        };
        const setDemSizeUniform = demTexture2 => {
            uniforms['u_dem_size'] = demTexture2.size[0] === 1 ? 1 : demTexture2.size[0] - 2;
        };
        let demTexture = null;
        if (!this.enabled) {
            demTexture = this.emptyDEMTexture;
        } else if (prevDemTile && demTile) {
            demTexture = demTile.demTexture;
            context.activeTexture.set(gl.TEXTURE4);
            prevDemTile.demTexture.bind(filteringForDemTile(prevDemTile), gl.CLAMP_TO_EDGE);
            uniforms['u_dem_lerp'] = morphingPhase;
        } else {
            demTile = this.terrainTileForTile[tile.tileID.key];
            demTexture = this._prepareDemTileUniforms(tile, demTile, uniforms) ? demTile.demTexture : this.emptyDEMTexture;
        }
        context.activeTexture.set(gl.TEXTURE2);
        if (demTexture) {
            setDemSizeUniform(demTexture);
            demTexture.bind(filteringForDemTile(demTile), gl.CLAMP_TO_EDGE);
        }
        this.painter.setupDepthForOcclusion(options && options.useDepthForOcclusion, program, uniforms);
        if (options && options.useMeterToDem && demTile) {
            const meterToDEM = (1 << demTile.tileID.canonical.z) * index.bH(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 globeUniforms2 = this.globeUniformValues(this.painter.transform, tile.tileID.canonical, options && options.useDenormalizedUpVectorScale);
            program.setGlobeUniformValues(context, globeUniforms2);
        }
    }
    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, index.ag, 0),
            'u_tile_br_up': projection.upVector(id, index.ag, index.ag),
            'u_tile_bl_up': projection.upVector(id, 0, index.ag),
            'u_tile_up_scale': useDenormalizedUpVectorScale ? index.cL(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];
        const drapedLayerBatch = this._drapedRenderBatches.shift();
        const layerIds = painter.style.order;
        const accumulatedDrapes = [];
        let poolIndex = 0;
        for (const proxy of proxies) {
            const tile = proxySourceCache.getTileByID(proxy.proxyTileKey);
            const renderCacheIndex = proxySourceCache.proxyCachedFBO[proxy.key] ? proxySourceCache.proxyCachedFBO[proxy.key][startLayerIndex] : void 0;
            const fbo = renderCacheIndex !== void 0 ? proxySourceCache.renderCache[renderCacheIndex] : this.pool[poolIndex++];
            const useRenderCache = renderCacheIndex !== void 0;
            tile.texture = fbo.tex;
            if (useRenderCache && !fbo.dirty) {
                accumulatedDrapes.push(tile.tileID);
                continue;
            }
            context.bindFramebuffer.set(fbo.fb.framebuffer);
            this.renderedToTile = false;
            if (fbo.dirty) {
                context.clear({
                    color: index.aj.transparent,
                    stencil: 0
                });
                fbo.dirty = false;
            }
            let currentStencilSource;
            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;
                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);
            }
        }
        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;
        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;
        const preparedTiles = this._visibleDemTiles.filter(tile => tile.dem).map(tile => {
            const id = tile.tileID;
            const tiles = 1 << id.overscaledZ;
            const {x, y} = id.canonical;
            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;
            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 index.T(context, {
            width: bufferSize[0],
            height: bufferSize[1],
            data: null
        }, gl.RGBA8);
        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 === void 0) {
            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) {
            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() {
        if (this._debugParams.disableRenderCache) {
            return true;
        }
        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 === 'hillshade') {
                return !isHidden && layer.shouldRedrape();
            }
            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;
            const widthExpression = layer.widthExpression();
            if (!(widthExpression instanceof index.a9))
                continue;
            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;
            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() {
        this._style.updateDrapeFirstLayers();
        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 layer2 = this._style._mergedLayers[layerIds[currentLayer]];
            if (layer2.isHidden(this.painter.transform.zoom)) {
                continue;
            }
            if (!this._style.isLayerDraped(layer2)) {
                if (layer2.type === 'fill-extrusion') {
                    this._pendingGroundEffectLayers.push(currentLayer);
                }
                if (batchStart !== void 0) {
                    batches.push({
                        start: batchStart,
                        end: currentLayer - 1
                    });
                    batchStart = void 0;
                }
                continue;
            }
            if (batchStart === void 0) {
                batchStart = currentLayer;
            }
        }
        if (batchStart !== void 0) {
            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) {
                index.w('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] !== void 0) {
                const prev = previousProxyToSource[proxy.key];
                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;
                }
                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;
                }
                let index = psc.renderCachePool.pop();
                if (index === void 0 && psc.renderCache.length < RENDER_CACHE_MAX_SIZE) {
                    index = psc.renderCache.length;
                    psc.renderCache.push(this._createFBO());
                }
                if (index !== void 0) {
                    psc.proxyCachedFBO[id.key] = {};
                    psc.proxyCachedFBO[id.key][batch.start] = index;
                    psc.renderCache[index].dirty = true;
                }
            }
        }
        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 (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;
        }
        if (this._overlapStencilType === 'Clip') {
            this._overlapStencilMode.ref = this.painter._tileClippingMaskIDs[id.key];
        }
        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
        ];
        index.ab.vec4.transformMat4(far, far, transform.pixelMatrixInverse);
        index.ab.vec4.scale(far, far, 1 / far[3]);
        far[0] /= transform.worldSize;
        far[1] /= transform.worldSize;
        const camera = transform._camera.position;
        const mercatorZScale = index.bH(1, transform.center.lat);
        const p = [
            camera[0],
            camera[1],
            camera[2] / mercatorZScale,
            0
        ];
        const dir = index.ab.vec3.subtract([], far.slice(0, 3), p);
        index.ab.vec3.normalize(dir, dir);
        const exaggeration = this._exaggeration;
        const distanceAlongRay = this.raycast(p, dir, exaggeration);
        if (distanceAlongRay === null || !distanceAlongRay)
            return null;
        index.ab.vec3.scaleAndAdd(p, p, dir, distanceAlongRay);
        p[3] = p[2];
        p[2] *= mercatorZScale;
        return p;
    }
    _setupProxiedCoordsForOrtho(sourceCache, sourceCoords, previousProxyToSource) {
        if (sourceCache.getSource() instanceof index.aJ) {
            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;
        const proxiesToSort = /* @__PURE__ */
        new Set();
        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);
            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 {
                    array.splice(array.length - 1, 0, id);
                }
                const arr = this.proxyToSource[proxy.tileID.key][sourceCache.id];
                if (!proxiesToSort.has(arr)) {
                    proxiesToSort.add(arr);
                }
                coords.push(id);
                hasOverlap = true;
            }
        }
        this._sourceTilesOverlap[sourceCache.id] = hasOverlap;
        if (hasOverlap && this._debugParams.sortTilesHiZFirst) {
            for (const arr of proxiesToSort) {
                arr.sort((a, b) => {
                    return b.overscaledZ - a.overscaledZ;
                });
            }
        }
    }
    _setupProxiedCoordsForImageSource(sourceCache, sourceCoords, previousProxyToSource) {
        if (!sourceCache.getSource().loaded())
            return;
        const coords = this.proxiedCoords[sourceCache.id] = [];
        const proxys = this.proxyCoords;
        const imageSource = sourceCache.getSource();
        const tileID = imageSource.tileID;
        if (!tileID)
            return;
        const anchor = new index.P(tileID.x, tileID.y)._div(1 << tileID.z);
        const aabb = imageSource.coordinates.map(index.aa.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 index.P(Number.MAX_VALUE, Number.MAX_VALUE),
            max: new index.P(-Number.MAX_VALUE, -Number.MAX_VALUE)
        });
        const tileOutsideImage = (tileID2, imageTileID) => {
            const x = tileID2.wrap + tileID2.canonical.x / (1 << tileID2.canonical.z);
            const y = tileID2.canonical.y / (1 << tileID2.canonical.z);
            const d = index.ag / (1 << tileID2.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;
                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 = index.ab.mat4.create();
            let size, xOffset, yOffset;
            const wrap = tile.tileID.wrap - proxyTileID.wrap << proxyTileID.overscaledZ;
            if (scale > 0) {
                size = index.ag >> scale;
                xOffset = size * ((tile.tileID.canonical.x << scale) - proxyTileID.canonical.x + wrap);
                yOffset = size * ((tile.tileID.canonical.y << scale) - proxyTileID.canonical.y);
            } else {
                size = index.ag << -scale;
                xOffset = index.ag * (tile.tileID.canonical.x - (proxyTileID.canonical.x + wrap << -scale));
                yOffset = index.ag * (tile.tileID.canonical.y - (proxyTileID.canonical.y << -scale));
            }
            index.ab.mat4.ortho(matrix, 0, size, 0, size, 0, 1);
            index.ab.mat4.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 index.aG(z, tileID.wrap, maxzoom, tileID.canonical.x >> downscale, tileID.canonical.y >> downscale);
                } else if (downscale !== 0) {
                    z = maxzoom;
                    sourceTileID = new index.aG(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 = key2 => {
            path.forEach(id => {
                lookup[id] = key2;
            });
            path.length = 0;
        };
        for (z = z - 1; z >= minzoom && !(tile && tile.hasData()); z--) {
            if (tile) {
                pathToLookup(tile.tileID.key);
            }
            const id = sourceTileID.calculateScaledKey(z);
            tile = sourceCache.getTileByID(id);
            if (tile && tile.hasData())
                break;
            const key2 = lookup[id];
            if (key2 === null) {
                break;
            } else if (key2 !== void 0) {
                tile = sourceCache.getTileByID(key2);
                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 index.P(cameraCoordinate.x, cameraCoordinate.y);
    tileIDs.sort((a, b) => {
        if (b.overscaledZ - a.overscaledZ)
            return b.overscaledZ - a.overscaledZ;
        const aPoint = new index.P(a.canonical.x + (1 << a.canonical.z) * a.wrap, a.canonical.y);
        const bPoint = new index.P(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);
    });
}
function createGrid(count) {
    const boundsArray = new index.b4();
    const indexArray = new index.aU();
    const size = count + 2;
    boundsArray.reserve(size * size);
    indexArray.reserve((size - 1) * (size - 1) * 2);
    const step = index.ag / (count - 1);
    const gridBound = index.ag + step / 2;
    const bound = gridBound + step;
    const skirtOffset = 24575;
    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 = index.aw(Math.round(x), 0, index.ag);
            const yi = index.aw(Math.round(y), 0, index.ag);
            boundsArray.emplaceBack(xi + offset, yi);
        }
    }
    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);
        }
    }
    [
        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 index.bN(context),
    'u_dem_prev': new index.bN(context),
    'u_dem_tl': new index.bK(context),
    'u_dem_scale': new index.bM(context),
    'u_dem_tl_prev': new index.bK(context),
    'u_dem_scale_prev': new index.bM(context),
    'u_dem_size': new index.bM(context),
    'u_dem_lerp': new index.bM(context),
    'u_exaggeration': new index.bM(context),
    'u_depth': new index.bN(context),
    'u_depth_size_inv': new index.bK(context),
    'u_depth_range_unpack': new index.bK(context),
    'u_occluder_half_size': new index.bM(context),
    'u_occlusion_depth_offset': new index.bM(context),
    'u_meter_to_dem': new index.bM(context),
    'u_label_plane_matrix_inv': new index.bJ(context)
});
function defaultTerrainUniforms() {
    return {
        'u_dem': 2,
        'u_dem_prev': 4,
        'u_dem_tl': [
            0,
            0
        ],
        'u_dem_tl_prev': [
            0,
            0
        ],
        'u_dem_scale': 0,
        'u_dem_scale_prev': 0,
        'u_dem_size': 0,
        'u_dem_lerp': 1,
        'u_depth': 3,
        'u_depth_size_inv': [
            0,
            0
        ],
        'u_depth_range_unpack': [
            0,
            1
        ],
        'u_occluder_half_size': 16,
        'u_occlusion_depth_offset': -0.0001,
        'u_exaggeration': 0
    };
}
const globeUniforms = context => ({
    'u_tile_tl_up': new index.bL(context),
    'u_tile_tr_up': new index.bL(context),
    'u_tile_br_up': new index.bL(context),
    'u_tile_bl_up': new index.bL(context),
    'u_tile_up_scale': new index.bM(context)
});

const fogUniforms = context => ({
    'u_fog_matrix': new index.bJ(context),
    'u_fog_range': new index.bK(context),
    'u_fog_color': new index.ca(context),
    'u_fog_horizon_blend': new index.bM(context),
    'u_fog_vertical_limit': new index.bK(context),
    'u_fog_temporal_offset': new index.bM(context),
    'u_frustum_tl': new index.bL(context),
    'u_frustum_tr': new index.bL(context),
    'u_frustum_br': new index.bL(context),
    'u_frustum_bl': new index.bL(context),
    'u_globe_pos': new index.bL(context),
    'u_globe_radius': new index.bM(context),
    'u_globe_transition': new index.bM(context),
    'u_is_globe': new index.bN(context),
    'u_viewport': new index.bK(context)
});
const fogUniformValues = (painter, fog, tileID, fogOpacity, frustumDirTl, frustumDirTr, frustumDirBr, frustumDirBl, globePosition, globeRadius, viewport, fogMatrix) => {
    const tr = painter.transform;
    const ignoreLUT = fog.properties.get('color-use-theme') === 'none';
    const fogColor = fog.properties.get('color').toRenderColor(ignoreLUT ? null : painter.style.getLut(fog.scope)).toArray01();
    fogColor[3] = fogOpacity;
    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': index.ae(tr.zoom),
        'u_is_globe': +(tr.projection.name === 'globe')
    };
};

const lightsUniforms = context => ({
    'u_lighting_ambient_color': new index.bL(context),
    'u_lighting_directional_dir': new index.bL(context),
    'u_lighting_directional_color': new index.bL(context),
    'u_ground_radiance': new index.bL(context)
});
function calculateAmbientDirectionalFactor(dir, normal, dirColor) {
    const NdotL = index.ab.vec3.dot(normal, dir);
    const factorReductionMax = 0.3;
    const dirLuminance = index.ab.vec3.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;
    };
    const ambientDirectionalFactor = lerp(directionalFactorMin, 1, Math.min(NdotL + 1, 1));
    const verticalFactorMin = 0.92;
    const verticalFactor = lerp(verticalFactorMin, 1, Math.asin(index.aw(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
    ];
    index.ab.vec3.scale(ambientContrib, ambientColor.slice(0, 3), ambientDirectionalFactor);
    const dirConrib = [
        0,
        0,
        0
    ];
    index.ab.vec3.scale(dirConrib, dirColor.slice(0, 3), dir[2]);
    const radiance = [
        0,
        0,
        0
    ];
    index.ab.vec3.add(radiance, ambientContrib, dirConrib);
    return index.cf(radiance);
}
const lightsUniformValues = (directional, ambient, style) => {
    const direction = directional.properties.get('direction');
    const dirIgnoreLut = directional.properties.get('color-use-theme') === 'none';
    const directionalColor = directional.properties.get('color').toRenderColor(dirIgnoreLut ? null : style.getLut(directional.scope)).toArray01();
    const directionalIntensity = directional.properties.get('intensity');
    const ambIgnoreLut = ambient.properties.get('color-use-theme') === 'none';
    const ambientColor = ambient.properties.get('color').toRenderColor(ambIgnoreLut ? null : style.getLut(ambient.scope)).toArray01();
    const ambientIntensity = ambient.properties.get('intensity');
    const dirVec = [
        direction.x,
        direction.y,
        direction.z
    ];
    const ambientColorLinear = index.cM(ambientColor, ambientIntensity);
    const directionalColorLinear = index.cM(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 debugWireframe2DLayerProgramNames = [
    'fill',
    'fillOutline',
    'fillPattern',
    'line',
    'linePattern',
    'background',
    'backgroundPattern',
    'hillshade',
    'raster'
];
const debugWireframe3DLayerProgramNames = [
    'stars',
    'rainParticle',
    'snowParticle',
    'fillExtrusion',
    'fillExtrusionGroundEffect',
    'model',
    'symbol'
];
const instancingUniforms = context => ({ 'u_instanceID': new index.bN(context) });
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 dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];
        const allAttrInfo = (source.staticAttributes || []).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 += `
${ includeMap[include] }`;
        }
        fragmentSource += `
${ source.fragmentSource }`;
        let vertexSource = version + defines.concat(preludeVertPrecisionQualifiers, preludeCommonSource, prelude.vertexSource).join('\n');
        for (const include of source.vertexIncludes) {
            vertexSource += `
${ includeMap[include] }`;
        }
        this.forceManualRenderingForInstanceIDShaders = context.forceManualRenderingForInstanceIDShaders && source.vertexSource.indexOf('gl_InstanceID') !== -1;
        if (this.forceManualRenderingForInstanceIDShaders) {
            vertexSource += `
uniform int u_instanceID;
`;
        }
        vertexSource += `
${ source.vertexSource }`;
        if (this.forceManualRenderingForInstanceIDShaders) {
            vertexSource = vertexSource.replaceAll('gl_InstanceID', 'u_instanceID');
        }
        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]) {
                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 (this.forceManualRenderingForInstanceIDShaders) {
            this.instancingUniforms = instancingUniforms(context);
        }
        if (fixedDefines.includes('TERRAIN') || name.indexOf('symbol') !== -1 || name.indexOf('circle') !== -1) {
            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 = ((() => {
            if (wireframe.terrain && (this.name === 'terrainRaster' || this.name === 'globeRaster')) {
                return true;
            }
            const drapingInProgress = painter._terrain && painter._terrain.renderingToTexture;
            if (wireframe.layers2D && !drapingInProgress) {
                if (debugWireframe2DLayerProgramNames.includes(this.name)) {
                    return true;
                }
            }
            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');
        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 });
        }
        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();
        context.setColorMode(new ColorMode([
            gl.ONE,
            gl.ONE_MINUS_SRC_ALPHA,
            gl.ZERO,
            gl.ONE
        ], index.aj.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;
        const offset = segment.primitiveOffset * 3 * 2 * 2;
        if (this.forceManualRenderingForInstanceIDShaders) {
            const renderInstanceCount = instanceCount ? instanceCount : 1;
            for (let i = 0; i < renderInstanceCount; ++i) {
                debugProgram.instancingUniforms['u_instanceID'].set(this.program, 'u_instanceID', i);
                gl.drawElements(gl.LINES, count, gl.UNSIGNED_SHORT, offset);
            }
        } else {
            if (instanceCount && instanceCount > 1) {
                gl.drawElementsInstanced(gl.LINES, count, gl.UNSIGNED_SHORT, offset, instanceCount);
            } else {
                gl.drawElements(gl.LINES, count, gl.UNSIGNED_SHORT, offset);
            }
        }
        indexBuffer.bind();
        context.program.set(this.program);
        context.setDepthMode(depthMode);
        context.setStencilMode(stencilMode);
        context.setColorMode(colorMode);
    }
    checkUniforms(name, define, uniforms) {
        if (this.fixedDefines.includes(define)) {
            for (const key of Object.keys(uniforms)) {
                if (!uniforms[key].initialized) {
                    throw new Error(`Program '${ this.name }', from draw '${ name }': uniform ${ key } not set but required by ${ define } being defined`);
                }
            }
        }
    }
    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 });
        }
        const primitiveSize = {
            [gl.POINTS]: 1,
            [gl.LINES]: 2,
            [gl.TRIANGLES]: 3,
            [gl.LINE_STRIP]: 1
        }[drawMode];
        this.checkUniforms(layerID, 'RENDER_SHADOWS', this.shadowUniforms);
        const vertexAttribDivisorValue = instanceCount && instanceCount > 0 ? 1 : void 0;
        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 (this.forceManualRenderingForInstanceIDShaders) {
                const renderInstanceCount = instanceCount ? instanceCount : 1;
                for (let i = 0; i < renderInstanceCount; ++i) {
                    this.instancingUniforms['u_instanceID'].set(this.program, 'u_instanceID', i);
                    if (indexBuffer) {
                        gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2);
                    } else {
                        gl.drawArrays(drawMode, segment.vertexOffset, segment.vertexLength);
                    }
                }
            } else {
                if (instanceCount && instanceCount > 1) {
                    gl.drawElementsInstanced(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2, instanceCount);
                } else if (indexBuffer) {
                    gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2);
                } else {
                    gl.drawArrays(drawMode, segment.vertexOffset, segment.vertexLength);
                }
            }
            if (drawMode === gl.TRIANGLES && indexBuffer) {
                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 ? tile.imageAtlasTexture.size : [
            0,
            0
        ],
        'u_tile_units_to_pixels': 1 / index.ar(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, patternPosition, painter, isViewport, tile) {
    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': patternPosition.tl,
        'u_pattern_br': patternPosition.br,
        'u_texsize': [
            width,
            height
        ],
        'u_pattern_size': patternPosition.displaySize,
        'u_pattern_units_to_pixels': isViewport ? [
            painter.transform.width,
            -1 * painter.transform.height
        ] : [
            1 / index.ar(tile, 1, painter.transform.tileZoom),
            1 / index.ar(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 fillExtrusionAlignmentType = {
    'terrain': 0,
    'flat': 1
};
const fillExtrusionUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_lightpos': new index.bL(context),
    'u_lightintensity': new index.bM(context),
    'u_lightcolor': new index.bL(context),
    'u_vertical_gradient': new index.bM(context),
    'u_opacity': new index.bM(context),
    'u_edge_radius': new index.bM(context),
    'u_width_scale': new index.bM(context),
    'u_ao': new index.bK(context),
    'u_height_type': new index.bN(context),
    'u_base_type': new index.bN(context),
    // globe uniforms:
    'u_tile_id': new index.bL(context),
    'u_zoom_transition': new index.bM(context),
    'u_inv_rot_matrix': new index.bJ(context),
    'u_merc_center': new index.bK(context),
    'u_up_dir': new index.bL(context),
    'u_height_lift': new index.bM(context),
    'u_flood_light_color': new index.bL(context),
    'u_vertical_scale': new index.bM(context),
    'u_flood_light_intensity': new index.bM(context),
    'u_ground_shadow_factor': new index.bL(context)
});
const fillExtrusionDepthUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_edge_radius': new index.bM(context),
    'u_width_scale': new index.bM(context),
    'u_vertical_scale': new index.bM(context),
    'u_height_type': new index.bN(context),
    'u_base_type': new index.bN(context)
});
const fillExtrusionPatternUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_lightpos': new index.bL(context),
    'u_lightintensity': new index.bM(context),
    'u_lightcolor': new index.bL(context),
    'u_vertical_gradient': new index.bM(context),
    'u_height_factor': new index.bM(context),
    'u_edge_radius': new index.bM(context),
    'u_width_scale': new index.bM(context),
    'u_ao': new index.bK(context),
    'u_height_type': new index.bN(context),
    'u_base_type': new index.bN(context),
    // globe uniforms:
    'u_tile_id': new index.bL(context),
    'u_zoom_transition': new index.bM(context),
    'u_inv_rot_matrix': new index.bJ(context),
    'u_merc_center': new index.bK(context),
    'u_up_dir': new index.bL(context),
    'u_height_lift': new index.bM(context),
    // pattern uniforms
    'u_image': new index.bN(context),
    'u_texsize': new index.bK(context),
    'u_pixel_coord_upper': new index.bK(context),
    'u_pixel_coord_lower': new index.bK(context),
    'u_tile_units_to_pixels': new index.bM(context),
    'u_opacity': new index.bM(context)
});
const fillExtrusionGroundEffectUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_opacity': new index.bM(context),
    'u_ao_pass': new index.bM(context),
    'u_meter_to_tile': new index.bM(context),
    'u_ao': new index.bK(context),
    'u_flood_light_intensity': new index.bM(context),
    'u_flood_light_color': new index.bL(context),
    'u_attenuation': new index.bM(context),
    'u_edge_radius': new index.bM(context),
    'u_fb': new index.bN(context),
    'u_fb_size': new index.bM(context),
    'u_dynamic_offset': new index.bM(context)
});
const identityMatrix$2 = index.ab.mat4.create();
const fillExtrusionUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, aoIntensityRadius, edgeRadius, lineWidthScale, coord, heightLift, heightAlignment, baseAlignment, 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 = index.ab.mat3.create();
    const anchor = light.properties.get('anchor');
    if (anchor === 'viewport') {
        index.ab.mat3.fromRotation(lightMat, -painter.transform.angle);
        index.ab.vec3.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_height_type': fillExtrusionAlignmentType[heightAlignment],
        'u_base_type': fillExtrusionAlignmentType[baseAlignment],
        'u_ao': aoIntensityRadius,
        'u_edge_radius': edgeRadius,
        'u_width_scale': lineWidthScale,
        '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 index.bT(0, 0, 0), mercatorCenter[0] * index.ag, mercatorCenter[1] * index.ag);
        uniformValues['u_height_lift'] = heightLift;
    }
    return uniformValues;
};
const fillExtrusionDepthUniformValues = (matrix, edgeRadius, lineWidthScale, verticalScale, heightAlignment, baseAlignment) => {
    return {
        'u_matrix': matrix,
        'u_edge_radius': edgeRadius,
        'u_width_scale': lineWidthScale,
        'u_vertical_scale': verticalScale,
        'u_height_type': fillExtrusionAlignmentType[heightAlignment],
        'u_base_type': fillExtrusionAlignmentType[baseAlignment]
    };
};
const fillExtrusionPatternUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, aoIntensityRadius, edgeRadius, lineWidthScale, coord, tile, heightLift, heightAlignment, baseAlignment, zoomTransition, mercatorCenter, invMatrix, floodLightColor, verticalScale) => {
    const uniformValues = fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, aoIntensityRadius, edgeRadius, lineWidthScale, coord, heightLift, heightAlignment, baseAlignment, zoomTransition, mercatorCenter, invMatrix, floodLightColor, verticalScale, 1, [
        0,
        0,
        0
    ]);
    const heightFactorUniform = { 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 };
    return index.l(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,
        'u_dynamic_offset': 1
    };
    return uniformValues;
};

const fillUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_emissive_strength': new index.bM(context)
});
const fillPatternUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_emissive_strength': new index.bM(context),
    'u_image': new index.bN(context),
    'u_texsize': new index.bK(context),
    'u_pixel_coord_upper': new index.bK(context),
    'u_pixel_coord_lower': new index.bK(context),
    'u_tile_units_to_pixels': new index.bM(context)
});
const fillOutlineUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_emissive_strength': new index.bM(context),
    'u_world': new index.bK(context)
});
const fillOutlinePatternUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_emissive_strength': new index.bM(context),
    'u_world': new index.bK(context),
    'u_image': new index.bN(context),
    'u_texsize': new index.bK(context),
    'u_pixel_coord_upper': new index.bK(context),
    'u_pixel_coord_lower': new index.bK(context),
    'u_tile_units_to_pixels': new index.bM(context)
});
const fillUniformValues = (matrix, emissiveStrength) => ({
    'u_matrix': matrix,
    'u_emissive_strength': emissiveStrength
});
const fillPatternUniformValues = (matrix, emissiveStrength, painter, tile) => index.l(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) => index.l(fillPatternUniformValues(matrix, emissiveStrength, painter, tile), { 'u_world': drawingBufferSize });

const collisionUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_camera_to_center_distance': new index.bM(context),
    'u_extrude_scale': new index.bK(context)
});
const collisionCircleUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_inv_matrix': new index.bJ(context),
    'u_camera_to_center_distance': new index.bM(context),
    'u_viewport_size': new index.bK(context)
});
const collisionUniformValues = (matrix, transform, tile, projection) => {
    const pixelRatio = index.ag / 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 index.cz(context),
    'u_matrix': new index.bJ(context),
    'u_overlay': new index.bN(context),
    'u_overlay_scale': new index.bM(context)
});
const debugUniformValues = (matrix, color, scaleRatio = 1) => ({
    'u_matrix': matrix,
    'u_color': color.toRenderColor(null),
    'u_overlay': 0,
    'u_overlay_scale': scaleRatio
});

const heatmapUniforms = context => ({
    'u_extrude_scale': new index.bM(context),
    'u_intensity': new index.bM(context),
    'u_matrix': new index.bJ(context),
    'u_inv_rot_matrix': new index.bJ(context),
    'u_merc_center': new index.bK(context),
    'u_tile_id': new index.bL(context),
    'u_zoom_transition': new index.bM(context),
    'u_up_dir': new index.bL(context)
});
const heatmapTextureUniforms = context => ({
    'u_image': new index.bN(context),
    'u_color_ramp': new index.bN(context),
    'u_opacity': new index.bM(context)
});
const identityMatrix$1 = index.ab.mat4.create();
const heatmapUniformValues = (painter, coord, tile, invMatrix, mercatorCenter, zoom, intensity) => {
    const transform = painter.transform;
    const isGlobe = transform.projection.name === 'globe';
    const extrudeScale = isGlobe ? index.cN(transform.zoom, coord.canonical) * transform._pixelsPerMercatorPixel : index.ar(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'] = index.ae(transform.zoom);
        const x = mercatorCenter[0] * index.ag;
        const y = mercatorCenter[1] * index.ag;
        values['u_up_dir'] = transform.projection.upVector(new index.bT(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')
    };
};

function computeRasterColorMix(colorRampRes, [mixR, mixG, mixB, mixA], [min, max]) {
    if (min === max)
        return [
            0,
            0,
            0,
            0
        ];
    const factor = 255 * (colorRampRes - 1) / (colorRampRes * (max - min));
    return [
        mixR * factor,
        mixG * factor,
        mixB * factor,
        mixA * factor
    ];
}
function computeRasterColorOffset(colorRampRes, offset, [min, max]) {
    if (min === max)
        return 0;
    return 0.5 / colorRampRes + (offset - min) * (colorRampRes - 1) / (colorRampRes * (max - min));
}

const rasterUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_normalize_matrix': new index.bJ(context),
    'u_globe_matrix': new index.bJ(context),
    'u_merc_matrix': new index.bJ(context),
    'u_grid_matrix': new index.cA(context),
    'u_tl_parent': new index.bK(context),
    'u_scale_parent': new index.bM(context),
    'u_fade_t': new index.bM(context),
    'u_opacity': new index.bM(context),
    'u_image0': new index.bN(context),
    'u_image1': new index.bN(context),
    'u_brightness_low': new index.bM(context),
    'u_brightness_high': new index.bM(context),
    'u_saturation_factor': new index.bM(context),
    'u_contrast_factor': new index.bM(context),
    'u_spin_weights': new index.bL(context),
    'u_perspective_transform': new index.bK(context),
    'u_raster_elevation': new index.bM(context),
    'u_zoom_transition': new index.bM(context),
    'u_merc_center': new index.bK(context),
    'u_cutoff_params': new index.ca(context),
    'u_colorization_mix': new index.ca(context),
    'u_colorization_offset': new index.bM(context),
    'u_color_ramp': new index.bN(context),
    'u_texture_offset': new index.bK(context),
    'u_texture_res': new index.bK(context),
    'u_emissive_strength': new index.bM(context)
});
const rasterUniformValues = (matrix, normalizeMatrix, globeMatrix, mercMatrix, gridMatrix, parentTL, zoomTransition, mercatorCenter, cutoffParams, parentScaleBy, fade, layer, perspectiveTransform, elevation, colorRampUnit, colorMix, colorOffset, colorRange, tileSize, buffer, emissiveStrength) => ({
    'u_matrix': matrix,
    'u_normalize_matrix': normalizeMatrix,
    'u_globe_matrix': globeMatrix,
    'u_merc_matrix': mercMatrix,
    'u_grid_matrix': gridMatrix,
    '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': index.cO(layer.paint.get('raster-saturation')),
    'u_contrast_factor': index.cP(layer.paint.get('raster-contrast')),
    'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate')),
    'u_perspective_transform': perspectiveTransform,
    'u_raster_elevation': elevation,
    'u_zoom_transition': zoomTransition,
    'u_merc_center': mercatorCenter,
    'u_cutoff_params': cutoffParams,
    'u_colorization_mix': computeRasterColorMix(index.cQ, colorMix, colorRange),
    'u_colorization_offset': computeRasterColorOffset(index.cQ, colorOffset, colorRange),
    'u_color_ramp': colorRampUnit,
    'u_texture_offset': [
        buffer / (tileSize + 2 * buffer),
        tileSize / (tileSize + 2 * buffer)
    ],
    'u_texture_res': [
        tileSize + 2 * buffer,
        tileSize + 2 * buffer
    ],
    'u_emissive_strength': emissiveStrength
});
const rasterPoleUniformValues = (matrix, normalizeMatrix, globeMatrix, zoomTransition, fade, layer, perspectiveTransform, elevation, colorRampUnit, colorMix, colorOffset, colorRange, emissiveStrength) => rasterUniformValues(matrix, normalizeMatrix, globeMatrix, new Float32Array(16), new Float32Array(9), [
    0,
    0
], zoomTransition, [
    0,
    0
], [
    0,
    0,
    0,
    0
], 1, fade, layer, perspectiveTransform || [
    0,
    0
], elevation, colorRampUnit, colorMix, colorOffset, colorRange, 1, 0, emissiveStrength);
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
    ];
}

const RASTER_PARTICLE_POS_OFFSET = 0.05;
const RASTER_PARTICLE_POS_SCALE = 1 + 2 * RASTER_PARTICLE_POS_OFFSET;
const rasterParticleUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_normalize_matrix': new index.bJ(context),
    'u_globe_matrix': new index.bJ(context),
    'u_merc_matrix': new index.bJ(context),
    'u_grid_matrix': new index.cA(context),
    'u_tl_parent': new index.bK(context),
    'u_scale_parent': new index.bM(context),
    'u_fade_t': new index.bM(context),
    'u_opacity': new index.bM(context),
    'u_image0': new index.bN(context),
    'u_image1': new index.bN(context),
    'u_raster_elevation': new index.bM(context),
    'u_zoom_transition': new index.bM(context),
    'u_merc_center': new index.bK(context),
    'u_cutoff_params': new index.ca(context)
});
const rasterParticleUniformValues = (matrix, normalizeMatrix, globeMatrix, mercMatrix, gridMatrix, parentTL, zoomTransition, mercatorCenter, cutoffParams, parentScaleBy, fade, elevation) => ({
    'u_matrix': matrix,
    'u_normalize_matrix': normalizeMatrix,
    'u_globe_matrix': globeMatrix,
    'u_merc_matrix': mercMatrix,
    'u_grid_matrix': gridMatrix,
    'u_tl_parent': parentTL,
    'u_scale_parent': parentScaleBy,
    'u_fade_t': fade.mix,
    'u_opacity': fade.opacity,
    'u_image0': 0,
    'u_image1': 1,
    'u_raster_elevation': elevation,
    'u_zoom_transition': zoomTransition,
    'u_merc_center': mercatorCenter,
    'u_cutoff_params': cutoffParams
});
const rasterParticleTextureUniforms = context => ({
    'u_texture': new index.bN(context),
    'u_opacity': new index.bM(context)
});
const rasterParticleTextureUniformValues = (textureUnit, opacity) => ({
    'u_texture': textureUnit,
    'u_opacity': opacity
});
const rasterParticleDrawUniforms = context => ({
    'u_particle_texture': new index.bN(context),
    'u_particle_texture_side_len': new index.bM(context),
    'u_tile_offset': new index.bK(context),
    'u_velocity': new index.bN(context),
    'u_color_ramp': new index.bN(context),
    'u_velocity_res': new index.bK(context),
    'u_max_speed': new index.bM(context),
    'u_uv_offset': new index.bK(context),
    'u_data_scale': new index.bK(context),
    'u_data_offset': new index.bM(context),
    'u_particle_pos_scale': new index.bM(context),
    'u_particle_pos_offset': new index.bK(context)
});
const rasterParticleDrawUniformValues = (particleTextureUnit, particleTextureSideLen, tileOffset, velocityTextureUnit, velocityTextureSize, colorRampUnit, maxSpeed, textureOffset, dataScale, dataOffset) => ({
    'u_particle_texture': particleTextureUnit,
    'u_particle_texture_side_len': particleTextureSideLen,
    'u_tile_offset': tileOffset,
    'u_velocity': velocityTextureUnit,
    'u_color_ramp': colorRampUnit,
    'u_velocity_res': velocityTextureSize,
    'u_max_speed': maxSpeed,
    'u_uv_offset': textureOffset,
    'u_data_scale': [
        255 * dataScale[0],
        255 * dataScale[1]
    ],
    'u_data_offset': dataOffset,
    'u_particle_pos_scale': RASTER_PARTICLE_POS_SCALE,
    'u_particle_pos_offset': [
        RASTER_PARTICLE_POS_OFFSET,
        RASTER_PARTICLE_POS_OFFSET
    ]
});
const rasterParticleUpdateUniforms = context => ({
    'u_particle_texture': new index.bN(context),
    'u_particle_texture_side_len': new index.bM(context),
    'u_velocity': new index.bN(context),
    'u_velocity_res': new index.bK(context),
    'u_max_speed': new index.bM(context),
    'u_speed_factor': new index.bM(context),
    'u_reset_rate': new index.bM(context),
    'u_rand_seed': new index.bM(context),
    'u_uv_offset': new index.bK(context),
    'u_data_scale': new index.bK(context),
    'u_data_offset': new index.bM(context),
    'u_particle_pos_scale': new index.bM(context),
    'u_particle_pos_offset': new index.bK(context)
});
const rasterParticleUpdateUniformValues = (particleTextureUnit, particleTextureSideLen, velocityTextureUnit, velocityTextureSize, maxSpeed, speedFactor, resetRate, textureOffset, dataScale, dataOffset) => ({
    'u_particle_texture': particleTextureUnit,
    'u_particle_texture_side_len': particleTextureSideLen,
    'u_velocity': velocityTextureUnit,
    'u_velocity_res': velocityTextureSize,
    'u_max_speed': maxSpeed,
    'u_speed_factor': speedFactor,
    'u_reset_rate': resetRate,
    'u_rand_seed': Math.random(),
    'u_uv_offset': textureOffset,
    'u_data_scale': [
        255 * dataScale[0],
        255 * dataScale[1]
    ],
    'u_data_offset': dataOffset,
    'u_particle_pos_scale': RASTER_PARTICLE_POS_SCALE,
    'u_particle_pos_offset': [
        RASTER_PARTICLE_POS_OFFSET,
        RASTER_PARTICLE_POS_OFFSET
    ]
});

const symbolUniforms = context => ({
    'u_is_size_zoom_constant': new index.bN(context),
    'u_is_size_feature_constant': new index.bN(context),
    'u_size_t': new index.bM(context),
    'u_size': new index.bM(context),
    'u_camera_to_center_distance': new index.bM(context),
    'u_rotate_symbol': new index.bN(context),
    'u_aspect_ratio': new index.bM(context),
    'u_fade_change': new index.bM(context),
    'u_matrix': new index.bJ(context),
    'u_label_plane_matrix': new index.bJ(context),
    'u_coord_matrix': new index.bJ(context),
    'u_is_text': new index.bN(context),
    'u_elevation_from_sea': new index.bN(context),
    'u_pitch_with_map': new index.bN(context),
    'u_texsize': new index.bK(context),
    'u_texsize_icon': new index.bK(context),
    'u_texture': new index.bN(context),
    'u_texture_icon': new index.bN(context),
    'u_gamma_scale': new index.bM(context),
    'u_device_pixel_ratio': new index.bM(context),
    'u_tile_id': new index.bL(context),
    'u_zoom_transition': new index.bM(context),
    'u_inv_rot_matrix': new index.bJ(context),
    'u_merc_center': new index.bK(context),
    'u_camera_forward': new index.bL(context),
    'u_tile_matrix': new index.bJ(context),
    'u_up_vector': new index.bL(context),
    'u_ecef_origin': new index.bL(context),
    'u_is_halo': new index.bN(context),
    'u_icon_transition': new index.bM(context),
    'u_color_adj_mat': new index.bJ(context),
    'u_scale_factor': new index.bM(context)
});
const identityMatrix = index.ab.mat4.create();
const symbolUniformValues = (functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, elevationFromSea, isText, texSize, texSizeIcon, isHalo, coord, zoomTransition, mercatorCenter, invMatrix, upVector, projection, colorAdjustmentMatrix, transition, scaleFactor) => {
    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_elevation_from_sea': elevationFromSea ? 1 : 0,
        'u_pitch_with_map': +pitchWithMap,
        'u_texsize': texSize,
        'u_texsize_icon': texSizeIcon,
        'u_texture': 0,
        'u_texture_icon': 1,
        '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_color_adj_mat': colorAdjustmentMatrix,
        'u_icon_transition': transition ? transition : 0,
        'u_gamma_scale': pitchWithMap ? painter.transform.getCameraToCenterDistance(projection) * Math.cos(painter.terrain ? 0 : painter.transform._pitch) : 1,
        'u_device_pixel_ratio': index.q.devicePixelRatio,
        'u_is_halo': +isHalo,
        'u_scale_factor': scaleFactor ? scaleFactor : 1
    };
    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'] = index.cR(transform.globeMatrix, coord.toUnwrapped());
        values['u_tile_matrix'] = Float32Array.from(transform.globeMatrix);
        values['u_up_vector'] = upVector;
    }
    return values;
};

const backgroundUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_emissive_strength': new index.bM(context),
    'u_opacity': new index.bM(context),
    'u_color': new index.cz(context)
});
const backgroundPatternUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_emissive_strength': new index.bM(context),
    'u_opacity': new index.bM(context),
    'u_image': new index.bN(context),
    'u_pattern_tl': new index.bK(context),
    'u_pattern_br': new index.bK(context),
    'u_texsize': new index.bK(context),
    'u_pattern_size': new index.bK(context),
    'u_pixel_coord_upper': new index.bK(context),
    'u_pixel_coord_lower': new index.bK(context),
    'u_pattern_units_to_pixels': new index.bK(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, patternPosition, isViewport, tile) => index.l(bgPatternUniformValues(image, scope, patternPosition, painter, isViewport, tile), {
    'u_matrix': matrix,
    'u_emissive_strength': emissiveStrength,
    'u_opacity': opacity
});

const skyboxUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_sun_direction': new index.bL(context),
    'u_cubemap': new index.bN(context),
    'u_opacity': new index.bM(context),
    'u_temporal_offset': new index.bM(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 index.bJ(context),
    'u_color_ramp': new index.bN(context),
    // radial gradient uniforms
    'u_center_direction': new index.bL(context),
    'u_radius': new index.bM(context),
    'u_opacity': new index.bM(context),
    'u_temporal_offset': new index.bM(context)
});
const skyboxGradientUniformValues = (matrix, centerDirection, radius, opacity, temporalOffset) => {
    return {
        'u_matrix': matrix,
        'u_color_ramp': 0,
        'u_center_direction': centerDirection,
        'u_radius': index.ai(radius),
        'u_opacity': opacity,
        'u_temporal_offset': temporalOffset
    };
};

const skyboxCaptureUniforms = context => ({
    'u_matrix_3f': new index.cA(context),
    'u_sun_direction': new index.bL(context),
    'u_sun_intensity': new index.bM(context),
    'u_color_tint_r': new index.ca(context),
    'u_color_tint_m': new index.ca(context),
    'u_luminance': new index.bM(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 modelUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_lighting_matrix': new index.bJ(context),
    'u_normal_matrix': new index.bJ(context),
    'u_node_matrix': new index.bJ(context),
    'u_lightpos': new index.bL(context),
    'u_lightintensity': new index.bM(context),
    'u_lightcolor': new index.bL(context),
    'u_camera_pos': new index.bL(context),
    'u_opacity': new index.bM(context),
    'u_baseColorFactor': new index.ca(context),
    'u_emissiveFactor': new index.ca(context),
    'u_metallicFactor': new index.bM(context),
    'u_roughnessFactor': new index.bM(context),
    'u_baseTextureIsAlpha': new index.bN(context),
    'u_alphaMask': new index.bN(context),
    'u_alphaCutoff': new index.bM(context),
    'u_baseColorTexture': new index.bN(context),
    'u_metallicRoughnessTexture': new index.bN(context),
    'u_normalTexture': new index.bN(context),
    'u_occlusionTexture': new index.bN(context),
    'u_emissionTexture': new index.bN(context),
    'u_lutTexture': new index.bN(context),
    'u_color_mix': new index.ca(context),
    'u_aoIntensity': new index.bM(context),
    'u_emissive_strength': new index.bM(context),
    'u_occlusionTextureTransform': new index.ca(context)
});
const emptyMat4 = new Float32Array(index.ab.mat4.identity([]));
const modelUniformValues = (matrix, lightingMatrix, normalMatrix, nodeMatrix, painter, opacity, baseColorFactor, emissiveFactor, metallicFactor, roughnessFactor, material, emissiveStrength, layer, cameraPos = [
    0,
    0,
    0
], occlusionTextureTransform) => {
    const light = painter.style.light;
    const _lp = light.properties.get('position');
    const lightPos = [
        -_lp.x,
        -_lp.y,
        _lp.z
    ];
    const lightMat = index.ab.mat3.create();
    const anchor = light.properties.get('anchor');
    if (anchor === 'viewport') {
        index.ab.mat3.fromRotation(lightMat, -painter.transform.angle);
        index.ab.vec3.transformMat3(lightPos, lightPos, lightMat);
    }
    const alphaMask = material.alphaMode === 'MASK';
    const lightColor = light.properties.get('color').toRenderColor(null);
    const aoIntensity = layer.paint.get('model-ambient-occlusion-intensity');
    const colorMix = layer.paint.get('model-color').constantOr(index.aj.white).toRenderColor(null);
    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_node_matrix': nodeMatrix ? nodeMatrix : emptyMat4,
        '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_lutTexture': TextureSlots.LUT,
        'u_color_mix': [
            colorMix.r,
            colorMix.g,
            colorMix.b,
            colorMixIntensity
        ],
        'u_aoIntensity': aoIntensity,
        'u_emissive_strength': emissiveStrength,
        'u_occlusionTextureTransform': occlusionTextureTransform ? occlusionTextureTransform : [
            0,
            0,
            0,
            0
        ]
    };
    return uniformValues;
};
const modelDepthUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_instance': new index.bJ(context),
    'u_node_matrix': new index.bJ(context)
});
const modelDepthUniformValues = (matrix, instance = emptyMat4, nodeMatrix = emptyMat4) => {
    return {
        'u_matrix': matrix,
        'u_instance': instance,
        'u_node_matrix': nodeMatrix
    };
};

const starsUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_up': new index.bL(context),
    'u_right': new index.bL(context),
    'u_intensity_multiplier': new index.bM(context)
});
const starsUniformValues = (matrix, up, right, intensityMultiplier) => ({
    'u_matrix': Float32Array.from(matrix),
    'u_up': up,
    'u_right': right,
    'u_intensity_multiplier': intensityMultiplier
});

const occlusionUniforms = context => ({
    'u_matrix': new index.bJ(context),
    'u_anchorPos': new index.bL(context),
    'u_screenSizePx': new index.bK(context),
    'u_occluderSizePx': new index.bK(context),
    'u_color': new index.ca(context)
});

const snowUniforms = context => ({
    'u_modelview': new index.bJ(context),
    'u_projection': new index.bJ(context),
    'u_time': new index.bM(context),
    'u_cam_pos': new index.bL(context),
    'u_velocityConeAperture': new index.bM(context),
    'u_velocity': new index.bM(context),
    'u_horizontalOscillationRadius': new index.bM(context),
    'u_horizontalOscillationRate': new index.bM(context),
    'u_boxSize': new index.bM(context),
    'u_billboardSize': new index.bM(context),
    'u_simpleShapeParameters': new index.bK(context),
    'u_screenSize': new index.bK(context),
    'u_thinningCenterPos': new index.bK(context),
    'u_thinningShape': new index.bL(context),
    'u_thinningAffectedRatio': new index.bM(context),
    'u_thinningParticleOffset': new index.bM(context),
    'u_particleColor': new index.ca(context),
    'u_direction': new index.bL(context)
});
const snowUniformValues = values => ({
    'u_modelview': Float32Array.from(values.modelview),
    'u_projection': Float32Array.from(values.projection),
    'u_time': values.time,
    'u_cam_pos': values.camPos,
    'u_velocityConeAperture': values.velocityConeAperture,
    'u_velocity': values.velocity,
    'u_horizontalOscillationRadius': values.horizontalOscillationRadius,
    'u_horizontalOscillationRate': values.horizontalOscillationRate,
    'u_boxSize': values.boxSize,
    'u_billboardSize': values.billboardSize,
    'u_simpleShapeParameters': values.simpleShapeParameters,
    'u_screenSize': values.screenSize,
    'u_thinningCenterPos': values.thinningCenterPos,
    'u_thinningShape': values.thinningShape,
    'u_thinningAffectedRatio': values.thinningAffectedRatio,
    'u_thinningParticleOffset': values.thinningParticleOffset,
    'u_particleColor': values.color,
    'u_direction': values.direction
});

const rainUniforms = context => ({
    'u_modelview': new index.bJ(context),
    'u_projection': new index.bJ(context),
    'u_time': new index.bM(context),
    'u_cam_pos': new index.bL(context),
    'u_texScreen': new index.bN(context),
    'u_velocityConeAperture': new index.bM(context),
    'u_velocity': new index.bM(context),
    'u_boxSize': new index.bM(context),
    'u_rainDropletSize': new index.bK(context),
    'u_distortionStrength': new index.bM(context),
    'u_rainDirection': new index.bL(context),
    'u_color': new index.ca(context),
    'u_screenSize': new index.bK(context),
    'u_thinningCenterPos': new index.bK(context),
    'u_thinningShape': new index.bL(context),
    'u_thinningAffectedRatio': new index.bM(context),
    'u_thinningParticleOffset': new index.bM(context),
    'u_shapeDirectionalPower': new index.bM(context),
    'u_shapeNormalPower': new index.bM(context),
    'u_mode': new index.bM(context)
});
const rainUniformValues = values => ({
    'u_modelview': Float32Array.from(values.modelview),
    'u_projection': Float32Array.from(values.projection),
    'u_time': values.time,
    'u_cam_pos': values.camPos,
    'u_texScreen': 0,
    'u_velocityConeAperture': values.velocityConeAperture,
    'u_velocity': values.velocity,
    'u_boxSize': values.boxSize,
    'u_rainDropletSize': values.rainDropletSize,
    'u_distortionStrength': values.distortionStrength,
    'u_rainDirection': values.rainDirection,
    'u_color': values.color,
    'u_screenSize': values.screenSize,
    'u_thinningCenterPos': values.thinningCenterPos,
    'u_thinningShape': values.thinningShape,
    'u_thinningAffectedRatio': values.thinningAffectedRatio,
    'u_thinningParticleOffset': values.thinningParticleOffset,
    'u_shapeDirectionalPower': values.shapeDirectionalPower,
    'u_shapeNormalPower': values.shapeNormalPower,
    'u_mode': values.mode
});

const vignetteUniforms = context => ({
    'u_vignetteShape': new index.bL(context),
    'u_vignetteColor': new index.ca(context)
});
const vignetteUniformValues = values => ({
    'u_vignetteShape': values.vignetteShape,
    'u_vignetteColor': values.vignetteColor
});

const programUniforms = {
    fillExtrusion: fillExtrusionUniforms,
    fillExtrusionDepth: fillExtrusionDepthUniforms,
    fillExtrusionPattern: fillExtrusionPatternUniforms,
    fillExtrusionGroundEffect: fillExtrusionGroundEffectUniforms,
    fill: fillUniforms,
    fillPattern: fillPatternUniforms,
    fillOutline: fillOutlineUniforms,
    fillOutlinePattern: fillOutlinePatternUniforms,
    circle: index.cS,
    collisionBox: collisionUniforms,
    collisionCircle: collisionCircleUniforms,
    debug: debugUniforms,
    clippingMask: clippingMaskUniforms,
    heatmap: heatmapUniforms,
    heatmapTexture: heatmapTextureUniforms,
    hillshade: hillshadeUniforms,
    hillshadePrepare: hillshadePrepareUniforms,
    line: index.cT,
    linePattern: index.cU,
    raster: rasterUniforms,
    rasterParticle: rasterParticleUniforms,
    rasterParticleTexture: rasterParticleTextureUniforms,
    rasterParticleDraw: rasterParticleDrawUniforms,
    rasterParticleUpdate: rasterParticleUpdateUniforms,
    symbol: symbolUniforms,
    background: backgroundUniforms,
    backgroundPattern: backgroundPatternUniforms,
    terrainRaster: terrainRasterUniforms,
    skybox: skyboxUniforms,
    skyboxGradient: skyboxGradientUniforms,
    skyboxCapture: skyboxCaptureUniforms,
    globeRaster: globeRasterUniforms,
    globeAtmosphere: atmosphereUniforms,
    model: modelUniforms,
    modelDepth: modelDepthUniforms,
    groundShadow: groundShadowUniforms,
    stars: starsUniforms,
    snowParticle: snowUniforms,
    rainParticle: rainUniforms,
    vignette: vignetteUniforms,
    occlusion: occlusionUniforms
};

class IndexBuffer {
    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);
        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;
        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;

const AttributeType = {
    Int8: 'BYTE',
    Uint8: 'UNSIGNED_BYTE',
    Int16: 'SHORT',
    Uint16: 'UNSIGNED_SHORT',
    Int32: 'INT',
    Uint32: 'UNSIGNED_INT',
    Float32: 'FLOAT'
};
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 !== void 0) {
                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 !== void 0) {
                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 !== void 0 && 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 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);
    }
}

class Context {
    constructor(gl, options) {
        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.options = options ? Object.assign({}, options) : {};
        if (!this.options.extTextureFilterAnisotropicForceOff) {
            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.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.forceManualRenderingForInstanceIDShaders = options && !!options.forceManualRenderingForInstanceIDShaders || this.renderer && this.renderer.indexOf('PowerVR') !== -1;
        if (!this.options.extTextureFloatLinearForceOff) {
            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);
        this.maxPointSize = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE)[1];
    }
    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;
            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 (index.bn(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() {
        this.bindVertexArrayOES.set(null);
    }
}

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;
        const circleArray = bucket.collisionCircleArray;
        if (circleArray.length > 0) {
            const invTransform = index.ab.mat4.create();
            const transform = posMatrix;
            index.ab.mat4.mul(invTransform, bucket.placementInvProjMatrix, tr.glCoordMatrix);
            index.ab.mat4.mul(invTransform, invTransform, bucket.placementViewportMatrix);
            tileBatches.push({
                circleArray,
                circleOffset,
                transform,
                invTransform,
                projection: bucket.getProjection()
            });
            circleCount += circleArray.length / 4;
            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;
    }
    const circleProgram = painter.getOrCreateProgram('collisionCircle');
    const vertexData = new index.cV();
    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];
            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, index.cW.members, true);
    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, index.b7.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 index.aU();
    array.resize(triCount);
    array._trim();
    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 = index.ab.mat4.create();
function drawSymbols(painter, sourceCache, layer, coords, variableOffsets) {
    if (painter.renderPass !== 'translucent')
        return;
    const stencilMode = StencilMode.disabled;
    const colorMode = painter.colorModeForRenderPass();
    const variablePlacement = layer.layout.get('text-variable-anchor');
    const textSizeScaleRange = layer.layout.get('text-size-scale-range');
    const textScaleFactor = index.aw(painter.scaleFactor, textSizeScaleRange[0], textSizeScaleRange[1]);
    if (variablePlacement) {
        updateVariableAnchors(coords, painter, layer, sourceCache, layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), variableOffsets, textScaleFactor);
    }
    const areIconsVisible = layer.paint.get('icon-opacity').constantOr(1) !== 0;
    const areTextsVisible = layer.paint.get('text-opacity').constantOr(1) !== 0;
    if (layer.layout.get('symbol-sort-key').constantOr(1) !== void 0 && (areIconsVisible || areTextsVisible)) {
        drawLayerSymbols(painter, sourceCache, layer, coords, stencilMode, colorMode);
    } else {
        if (areIconsVisible) {
            drawLayerSymbols(painter, sourceCache, layer, coords, stencilMode, colorMode, { onlyIcons: true });
        }
        if (areTextsVisible) {
            drawLayerSymbols(painter, sourceCache, layer, coords, stencilMode, colorMode, { onlyText: true });
        }
    }
    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 = index.ab.mat4.multiply([], viewMatrix, transform.globeMatrix);
    index.ab.mat4.invert(viewToEcef, viewToEcef);
    const cameraUpVector = [
        0,
        0,
        0
    ];
    const up = [
        0,
        1,
        0,
        0
    ];
    index.ab.vec4.transformMat4(up, up, viewToEcef);
    cameraUpVector[0] = up[0];
    cameraUpVector[1] = up[1];
    cameraUpVector[2] = up[2];
    index.ab.vec3.normalize(cameraUpVector, cameraUpVector);
    return cameraUpVector;
}
function calculateVariableRenderShift({width, height, anchor, textOffset, textScale}, renderTextSize) {
    const {horizontalAlign, verticalAlign} = index.bD(anchor);
    const shiftX = -(horizontalAlign - 0.5) * width;
    const shiftY = -(verticalAlign - 0.5) * height;
    const variableOffset = index.bC(anchor, textOffset);
    return new index.P((shiftX / textScale + variableOffset[0]) * renderTextSize, (shiftY / textScale + variableOffset[1]) * renderTextSize);
}
function updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, variableOffsets, textScaleFactor) {
    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 = index.bp(sizeData, tr.zoom, textScaleFactor);
        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, index.cX, tr, labelPlaneMatrix, coord, tileScale, size, updateTextFitIcon);
        }
    }
}
function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize2, 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) {
            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 = symbolSize2.evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / index.bw;
            if (pitchWithMap) {
                renderTextSize *= bucket.tilePixelRatio / tileScale;
            }
            const shift = calculateVariableRenderShift(variableOffset, renderTextSize);
            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 === index.bq.vertical ? Math.PI / 2 : 0;
            for (let g = 0; g < numGlyphs; g++) {
                index.bt(dynamicTextLayoutVertexArray, x, y, z, angle);
            }
            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++) {
                    index.bt(dynamicIconLayoutVertexArray, x, y, z, angle);
                }
            }
        }
        bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);
    }
    bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);
}
function drawLayerSymbols(painter, sourceCache, layer, coords, stencilMode, colorMode, options = {}) {
    const iconTranslate = layer.paint.get('icon-translate');
    const textTranslate = layer.paint.get('text-translate');
    const iconTranslateAnchor = layer.paint.get('icon-translate-anchor');
    const textTranslateAnchor = layer.paint.get('text-translate-anchor');
    const iconRotationAlignment = layer.layout.get('icon-rotation-alignment');
    const textRotationAlignment = layer.layout.get('text-rotation-alignment');
    const iconPitchAlignment = layer.layout.get('icon-pitch-alignment');
    const textPitchAlignment = layer.layout.get('text-pitch-alignment');
    const iconKeepUpright = layer.layout.get('icon-keep-upright');
    const textKeepUpright = layer.layout.get('text-keep-upright');
    const iconSaturation = layer.paint.get('icon-color-saturation');
    const iconContrast = layer.paint.get('icon-color-contrast');
    const iconBrightnessMin = layer.paint.get('icon-color-brightness-min');
    const iconBrightnessMax = layer.paint.get('icon-color-brightness-max');
    const elevationFromSea = layer.layout.get('symbol-elevation-reference') === 'sea';
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const iconRotateWithMap = iconRotationAlignment === 'map';
    const textRotateWithMap = textRotationAlignment === 'map';
    const iconPitchWithMap = iconPitchAlignment === 'map';
    const textPitchWithMap = textPitchAlignment === 'map';
    const hasSortKey = layer.layout.get('symbol-sort-key').constantOr(1) !== void 0;
    let sortFeaturesByKey = false;
    const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
    const mercatorCenter = [
        index.at(tr.center.lng),
        index.aA(tr.center.lat)
    ];
    const variablePlacement = layer.layout.get('text-variable-anchor');
    const isGlobeProjection = tr.projection.name === 'globe';
    const tileRenderState = [];
    const mercatorCameraUp = [
        0,
        -1,
        0
    ];
    for (const coord of coords) {
        const tile = sourceCache.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        if (bucket.projection.name === 'mercator' && isGlobeProjection) {
            continue;
        }
        if (bucket.fullyClipped)
            continue;
        const bucketIsGlobeProjection = bucket.projection.name === 'globe';
        const globeToMercator = bucketIsGlobeProjection ? index.ae(tr.zoom) : 0;
        const tileMatrix = getSymbolTileProjectionMatrix(coord, bucket.getProjection(), tr);
        const s = tr.calculatePixelsToTileUnitsMatrix(tile);
        const hasVariableAnchors = variablePlacement && bucket.hasTextData();
        const updateTextFitIcon = bucket.hasIconTextFit() && hasVariableAnchors && bucket.hasIconData();
        const invMatrix = bucket.getProjection().createInversionMatrix(tr, coord.canonical);
        const setOcclusionDefines = defines => {
            if (!tr.depthOcclusionForSymbolsAndCircles) {
                return;
            }
            if (!layer.hasInitialOcclusionOpacityProperties) {
                if (painter.terrain) {
                    defines.push('DEPTH_D24');
                    defines.push('DEPTH_OCCLUSION');
                }
            } else {
                defines.push('DEPTH_D24');
                defines.push('DEPTH_OCCLUSION');
            }
        };
        const getIconState = () => {
            const alongLine = iconRotateWithMap && layer.layout.get('symbol-placement') !== 'point';
            const baseDefines = [];
            setOcclusionDefines(baseDefines);
            const projectedPosOnLabelSpace = alongLine || updateTextFitIcon;
            const transitionProgress = layer.paint.get('icon-image-cross-fade').constantOr(0);
            if (painter.terrainRenderModeElevated() && iconPitchWithMap) {
                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 (bucket.icon.zOffsetVertexBuffer) {
                baseDefines.push('Z_OFFSET');
            }
            if (iconSaturation !== 0 || iconContrast !== 0 || iconBrightnessMin !== 0 || iconBrightnessMax !== 1) {
                baseDefines.push('COLOR_ADJUSTMENT');
            }
            if (bucket.sdfIcons) {
                baseDefines.push('RENDER_SDF');
            }
            const programConfiguration = bucket.icon.programConfigurations.get(layer.id);
            const program = painter.getOrCreateProgram('symbol', {
                config: programConfiguration,
                defines: baseDefines
            });
            const texSize = tile.imageAtlasTexture ? tile.imageAtlasTexture.size : [
                0,
                0
            ];
            const sizeData = bucket.iconSizeData;
            const size = index.bp(sizeData, tr.zoom);
            const transformed = iconPitchWithMap || tr.pitch !== 0;
            const labelPlaneMatrixRendering = getLabelPlaneMatrixForRendering(tileMatrix, tile.tileID.canonical, iconPitchWithMap, iconRotateWithMap, tr, bucket.getProjection(), s);
            const glCoordMatrix = getGlCoordMatrix(tileMatrix, tile.tileID.canonical, iconPitchWithMap, iconRotateWithMap, tr, bucket.getProjection(), s);
            const uglCoordMatrix = painter.translatePosMatrix(glCoordMatrix, tile, iconTranslate, iconTranslateAnchor, true);
            const matrix = painter.translatePosMatrix(tileMatrix, tile, iconTranslate, iconTranslateAnchor);
            const uLabelPlaneMatrix = projectedPosOnLabelSpace ? identityMat4 : labelPlaneMatrixRendering;
            const rotateInShader = iconRotateWithMap && !iconPitchWithMap && !alongLine;
            let globeCameraUp = mercatorCameraUp;
            if ((isGlobeProjection || tr.mercatorFromTransition) && !iconRotateWithMap) {
                globeCameraUp = computeGlobeCameraUp(tr);
            }
            const cameraUpVector = bucketIsGlobeProjection ? globeCameraUp : mercatorCameraUp;
            const colorAdjustmentMatrix = layer.getColorAdjustmentMatrix(iconSaturation, iconContrast, iconBrightnessMin, iconBrightnessMax);
            const uniformValues = symbolUniformValues(sizeData.kind, size, rotateInShader, iconPitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, elevationFromSea, false, texSize, [
                0,
                0
            ], true, coord, globeToMercator, mercatorCenter, invMatrix, cameraUpVector, bucket.getProjection(), colorAdjustmentMatrix, transitionProgress);
            const atlasTexture = tile.imageAtlasTexture ? tile.imageAtlasTexture : null;
            const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear;
            const atlasInterpolation = bucket.sdfIcons || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? gl.LINEAR : gl.NEAREST;
            const hasHalo = bucket.sdfIcons && layer.paint.get('icon-halo-width').constantOr(1) !== 0;
            const labelPlaneMatrixInv = painter.terrain && iconPitchWithMap && alongLine ? index.ab.mat4.invert(index.ab.mat4.create(), labelPlaneMatrixRendering) : identityMat4;
            if (alongLine && bucket.icon) {
                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, iconPitchWithMap, iconRotateWithMap, tr, bucket.getProjection(), s);
                updateLineLabels(bucket, tileMatrix, painter, false, labelPlaneMatrixPlacement, glCoordMatrix, iconPitchWithMap, iconKeepUpright, getElevation, coord);
            }
            return {
                program,
                buffers: bucket.icon,
                uniformValues,
                atlasTexture,
                atlasTextureIcon: null,
                atlasInterpolation,
                atlasInterpolationIcon: null,
                isSDF: bucket.sdfIcons,
                hasHalo,
                tile,
                labelPlaneMatrixInv
            };
        };
        const getTextState = () => {
            const alongLine = textRotateWithMap && layer.layout.get('symbol-placement') !== 'point';
            const baseDefines = [];
            const projectedPosOnLabelSpace = alongLine || variablePlacement || updateTextFitIcon;
            if (painter.terrainRenderModeElevated() && textPitchWithMap) {
                baseDefines.push('PITCH_WITH_MAP_TERRAIN');
            }
            if (bucketIsGlobeProjection) {
                baseDefines.push('PROJECTION_GLOBE_VIEW');
                if (projectedPosOnLabelSpace) {
                    baseDefines.push('PROJECTED_POS_ON_VIEWPORT');
                }
            }
            if (bucket.text.zOffsetVertexBuffer) {
                baseDefines.push('Z_OFFSET');
            }
            if (bucket.iconsInText) {
                baseDefines.push('RENDER_TEXT_AND_SYMBOL');
            }
            baseDefines.push('RENDER_SDF');
            setOcclusionDefines(baseDefines);
            const programConfiguration = bucket.text.programConfigurations.get(layer.id);
            const program = painter.getOrCreateProgram('symbol', {
                config: programConfiguration,
                defines: baseDefines
            });
            let texSizeIcon = [
                0,
                0
            ];
            let atlasTextureIcon = null;
            let atlasInterpolationIcon;
            const sizeData = bucket.textSizeData;
            if (bucket.iconsInText) {
                texSizeIcon = tile.imageAtlasTexture ? tile.imageAtlasTexture.size : [
                    0,
                    0
                ];
                atlasTextureIcon = tile.imageAtlasTexture ? tile.imageAtlasTexture : null;
                const transformed = textPitchWithMap || tr.pitch !== 0;
                const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera';
                atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST;
            }
            const texSize = tile.glyphAtlasTexture ? tile.glyphAtlasTexture.size : [
                0,
                0
            ];
            const textSizeScaleRange = layer.layout.get('text-size-scale-range');
            const textScaleFactor = index.aw(painter.scaleFactor, textSizeScaleRange[0], textSizeScaleRange[1]);
            const size = index.bp(sizeData, tr.zoom, textScaleFactor);
            const labelPlaneMatrixRendering = getLabelPlaneMatrixForRendering(tileMatrix, tile.tileID.canonical, textPitchWithMap, textRotateWithMap, tr, bucket.getProjection(), s);
            const glCoordMatrix = getGlCoordMatrix(tileMatrix, tile.tileID.canonical, textPitchWithMap, textRotateWithMap, tr, bucket.getProjection(), s);
            const uglCoordMatrix = painter.translatePosMatrix(glCoordMatrix, tile, textTranslate, textTranslateAnchor, true);
            const matrix = painter.translatePosMatrix(tileMatrix, tile, textTranslate, textTranslateAnchor);
            const uLabelPlaneMatrix = projectedPosOnLabelSpace ? identityMat4 : labelPlaneMatrixRendering;
            const rotateInShader = textRotateWithMap && !textPitchWithMap && !alongLine;
            let globeCameraUp = mercatorCameraUp;
            if ((isGlobeProjection || tr.mercatorFromTransition) && !textRotateWithMap) {
                globeCameraUp = computeGlobeCameraUp(tr);
            }
            const cameraUpVector = bucketIsGlobeProjection ? globeCameraUp : mercatorCameraUp;
            const uniformValues = symbolUniformValues(sizeData.kind, size, rotateInShader, textPitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, elevationFromSea, true, texSize, texSizeIcon, true, coord, globeToMercator, mercatorCenter, invMatrix, cameraUpVector, bucket.getProjection(), null, null, textScaleFactor);
            const atlasTexture = tile.glyphAtlasTexture ? tile.glyphAtlasTexture : null;
            const atlasInterpolation = gl.LINEAR;
            const hasHalo = layer.paint.get('text-halo-width').constantOr(1) !== 0;
            const labelPlaneMatrixInv = painter.terrain && textPitchWithMap && alongLine ? index.ab.mat4.invert(index.ab.mat4.create(), labelPlaneMatrixRendering) : identityMat4;
            if (alongLine && bucket.text) {
                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, textPitchWithMap, textRotateWithMap, tr, bucket.getProjection(), s);
                updateLineLabels(bucket, tileMatrix, painter, true, labelPlaneMatrixPlacement, glCoordMatrix, textPitchWithMap, textKeepUpright, getElevation, coord);
            }
            return {
                program,
                buffers: bucket.text,
                uniformValues,
                atlasTexture,
                atlasTextureIcon,
                atlasInterpolation,
                atlasInterpolationIcon,
                isSDF: true,
                hasHalo,
                tile,
                labelPlaneMatrixInv
            };
        };
        const iconSegmentsLength = bucket.icon.segments.get().length;
        const textSegmentsLength = bucket.text.segments.get().length;
        const iconState = iconSegmentsLength && !options.onlyText ? getIconState() : null;
        const textState = textSegmentsLength && !options.onlyIcons ? getTextState() : null;
        const iconOpacity = layer.paint.get('icon-opacity').constantOr(1);
        const textOpacity = layer.paint.get('text-opacity').constantOr(1);
        if (hasSortKey && bucket.canOverlap) {
            sortFeaturesByKey = true;
            const oldIconSegments = iconOpacity && !options.onlyText ? bucket.icon.segments.get() : [];
            const oldTextSegments = textOpacity && !options.onlyIcons ? bucket.text.segments.get() : [];
            for (const segment of oldIconSegments) {
                tileRenderState.push({
                    segments: new index.b7([segment]),
                    sortKey: segment.sortKey,
                    state: iconState
                });
            }
            for (const segment of oldTextSegments) {
                tileRenderState.push({
                    segments: new index.b7([segment]),
                    sortKey: segment.sortKey,
                    state: textState
                });
            }
        } else {
            if (!options.onlyText) {
                tileRenderState.push({
                    segments: iconOpacity ? bucket.icon.segments : new index.b7([]),
                    sortKey: 0,
                    state: iconState
                });
            }
            if (!options.onlyIcons) {
                tileRenderState.push({
                    segments: textOpacity ? bucket.text.segments : new index.b7([]),
                    sortKey: 0,
                    state: textState
                });
            }
        }
    }
    if (sortFeaturesByKey) {
        tileRenderState.sort((a, b) => a.sortKey - b.sortKey);
    }
    for (const segmentState of tileRenderState) {
        const state = segmentState.state;
        if (!state) {
            continue;
        }
        if (painter.terrain) {
            const options2 = {
                // Use depth occlusion only for unspecified opacity multiplier case
                useDepthForOcclusion: tr.depthOcclusionForSymbolsAndCircles,
                labelPlaneMatrixInv: state.labelPlaneMatrixInv
            };
            painter.terrain.setupElevationDraw(state.tile, state.program, options2);
        } else {
            painter.setupDepthForOcclusion(tr.depthOcclusionForSymbolsAndCircles, state.program);
        }
        context.activeTexture.set(gl.TEXTURE0);
        if (state.atlasTexture) {
            state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE, true);
        }
        if (state.atlasTextureIcon) {
            context.activeTexture.set(gl.TEXTURE1);
            if (state.atlasTextureIcon) {
                state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE, true);
            }
        }
        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) !== void 0;
    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);
    const stencilMode = StencilMode.disabled;
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const isGlobeProjection = tr.projection.name === 'globe';
    const mercatorCenter = [
        index.at(tr.center.lng),
        index.aA(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 = index.cY(layer);
        const affectedByFog = painter.isTileAffectedByFog(coord);
        if (isGlobeProjection) {
            definesValues.push('PROJECTION_GLOBE_VIEW');
        }
        definesValues.push('DEPTH_D24');
        if (painter.terrain && tr.depthOcclusionForSymbolsAndCircles) {
            definesValues.push('DEPTH_OCCLUSION');
        }
        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 = index.cZ(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 index.b7([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;
        const stencilMode = StencilMode.disabled;
        const colorMode = new ColorMode([
            gl.ONE,
            gl.ONE,
            gl.ONE,
            gl.ONE
        ], index.aj.transparent, [
            true,
            true,
            true,
            true
        ]);
        const resolutionScaling = painter.transform.projection.name === 'globe' ? 0.5 : 0.25;
        bindFramebuffer(context, painter, layer, resolutionScaling);
        context.clear({ color: index.aj.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 = [
            index.at(tr.center.lng),
            index.aA(tr.center.lat)
        ];
        for (let i = 0; i < coords.length; i++) {
            const coord = coords[i];
            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$1(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;
    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$1(painter, layer) {
    const context = painter.context;
    const gl = context.gl;
    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 index.T(context, layer.colorRamp, gl.RGBA8);
    }
    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 prepare$4(layer, sourceCache, painter) {
    layer.hasElevatedBuckets = false;
    layer.hasNonElevatedBuckets = false;
    if (layer._unevaluatedLayout.getValue('line-elevation-reference') === void 0 && layer._unevaluatedLayout.getValue('line-z-offset') === void 0) {
        layer.hasNonElevatedBuckets = true;
        return;
    }
    if (sourceCache) {
        const coords = sourceCache.getVisibleCoordinates();
        for (const coord of coords) {
            const tile = sourceCache.getTile(coord);
            const bucket = tile.getBucket(layer);
            if (!bucket)
                continue;
            if (bucket.hasZOffset) {
                layer.hasElevatedBuckets = true;
            } else {
                layer.hasNonElevatedBuckets = true;
            }
            if (layer.hasElevatedBuckets && layer.hasNonElevatedBuckets) {
                break;
            }
        }
    }
}
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 occlusionOpacity = layer.paint.get('line-occlusion-opacity');
    const elevationReference = layer.layout.get('line-elevation-reference');
    const unitInMeters = layer.layout.get('line-width-unit') === 'meters';
    const elevationFromSea = elevationReference === 'sea';
    const context = painter.context;
    const gl = context.gl;
    if (layer.hasElevatedBuckets && painter.transform.projection.name === 'globe')
        return;
    const crossSlope = layer.layout.get('line-cross-slope');
    const hasCrossSlope = crossSlope !== void 0;
    const crossSlopeHorizontal = crossSlope < 1;
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const isDraping = painter.terrain && painter.terrain.renderingToTexture;
    const pixelRatio = isDraping ? 1 : index.q.devicePixelRatio;
    const dasharrayProperty = layer.paint.get('line-dasharray');
    const dasharray = dasharrayProperty.constantOr(1);
    const capProperty = layer.layout.get('line-cap');
    const constantDash = dasharrayProperty.constantOr(null);
    const constantCap = capProperty.constantOr(null);
    const patternProperty = layer.paint.get('line-pattern');
    const image = patternProperty.constantOr(1);
    const constantPattern = patternProperty.constantOr(null);
    const lineOpacity = layer.paint.get('line-opacity').constantOr(1);
    const hasOpacity = lineOpacity !== 1;
    let useStencilMaskRenderPass = !image && hasOpacity || // Only semi-transparent lines need stencil masking
    painter.depthOcclusion && occlusionOpacity > 0 && occlusionOpacity < 1;
    const gradient = layer.paint.get('line-gradient');
    const programId = image ? 'linePattern' : 'line';
    const definesValues = index.c_(layer);
    if (isDraping && painter.terrain && painter.terrain.clipOrMaskOverlapStencilType()) {
        useStencilMaskRenderPass = false;
    }
    let lineOpacityForOcclusion;
    if (occlusionOpacity !== 0 && painter.depthOcclusion) {
        const value = layer.paint._values['line-opacity'];
        if (value && value.value && value.value.kind === 'constant') {
            lineOpacityForOcclusion = value.value;
        } else {
            index.w(`Occlusion opacity for layer ${ layer.id } is supported only when line-opacity isn't data-driven.`);
        }
    }
    if (width.value.kind !== 'constant' && width.value.isLineProgressConstant === false) {
        definesValues.push('VARIABLE_LINE_WIDTH');
    }
    const renderTiles = (coords2, defines, depthMode, stencilMode3D, elevated) => {
        for (const coord of coords2) {
            const tile = sourceCache.getTile(coord);
            if (image && !tile.patternsLoaded())
                continue;
            const bucket = tile.getBucket(layer);
            if (!bucket)
                continue;
            if (bucket.hasZOffset && !elevated || !bucket.hasZOffset && elevated)
                continue;
            painter.prepareDrawTile();
            const programConfiguration = bucket.programConfigurations.get(layer.id);
            const affectedByFog = painter.isTileAffectedByFog(coord);
            const program = painter.getOrCreateProgram(programId, {
                config: programConfiguration,
                defines,
                overrideFog: affectedByFog,
                overrideRtt: elevated ? false : void 0
            });
            if (constantPattern && tile.imageAtlas) {
                const patternImage = index.A.from(constantPattern).getPrimary().scaleSelf(pixelRatio).serialize();
                const posTo = tile.imageAtlas.patternPositions[patternImage];
                if (posTo)
                    programConfiguration.setConstantPatternPositions(posTo);
            }
            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');
            if (constantCap === 'round' || constantCap === 'square') {
                const fakeOffsetShift = 1;
                if (trimStart !== trimEnd) {
                    if (trimStart === 0) {
                        trimStart -= fakeOffsetShift;
                    }
                    if (trimEnd === 1) {
                        trimEnd += fakeOffsetShift;
                    }
                }
            }
            const matrix = isDraping ? coord.projMatrix : null;
            const lineWidthScale = unitInMeters ? 1 / bucket.tileToMeter / index.ar(tile, 1, painter.transform.zoom) : 1;
            const lineFloorWidthScale = unitInMeters ? 1 / bucket.tileToMeter / index.ar(tile, 1, Math.floor(painter.transform.zoom)) : 1;
            const uniformValues = image ? index.c$(painter, tile, layer, matrix, pixelRatio, lineWidthScale, lineFloorWidthScale, [
                trimStart,
                trimEnd
            ]) : index.d0(painter, tile, layer, matrix, bucket.lineClipsArray.length, pixelRatio, lineWidthScale, lineFloorWidthScale, [
                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 / index.ag;
                        const maxTilePixelSize = 1024;
                        const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom;
                        textureResolution = index.aw(index.d1(maxTextureCoverage), 256, context.maxTextureSize);
                    }
                    layerGradient.gradient = index.d2({
                        expression: layer.gradientExpression(),
                        evaluationKey: 'lineProgress',
                        resolution: textureResolution,
                        image: layerGradient.gradient || void 0,
                        clips: bucket.lineClipsArray
                    });
                    if (layerGradient.texture) {
                        layerGradient.texture.update(layerGradient.gradient);
                    } else {
                        layerGradient.texture = new index.T(context, layerGradient.gradient, gl.RGBA8);
                    }
                    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);
                if (tile.lineAtlasTexture) {
                    tile.lineAtlasTexture.bind(gl.LINEAR, gl.REPEAT);
                }
                programConfiguration.updatePaintBuffers();
            }
            if (image) {
                context.activeTexture.set(gl.TEXTURE0);
                if (tile.imageAtlasTexture) {
                    tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
                }
                programConfiguration.updatePaintBuffers();
            }
            if (elevated && !elevationFromSea) {
                painter.terrain.setupElevationDraw(tile, program);
            }
            painter.uploadCommonUniforms(context, program, coord.toUnwrapped());
            const renderLine = stencilMode => {
                if (lineOpacityForOcclusion != null) {
                    lineOpacityForOcclusion.value = lineOpacity * occlusionOpacity;
                }
                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,
                    bucket.patternVertexBuffer,
                    bucket.zOffsetVertexBuffer
                ]);
                if (lineOpacityForOcclusion != null) {
                    lineOpacityForOcclusion.value = lineOpacity;
                }
            };
            if (useStencilMaskRenderPass && !elevated) {
                const stencilId = painter.stencilModeForClipping(coord).ref;
                const needsClearing = stencilId === 0 && isDraping;
                if (needsClearing) {
                    context.clear({ stencil: 0 });
                }
                const stencilFunc = {
                    func: gl.EQUAL,
                    mask: 255
                };
                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 {
                if (useStencilMaskRenderPass && elevated) {
                    uniformValues['u_alpha_discard_threshold'] = 0.001;
                }
                renderLine(elevated ? stencilMode3D : painter.stencilModeForClipping(coord));
            }
        }
    };
    if (layer.hasNonElevatedBuckets) {
        const terrainEnabledImmediateMode = !isDraping && painter.terrain;
        if (occlusionOpacity !== 0 && terrainEnabledImmediateMode) {
            index.w(`Occlusion opacity for layer ${ layer.id } is supported on terrain only if the layer has line-z-offset enabled.`);
        } else {
            if (!terrainEnabledImmediateMode) {
                const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
                const stencilMode3D = StencilMode.disabled;
                renderTiles(coords, definesValues, depthMode, stencilMode3D, false);
            } else {
                index.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${ layer.id }.`);
            }
        }
    }
    if (layer.hasElevatedBuckets) {
        definesValues.push('ELEVATED');
        if (hasCrossSlope) {
            definesValues.push(crossSlopeHorizontal ? 'CROSS_SLOPE_HORIZONTAL' : 'CROSS_SLOPE_VERTICAL');
        }
        if (elevationFromSea) {
            definesValues.push('ELEVATION_REFERENCE_SEA');
        }
        const stencilMode3D = useStencilMaskRenderPass ? painter.stencilModeFor3D() : StencilMode.disabled;
        const depthMode = new DepthMode(painter.depthOcclusion ? gl.GREATER : gl.LEQUAL, DepthMode.ReadOnly, painter.depthRangeFor3D);
        painter.forceTerrainMode = true;
        renderTiles(coords, definesValues, depthMode, stencilMode3D, true);
        painter.forceTerrainMode = false;
    }
    if (useStencilMaskRenderPass) {
        painter.resetStencilClippingMasks();
        if (isDraping) {
            context.clear({ stencil: 0 });
        }
    }
    if (occlusionOpacity !== 0 && !painter.depthOcclusion && !isDraping) {
        painter.layersWithOcclusionOpacity.push(painter.currentLayer);
    }
}

function drawFill(painter, sourceCache, layer, coords) {
    const color = layer.paint.get('fill-color');
    const opacity = layer.paint.get('fill-opacity');
    const is3D = layer.is3D();
    const depthModeFor3D = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    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(index.aj.transparent).a === 1 && opacity.constantOr(0) === 1) ? 'opaque' : 'translucent';
    if (painter.renderPass === pass) {
        const depthMode = is3D ? depthModeFor3D : painter.depthModeForSublayer(1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);
        drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false);
    }
    if (!is3D && painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) {
        const depthMode = is3D ? depthModeFor3D : 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 is3D = layer.is3D();
    const stencilFor3D = is3D ? painter.stencilModeFor3D() : StencilMode.disabled;
    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);
            if (tile.imageAtlasTexture) {
                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 patternImage = index.A.from(constantPattern).getPrimary().scaleSelf(index.q.devicePixelRatio).serialize();
            const posTo = atlas.patternPositions[patternImage];
            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, is3D ? stencilFor3D : painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration, void 0);
    }
}

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;
    if (opacity === 0) {
        return;
    }
    const conflateLayer = painter.conflationActive && painter.style.isLayerClipped(layer, source.getSource());
    const layerIdx = painter.style.order.indexOf(layer.fqid);
    if (conflateLayer) {
        updateReplacement(painter, source, layer, coords, layerIdx);
    }
    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 index.a9) {
                    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);
        const color = layer.paint.get('fill-extrusion-color').constantOr(index.aj.white);
        if (!rtt && color.a !== 0) {
            const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
            if (opacity === 1 && noPattern) {
                drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.unblended, conflateLayer);
            } else {
                drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled, conflateLayer);
                drawExtrusionTiles(painter, source, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass(), conflateLayer);
                painter.resetStencilClippingMasks();
            }
        }
        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 opacity2 = 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 floodLightIgnoreLut = layer.paint.get('fill-extrusion-flood-light-color-use-theme').constantOr('default') === 'none';
            const floodLightColor = layer.paint.get('fill-extrusion-flood-light-color').toRenderColor(floodLightIgnoreLut ? null : layer.lut).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) {
                    const stencilSdfPass = new StencilMode({
                        func: gl.ALWAYS,
                        mask: 255
                    }, 255, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
                    const colorSdfPass = new ColorMode([
                        gl.ONE,
                        gl.ONE,
                        gl.ONE,
                        gl.ONE
                    ], index.aj.transparent, [
                        false,
                        false,
                        false,
                        true
                    ], gl.MIN);
                    drawGroundEffect(painter, source, layer, coords, depthMode, stencilSdfPass, colorSdfPass, CullFaceMode.disabled, aoPass, 'sdf', opacity2, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, false);
                }
                {
                    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
                    ], index.aj.transparent, [
                        true,
                        true,
                        true,
                        true
                    ]);
                    drawGroundEffect(painter, source, layer, coords, depthMode, stencilColorPass, colorColorPass, CullFaceMode.disabled, aoPass, 'color', opacity2, 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);
                    {
                        const colorMode = new ColorMode([
                            gl.ONE,
                            gl.ONE,
                            gl.ONE,
                            gl.ONE
                        ], index.aj.transparent, [
                            false,
                            false,
                            false,
                            true
                        ]);
                        drawGroundEffect(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, aoPass, 'clear', opacity2, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors);
                    }
                    {
                        const stencilSdfPass = new StencilMode({
                            func: gl.ALWAYS,
                            mask: 255
                        }, 255, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
                        const colorSdfPass = new ColorMode([
                            gl.ONE,
                            gl.ONE,
                            gl.ONE,
                            gl.ONE
                        ], index.aj.transparent, [
                            false,
                            false,
                            false,
                            true
                        ], gl.MIN);
                        drawGroundEffect(painter, source, layer, coords, depthMode, stencilSdfPass, colorSdfPass, CullFaceMode.disabled, aoPass, 'sdf', opacity2, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors);
                    }
                    {
                        const srcColorFactor = aoPass ? gl.ZERO : gl.ONE_MINUS_DST_ALPHA;
                        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
                        ], index.aj.transparent, [
                            true,
                            true,
                            true,
                            true
                        ]);
                        drawGroundEffect(painter, source, layer, coords, depthMode, stencilColorPass, colorColorPass, CullFaceMode.disabled, aoPass, 'color', opacity2, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors);
                    }
                    {
                        const dstAlphaFactor = aoPass ? gl.ZERO : gl.ONE;
                        const blendEquation = aoPass ? gl.FUNC_ADD : gl.MAX;
                        const colorMode = new ColorMode([
                            gl.ONE,
                            gl.ONE,
                            gl.ONE,
                            dstAlphaFactor
                        ], index.aj.transparent, [
                            false,
                            false,
                            false,
                            true
                        ], blendEquation);
                        drawGroundEffect(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, aoPass, 'clear', opacity2, aoIntensity, aoRadius, floodLightIntensity, floodLightColor, attenuation, conflateLayer, renderNeighbors, framebufferCopyTexture);
                    }
                };
                if (aoEnabled || floodLightEnabled) {
                    painter.prepareDrawTile();
                    let framebufferCopyTexture;
                    if (terrain) {
                        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 index.T(context, new index.r({
                                width,
                                height
                            }), gl.RGBA8);
                        }
                        framebufferCopyTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
                        gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height);
                    }
                    if (aoEnabled) {
                        passDraped(true, false, framebufferCopyTexture);
                    }
                    if (floodLightEnabled) {
                        passDraped(false, true, framebufferCopyTexture);
                    }
                }
            } else {
                if (aoEnabled) {
                    passImmediate(true);
                }
                if (floodLightEnabled) {
                    passImmediate(false);
                }
                if (aoEnabled || floodLightEnabled) {
                    painter.resetStencilClippingMasks();
                }
            }
        }
    }
}
function drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode, replacementActive) {
    layer.resetLayerRenderingStats(painter);
    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' ? index.d3() : 0;
    const isGlobeProjection = tr.projection.name === 'globe';
    const globeToMercator = isGlobeProjection ? index.ae(tr.zoom) : 0;
    const mercatorCenter = [
        index.at(tr.center.lng),
        index.aA(tr.center.lat)
    ];
    const floodLightColorUseTheme = layer.paint.get('fill-extrusion-flood-light-color-use-theme').constantOr('default') === 'none';
    const floodLightColor = layer.paint.get('fill-extrusion-flood-light-color').toRenderColor(floodLightColorUseTheme ? null : layer.lut).toArray01().slice(0, 3);
    const floodLightIntensity = layer.paint.get('fill-extrusion-flood-light-intensity');
    const verticalScale = layer.paint.get('fill-extrusion-vertical-scale');
    const wallMode = layer.paint.get('fill-extrusion-line-width').constantOr(1) !== 0;
    const heightAlignment = layer.paint.get('fill-extrusion-height-alignment');
    const baseAlignment = layer.paint.get('fill-extrusion-base-alignment');
    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) {
        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');
    }
    if (wallMode) {
        baseDefines.push('RENDER_WALL_MODE');
    }
    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(painter.style, directionalLight, ambientLight);
        }
        if (!isShadowPass) {
            baseDefines.push('RENDER_SHADOWS', 'DEPTH_TEXTURE');
            if (shadowRenderer.useNormalOffset) {
                baseDefines.push('NORMAL_OFFSET');
            }
        }
        singleCascadeDefines = baseDefines.concat(['SHADOWS_SINGLE_CASCADE']);
    }
    const programName = drawDepth ? 'fillExtrusionDepth' : image ? 'fillExtrusionPattern' : 'fillExtrusion';
    const stats = layer.getLayerRenderingStats();
    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;
            terrain.setupElevationDraw(tile, program, { useMeterToDem: true });
        }
        if (!bucket.centroidVertexBuffer) {
            const attrIndex = program.attributes['a_centroid_pos'];
            if (attrIndex !== void 0)
                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);
            if (tile.imageAtlasTexture) {
                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 patternImage = index.A.from(constantPattern).getPrimary().scaleSelf(index.q.devicePixelRatio);
            const posTo = atlas.patternPositions[patternImage.serialize()];
            if (posTo)
                programConfiguration.setConstantPatternPositions(posTo);
        }
        const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient');
        const lineWidthScale = 1 / bucket.tileToMeter;
        let uniformValues;
        if (isShadowPass && shadowRenderer) {
            if (frustumCullShadowCaster(tile.tileID, bucket, painter)) {
                continue;
            }
            const tileMatrix = shadowRenderer.calculateShadowPassMatrixFromTile(tile.tileID.toUnwrapped());
            uniformValues = fillExtrusionDepthUniformValues(tileMatrix, roofEdgeRadius, lineWidthScale, verticalScale, heightAlignment, baseAlignment);
        } else {
            const matrix = painter.translatePosMatrix(coord.expandedProjMatrix, 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, lineWidthScale, coord, tile, heightLift, heightAlignment, baseAlignment, globeToMercator, mercatorCenter, invMatrix, floodLightColor, verticalScale);
            } else {
                uniformValues = fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, ao, roofEdgeRadius, lineWidthScale, coord, heightLift, heightAlignment, baseAlignment, globeToMercator, mercatorCenter, invMatrix, floodLightColor, verticalScale, floodLightIntensity, groundShadowFactor);
            }
        }
        painter.uploadCommonUniforms(context, program, coord.toUnwrapped(), null, cutoffParams);
        let segments = bucket.segments;
        if (tr.projection.name === 'mercator' && !isShadowPass) {
            segments = bucket.getVisibleSegments(tile.tileID, painter.terrain, painter.transform.getFrustum(0));
            if (!segments.get().length) {
                continue;
            }
        }
        if (stats) {
            if (!isShadowPass) {
                for (const segment of segments.get()) {
                    stats.numRenderedVerticesInTransparentPass += segment.primitiveLength;
                }
            } else {
                for (const segment of segments.get()) {
                    stats.numRenderedVerticesInShadowPass += segment.primitiveLength;
                }
            }
        }
        const dynamicBuffers = [];
        if (painter.terrain || replacementActive)
            dynamicBuffers.push(bucket.centroidVertexBuffer);
        if (isGlobeProjection)
            dynamicBuffers.push(bucket.layoutVertexExtBuffer);
        if (wallMode)
            dynamicBuffers.push(bucket.wallVertexBuffer);
        program.draw(painter, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration, dynamicBuffers);
    }
    if (painter.shadowRenderer)
        painter.shadowRenderer.useNormalOffset = false;
}
function updateReplacement(painter, source, layer, coords, layerIndex) {
    for (const coord of coords) {
        const tile = source.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket) {
            continue;
        }
        bucket.updateReplacement(coord, painter.replacementSource, layerIndex);
        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 = index.d4[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) {
                    translation = [
                        -index.ag,
                        0,
                        0
                    ];
                    regionId = 1;
                } else if (i === 1) {
                    translation = [
                        index.ag,
                        0,
                        0
                    ];
                    regionId = 0;
                } else if (i === 2) {
                    translation = [
                        0,
                        -index.ag,
                        0
                    ];
                    regionId = 3;
                } else {
                    translation = [
                        0,
                        index.ag,
                        0
                    ];
                    regionId = 2;
                }
                const segments = nGroundEffect.regionSegments[regionId];
                if (!segments)
                    continue;
                const proj = new Float32Array(16);
                index.ab.mat4.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);
            }
        }
    }
}
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;
    }
    if (terrain && demTile && demTile.dem) {
        if (bucket.selfDEMTileTimestamp !== demTile.dem._timestamp) {
            bucket.borderDoneWithNeighborZ = [
                -1,
                -1,
                -1,
                -1
            ];
            bucket.selfDEMTileTimestamp = demTile.dem._timestamp;
        }
    }
    const reconcileReplacement = (centroid1, centroid2) => {
        const hiddenFlag = (centroid1.flags | centroid2.flags) & index.d6;
        if (hiddenFlag) {
            centroid1.flags |= index.d6;
            centroid2.flags |= index.d6;
        } else {
            centroid1.flags &= ~index.d6;
            centroid2.flags &= ~index.d6;
        }
    };
    const encodeHeightAsCentroid = height => {
        return new index.P(Math.ceil((height + index.d7) * index.d8), 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);
            }
        };
        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
    ];
    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] = index.ag - b.min.x > a.max.x ? b.min.x - index.ag : 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] = index.ag - b.min.y > a.max.y ? b.min.y - index.ag : 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;
    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 ? index.ag + maxOffsetFromBorder : maxOffsetFromBorder;
        const thirdPoint = [
            verticalEdge ? coord3 : (min + max) / 2,
            verticalEdge ? (min + max) / 2 : coord3,
            0
        ];
        if (edge === 0 && maxOffsetFromBorder < 0 || edge !== 0 && maxOffsetFromBorder > 0) {
            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();
    };
    for (let i = 0; i < 4; i++) {
        const a = bucket.borderFeatureIndices[i];
        if (a.length === 0) {
            continue;
        }
        const nid = index.d4[i](coord);
        const nBucket = getLoadedBucket(nid);
        if (!nBucket || !(nBucket instanceof index.d5)) {
            continue;
        }
        const neighborDEMTile = terrain ? terrain.findDEMTileFor(nid) : null;
        if ((!neighborDEMTile || !neighborDEMTile.dem) && !reconcileReplacementState) {
            continue;
        }
        if (terrain && neighborDEMTile && neighborDEMTile.dem) {
            if (bucket.borderDEMTileTimestamp[i] !== neighborDEMTile.dem._timestamp) {
                bucket.borderDoneWithNeighborZ[i] = -1;
                bucket.borderDEMTileTimestamp[i] = neighborDEMTile.dem._timestamp;
            }
        }
        if (bucket.borderDoneWithNeighborZ[i] === nBucket.canonical.z) {
            continue;
        }
        if (nBucket.centroidVertexArray.length === 0) {
            nBucket.createCentroidsBuffer();
        }
        const j = (i < 2 ? 1 : 5) - i;
        const updateNeighbor = nBucket.borderDoneWithNeighborZ[j] !== bucket.canonical.z;
        const b = nBucket.borderFeatureIndices[j];
        let ib = 0;
        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];
            let partB;
            while (ib < b.length) {
                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]];
                let doReconcile = false;
                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;
                        doReconcile = true;
                        ib = saveIb + 1;
                    }
                } else if (count === 0) {
                    bucket.showCentroid(partA);
                    continue;
                }
                const centroidB = nBucket.centroidData[partB.centroidDataIndex];
                if (reconcileReplacementState && doReconcile) {
                    reconcileReplacement(centroidA, centroidB);
                }
                const moreThanOneBorderIntersected = partA.intersectsCount() > 1 || partB.intersectsCount() > 1;
                if (count > 1) {
                    ib = saveIb;
                    centroidA.centroidXY = centroidB.centroidXY = new index.P(0, 0);
                } else if (neighborDEMTile && neighborDEMTile.dem && !moreThanOneBorderIntersected) {
                    const span = projectCombinedSpanToBorder[i](centroidA, centroidB);
                    const edge = i % 2 ? index.ag - 1 : 0;
                    const height = flatBase(span[0], Math.min(index.ag - 1, span[1]), edge, neighborDEMTile, nid, i < 2, span[2]);
                    centroidA.centroidXY = centroidB.centroidXY = encodeHeightAsCentroid(height);
                } else if (moreThanOneBorderIntersected) {
                    centroidA.centroidXY = centroidB.centroidXY = new index.P(0, 0);
                } else {
                    centroidA.centroidXY = bucket.encodeBorderCentroid(partA);
                    centroidB.centroidXY = nBucket.encodeBorderCentroid(partB);
                }
                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;
    }
    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 = index.bR.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$1 = 2;
function adjustColorMix(colorMix) {
    return [
        colorMix[0] * index.d9,
        colorMix[1] * index.d9,
        colorMix[2] * index.d9,
        0
    ];
}
function drawRaster(painter, sourceCache, layer, tileIDs, variableOffsets, isInitialLoad) {
    if (painter.renderPass !== 'translucent')
        return;
    if (layer.paint.get('raster-opacity') === 0)
        return;
    const isGlobeProjection = painter.transform.projection.name === 'globe';
    const renderingWithElevation = layer.paint.get('raster-elevation') !== 0;
    const renderingElevatedOnGlobe = renderingWithElevation && isGlobeProjection;
    if (painter.renderElevatedRasterBackface && !renderingElevatedOnGlobe) {
        return;
    }
    const context = painter.context;
    const gl = context.gl;
    const source = sourceCache.getSource();
    const rasterConfig = configureRaster(source, layer, context, gl);
    if (source instanceof index.aJ && !tileIDs.length) {
        if (!isGlobeProjection) {
            return;
        }
    }
    const emissiveStrength = layer.paint.get('raster-emissive-strength');
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    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 (source instanceof index.aJ && !tileIDs.length && (source.onNorthPole || source.onSouthPole)) {
        const stencilMode = renderingWithElevation ? painter.stencilModeFor3D() : StencilMode.disabled;
        if (source.onNorthPole) {
            drawPole(true, null, painter, sourceCache, layer, emissiveStrength, rasterConfig, CullFaceMode.disabled, stencilMode);
        } else {
            drawPole(false, null, painter, sourceCache, layer, emissiveStrength, rasterConfig, CullFaceMode.disabled, stencilMode);
        }
        return;
    }
    if (!tileIDs.length) {
        return;
    }
    const [stencilModes, coords] = source instanceof index.aJ || renderingToTexture ? [
        {},
        tileIDs
    ] : painter.stencilConfigForOverlap(tileIDs);
    const minTileZ = coords[coords.length - 1].overscaledZ;
    if (renderingElevatedOnGlobe) {
        rasterConfig.defines.push('PROJECTION_GLOBE_VIEW');
    }
    if (renderingWithElevation) {
        rasterConfig.defines.push('RENDER_CUTOFF');
    }
    const drawTiles = (tiles, cullFaceMode, elevatedStencilMode) => {
        for (const coord of tiles) {
            const unwrappedTileID = coord.toUnwrapped();
            const tile = sourceCache.getTile(coord);
            if (renderingToTexture && !(tile && tile.hasData()))
                continue;
            context.activeTexture.set(gl.TEXTURE0);
            const textureDescriptor = getTextureDescriptor(tile, source, layer, rasterConfig);
            if (!textureDescriptor || !textureDescriptor.texture)
                continue;
            const {
                texture,
                mix: rasterColorMix,
                offset: rasterColorOffset,
                tileSize,
                buffer
            } = textureDescriptor;
            let depthMode;
            let projMatrix;
            if (renderingToTexture) {
                depthMode = DepthMode.disabled;
                projMatrix = coord.projMatrix;
            } else if (renderingWithElevation) {
                depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
                projMatrix = isGlobeProjection ? Float32Array.from(painter.transform.expandedFarZProjMatrix) : painter.transform.calculateProjMatrix(unwrappedTileID, align);
            } else {
                depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ, layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);
                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);
            texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
            context.activeTexture.set(gl.TEXTURE1);
            if (parentTile) {
                if (parentTile.texture) {
                    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 {
                texture.bind(textureFilter, gl.CLAMP_TO_EDGE);
            }
            if (texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) {
                gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
            }
            const tr = painter.transform;
            let perspectiveTransform;
            const cutoffParams = renderingWithElevation ? cutoffParamsForElevation$1(tr) : [
                0,
                0,
                0,
                0
            ];
            let normalizeMatrix;
            let globeMatrix;
            let globeMercatorMatrix;
            let mercatorCenter;
            let gridMatrix;
            let latitudinalLod = 0;
            if (renderingElevatedOnGlobe && source instanceof index.aJ && source.coordinates.length > 3) {
                normalizeMatrix = Float32Array.from(index.bb(index.cH(new index.bT(0, 0, 0))));
                globeMatrix = Float32Array.from(tr.globeMatrix);
                globeMercatorMatrix = Float32Array.from(index.cD(tr));
                mercatorCenter = [
                    index.at(tr.center.lng),
                    index.aA(tr.center.lat)
                ];
                perspectiveTransform = source.elevatedGlobePerspectiveTransform;
                gridMatrix = source.elevatedGlobeGridMatrix || new Float32Array(9);
            } else if (renderingElevatedOnGlobe) {
                const tileBounds = index.cE(coord.canonical);
                latitudinalLod = index.cF(tileBounds.getCenter().lat);
                normalizeMatrix = Float32Array.from(index.bb(index.cH(coord.canonical)));
                globeMatrix = Float32Array.from(tr.globeMatrix);
                globeMercatorMatrix = Float32Array.from(index.cD(tr));
                mercatorCenter = [
                    index.at(tr.center.lng),
                    index.aA(tr.center.lat)
                ];
                perspectiveTransform = [
                    0,
                    0
                ];
                gridMatrix = Float32Array.from(index.cG(coord.canonical, tileBounds, latitudinalLod, tr.worldSize / tr._pixelsPerMercatorPixel));
            } else {
                perspectiveTransform = source instanceof index.aJ ? source.perspectiveTransform : [
                    0,
                    0
                ];
                normalizeMatrix = new Float32Array(16);
                globeMatrix = new Float32Array(9);
                globeMercatorMatrix = new Float32Array(16);
                mercatorCenter = [
                    0,
                    0
                ];
                gridMatrix = new Float32Array(9);
            }
            const uniformValues = rasterUniformValues(projMatrix, normalizeMatrix, globeMatrix, globeMercatorMatrix, gridMatrix, parentTL || [
                0,
                0
            ], index.ae(painter.transform.zoom), mercatorCenter, cutoffParams, parentScaleBy || 1, fade, layer, perspectiveTransform, renderingWithElevation ? layer.paint.get('raster-elevation') : 0, RASTER_COLOR_TEXTURE_UNIT$1, rasterColorMix, rasterColorOffset, rasterConfig.range, tileSize, buffer, emissiveStrength);
            const affectedByFog = painter.isTileAffectedByFog(coord);
            const program = painter.getOrCreateProgram('raster', {
                defines: rasterConfig.defines,
                overrideFog: affectedByFog
            });
            painter.uploadCommonUniforms(context, program, unwrappedTileID);
            if (source instanceof index.aJ) {
                const elevatedGlobeVertexBuffer = source.elevatedGlobeVertexBuffer;
                const elevatedGlobeIndexBuffer = source.elevatedGlobeIndexBuffer;
                if (renderingToTexture || !isGlobeProjection) {
                    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 if (elevatedGlobeVertexBuffer && elevatedGlobeIndexBuffer) {
                    const segments = tr.zoom <= index.c6 ? source.elevatedGlobeSegments : source.getSegmentsForLongitude(tr.center.lng);
                    if (segments) {
                        program.draw(painter, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, cullFaceMode, uniformValues, layer.id, elevatedGlobeVertexBuffer, elevatedGlobeIndexBuffer, segments);
                    }
                }
            } else if (renderingElevatedOnGlobe) {
                depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadOnly, painter.depthRangeFor3D);
                const sharedBuffers = painter.globeSharedBuffers;
                if (sharedBuffers) {
                    const [buffer2, indexBuffer, segments] = sharedBuffers.getGridBuffers(latitudinalLod, false);
                    program.draw(painter, gl.TRIANGLES, depthMode, elevatedStencilMode || stencilMode, painter.colorModeForRenderPass(), cullFaceMode, uniformValues, layer.id, buffer2, indexBuffer, segments);
                }
            } else {
                const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = painter.getTileBoundsBuffers(tile);
                program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
            }
        }
        if (!(source instanceof index.aJ) && renderingElevatedOnGlobe) {
            for (const coord of tiles) {
                const topCap = coord.canonical.y === 0;
                const bottomCap = coord.canonical.y === (1 << coord.canonical.z) - 1;
                if (topCap) {
                    drawPole(true, coord, painter, sourceCache, layer, emissiveStrength, rasterConfig, cullFaceMode, elevatedStencilMode || StencilMode.disabled);
                }
                if (bottomCap) {
                    drawPole(false, coord, painter, sourceCache, layer, emissiveStrength, rasterConfig, cullFaceMode === CullFaceMode.frontCW ? CullFaceMode.backCW : CullFaceMode.frontCW, elevatedStencilMode || StencilMode.disabled);
                }
            }
        }
    };
    if (renderingElevatedOnGlobe) {
        if (painter.renderElevatedRasterBackface) {
            drawTiles(coords, CullFaceMode.backCW, painter.stencilModeFor3D());
        } else {
            drawTiles(coords, CullFaceMode.frontCW, painter.stencilModeFor3D());
        }
    } else {
        drawTiles(coords, CullFaceMode.disabled, void 0);
    }
    painter.resetStencilClippingMasks();
}
function drawPole(isNorth, coord, painter, sourceCache, layer, emissiveStrength, rasterConfig, cullFaceMode, stencilMode) {
    const source = sourceCache.getSource();
    const sharedBuffers = painter.globeSharedBuffers;
    if (!sharedBuffers)
        return;
    let tile;
    if (coord) {
        tile = sourceCache.getTile(coord);
    }
    let texture;
    let globeMatrix;
    if (source instanceof index.aJ) {
        texture = source.texture;
        globeMatrix = index.cI(0, 0, painter.transform);
    } else if (tile && coord) {
        texture = tile.texture;
        globeMatrix = index.cI(coord.canonical.z, coord.canonical.x, painter.transform);
    }
    if (!texture || !globeMatrix)
        return;
    if (!isNorth) {
        globeMatrix = index.ab.mat4.scale(index.ab.mat4.create(), globeMatrix, [
            1,
            -1,
            1
        ]);
    }
    const context = painter.context;
    const gl = context.gl;
    const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR;
    const colorMode = painter.colorModeForDrapableLayerRenderPass(emissiveStrength);
    const defines = rasterConfig.defines;
    defines.push('GLOBE_POLES');
    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    const projMatrix = Float32Array.from(painter.transform.expandedFarZProjMatrix);
    const normalizeMatrix = Float32Array.from(index.bb(index.cH(new index.bT(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);
    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] = coord ? sharedBuffers.getPoleBuffers(coord.canonical.z, false) : sharedBuffers.getPoleBuffers(0, true);
    const elevation = layer.paint.get('raster-elevation');
    let vertexBuffer;
    if (isNorth) {
        vertexBuffer = northPoleBuffer;
        painter.renderDefaultNorthPole = elevation !== 0;
    } else {
        vertexBuffer = southPoleBuffer;
        painter.renderDefaultSouthPole = elevation !== 0;
    }
    const rasterColorMix = adjustColorMix(rasterConfig.mix);
    const uniformValues = rasterPoleUniformValues(projMatrix, normalizeMatrix, globeMatrix, index.ae(painter.transform.zoom), fade, layer, [
        0,
        0
    ], elevation, RASTER_COLOR_TEXTURE_UNIT$1, rasterColorMix, rasterConfig.offset, rasterConfig.range, emissiveStrength);
    const program = painter.getOrCreateProgram('raster', { defines });
    painter.uploadCommonUniforms(context, program, null);
    program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, layer.id, vertexBuffer, indexBuffer, segment);
}
function cutoffParamsForElevation$1(tr) {
    const near = tr._nearZ;
    const far = tr.projection.farthestPixelDistance(tr);
    const zRange = far - near;
    const fadeRangePixels = tr.height * 0.2;
    const cutoffDistance = near + fadeRangePixels;
    const relativeCutoffDistance = (cutoffDistance - near) / zRange;
    const relativeCutoffFadeDistance = (cutoffDistance - fadeRangePixels - near) / zRange;
    return [
        near,
        far,
        relativeCutoffFadeDistance,
        relativeCutoffDistance
    ];
}
function prepare$3(layer, sourceCache, _) {
    const source = sourceCache.getSource();
    if (!(source instanceof RasterArrayTileSource) || !source.loaded())
        return;
    const sourceLayer = layer.sourceLayer || source.rasterLayerIds && source.rasterLayerIds[0];
    if (!sourceLayer)
        return;
    const band = layer.paint.get('raster-array-band') || source.getInitialBand(sourceLayer);
    if (band == null)
        return;
    const tiles = sourceCache.getIds().map(id => sourceCache.getTileByID(id));
    for (const tile of tiles) {
        if (tile.updateNeeded(sourceLayer, band)) {
            source.prepareTile(tile, sourceLayer, band);
        }
    }
}
function getTextureDescriptor(tile, source, layer, rasterConfig) {
    if (!tile)
        return;
    if (source instanceof RasterArrayTileSource && tile instanceof RasterArrayTile) {
        return source.getTextureDescriptor(tile, layer, true);
    }
    return {
        texture: tile.texture,
        mix: adjustColorMix(rasterConfig.mix),
        offset: rasterConfig.offset,
        buffer: 0,
        tileSize: 1
    };
}
function configureRaster(source, layer, context, gl) {
    const isRasterColor = layer.paint.get('raster-color');
    const isRasterArray = source.type === 'raster-array';
    const defines = [];
    const inputResampling = layer.paint.get('raster-resampling');
    const inputMix = layer.paint.get('raster-color-mix');
    let range = layer.paint.get('raster-color-range');
    const mix = [
        inputMix[0],
        inputMix[1],
        inputMix[2],
        0
    ];
    const offset = inputMix[3];
    let resampling = inputResampling === 'nearest' ? gl.NEAREST : gl.LINEAR;
    if (isRasterArray) {
        defines.push('RASTER_ARRAY');
        if (!isRasterColor)
            defines.push('RASTER_COLOR');
        if (inputResampling === 'linear')
            defines.push('RASTER_ARRAY_LINEAR');
        resampling = gl.NEAREST;
        if (!range) {
            if (source.rasterLayers) {
                const foundLayer = source.rasterLayers.find(({id}) => id === layer.sourceLayer);
                if (foundLayer && foundLayer.fields && foundLayer.fields.range) {
                    range = foundLayer.fields.range;
                }
            }
        }
    }
    range = range || [
        0,
        1
    ];
    if (isRasterColor) {
        defines.push('RASTER_COLOR');
        context.activeTexture.set(gl.TEXTURE2);
        layer.updateColorRamp(range);
        let tex = layer.colorRampTexture;
        if (!tex)
            tex = layer.colorRampTexture = new index.T(context, layer.colorRamp, gl.RGBA8);
        tex.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    }
    return {
        mix,
        range,
        offset,
        defines,
        resampling
    };
}

var particleAttributes = index.da([{
        name: 'a_index',
        type: 'Int16',
        components: 1
    }]);

class RasterParticleState {
    constructor(context, id, textureSize, RGBAPositions) {
        const emptyImage = {
            width: textureSize[0],
            height: textureSize[1],
            data: null
        };
        const gl = context.gl;
        this.targetColorTexture = new index.T(context, emptyImage, gl.RGBA8, { useMipmap: false });
        this.backgroundColorTexture = new index.T(context, emptyImage, gl.RGBA8, { useMipmap: false });
        this.context = context;
        this.updateParticleTexture(id, RGBAPositions);
        this.lastInvalidatedAt = 0;
    }
    updateParticleTexture(id, RGBAPositions) {
        if (this.particleTextureDimension === RGBAPositions.width) {
            return;
        }
        if (this.particleTexture0 || this.particleTexture1 || this.particleIndexBuffer || this.particleSegment) {
            this.particleTexture0.destroy();
            this.particleTexture1.destroy();
            this.particleIndexBuffer.destroy();
            this.particleSegment.destroy();
        }
        const gl = this.context.gl;
        const numParticles = RGBAPositions.width * RGBAPositions.height;
        this.particleTexture0 = new index.T(this.context, RGBAPositions, gl.RGBA8, {
            premultiply: false,
            useMipmap: false
        });
        this.particleTexture1 = new index.T(this.context, RGBAPositions, gl.RGBA8, {
            premultiply: false,
            useMipmap: false
        });
        const particleIndices = new index.db();
        particleIndices.reserve(numParticles);
        for (let i = 0; i < numParticles; i++) {
            particleIndices.emplaceBack(i);
        }
        this.particleIndexBuffer = this.context.createVertexBuffer(particleIndices, particleAttributes.members, true);
        this.particleSegment = index.b7.simpleSegment(0, 0, this.particleIndexBuffer.length, 0);
        this.particleTextureDimension = RGBAPositions.width;
    }
    update(layerLastInvalidatedAt) {
        if (this.lastInvalidatedAt < layerLastInvalidatedAt) {
            this.lastInvalidatedAt = index.q.now();
            return false;
        }
        return true;
    }
    destroy() {
        this.targetColorTexture.destroy();
        this.backgroundColorTexture.destroy();
        this.particleIndexBuffer.destroy();
        this.particleTexture0.destroy();
        this.particleTexture1.destroy();
        this.particleSegment.destroy();
    }
}

const VELOCITY_TEXTURE_UNIT = 0;
const RASTER_PARTICLE_TEXTURE_UNIT = 1;
const RASTER_COLOR_TEXTURE_UNIT = 2;
const SPEED_MAX_VALUE = 0.15;
function drawRasterParticle(painter, sourceCache, layer, tileIDs, _, isInitialLoad) {
    if (painter.renderPass === 'offscreen') {
        renderParticlesToTexture(painter, sourceCache, layer, tileIDs);
    }
    if (painter.renderPass === 'translucent') {
        renderTextureToMap(painter, sourceCache, layer, tileIDs);
        painter.style.map.triggerRepaint();
    }
}
function createPositionRGBAData(textureDimension) {
    const numParticles = textureDimension * textureDimension;
    const RGBAPositions = new Uint8Array(4 * numParticles);
    const esgtsa = function (s) {
        s |= 0;
        s = Math.imul(s ^ 2747636419, 2654435769);
        s = Math.imul(s ^ s >>> 16, 2654435769);
        s = Math.imul(s ^ s >>> 16, 2654435769);
        return (s >>> 0) / 4294967296;
    };
    const invScale = 1 / RASTER_PARTICLE_POS_SCALE;
    for (let i = 0; i < numParticles; i++) {
        const x = invScale * (esgtsa(2 * i + 0) + RASTER_PARTICLE_POS_OFFSET);
        const y = invScale * (esgtsa(2 * i + 1) + RASTER_PARTICLE_POS_OFFSET);
        const rx = x;
        const ry = x * 255 % 1;
        const rz = y;
        const rw = y * 255 % 1;
        const px = rx - ry / 255;
        const py = ry;
        const pz = rz - rw / 255;
        const pw = rw;
        RGBAPositions[4 * i + 0] = 255 * px;
        RGBAPositions[4 * i + 1] = 255 * py;
        RGBAPositions[4 * i + 2] = 255 * pz;
        RGBAPositions[4 * i + 3] = 255 * pw;
    }
    return RGBAPositions;
}
function renderParticlesToTexture(painter, sourceCache, layer, tileIDs) {
    if (!tileIDs.length) {
        return;
    }
    const context = painter.context;
    const gl = context.gl;
    const source = sourceCache.getSource();
    if (!(source instanceof RasterArrayTileSource))
        return;
    const particleTextureDimension = Math.ceil(Math.sqrt(layer.paint.get('raster-particle-count')));
    let particlePositionRGBAImage = layer.particlePositionRGBAImage;
    if (!particlePositionRGBAImage || particlePositionRGBAImage.width !== particleTextureDimension) {
        const RGBAData = createPositionRGBAData(particleTextureDimension);
        const imageSize = {
            width: particleTextureDimension,
            height: particleTextureDimension
        };
        particlePositionRGBAImage = layer.particlePositionRGBAImage = new index.r(imageSize, RGBAData);
    }
    let particleFramebuffer = layer.particleFramebuffer;
    if (!particleFramebuffer) {
        particleFramebuffer = layer.particleFramebuffer = context.createFramebuffer(particleTextureDimension, particleTextureDimension, true, null);
    } else if (particleFramebuffer.width !== particleTextureDimension) {
        particleFramebuffer.destroy();
        particleFramebuffer = layer.particleFramebuffer = context.createFramebuffer(particleTextureDimension, particleTextureDimension, true, null);
    }
    const tiles = [];
    for (const id of tileIDs) {
        const tile = sourceCache.getTile(id);
        if (!(tile instanceof RasterArrayTile))
            continue;
        const data = getTileData(tile, source, layer);
        if (!data)
            continue;
        const textureSize = [
            tile.tileSize,
            tile.tileSize
        ];
        let tileFramebuffer = layer.tileFramebuffer;
        if (!tileFramebuffer) {
            const fbWidth = textureSize[0];
            const fbHeight = textureSize[1];
            tileFramebuffer = layer.tileFramebuffer = context.createFramebuffer(fbWidth, fbHeight, true, null);
        }
        let state = tile.rasterParticleState;
        if (!state) {
            state = tile.rasterParticleState = new RasterParticleState(context, id, textureSize, particlePositionRGBAImage);
        }
        const renderBackground2 = state.update(layer.lastInvalidatedAt);
        if (state.particleTextureDimension !== particleTextureDimension) {
            state.updateParticleTexture(id, particlePositionRGBAImage);
        }
        const t = state.targetColorTexture;
        state.targetColorTexture = state.backgroundColorTexture;
        state.backgroundColorTexture = t;
        const p = state.particleTexture0;
        state.particleTexture0 = state.particleTexture1;
        state.particleTexture1 = p;
        tiles.push([
            id,
            data,
            state,
            renderBackground2
        ]);
    }
    if (tiles.length === 0) {
        return;
    }
    const now = index.q.now();
    const frameDeltaSeconds = layer.previousDrawTimestamp ? 0.001 * (now - layer.previousDrawTimestamp) : 0.0167;
    layer.previousDrawTimestamp = now;
    if (layer.hasColorMap()) {
        context.activeTexture.set(gl.TEXTURE0 + RASTER_COLOR_TEXTURE_UNIT);
        let tex = layer.colorRampTexture;
        if (!tex)
            tex = layer.colorRampTexture = new index.T(context, layer.colorRamp, gl.RGBA8);
        tex.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    }
    context.bindFramebuffer.set(layer.tileFramebuffer.framebuffer);
    renderBackground(painter, layer, tiles);
    renderParticles(painter, sourceCache, layer, tiles);
    context.bindFramebuffer.set(layer.particleFramebuffer.framebuffer);
    updateParticles(painter, layer, tiles, frameDeltaSeconds);
}
function getTileData(tile, source, layer) {
    if (!tile) {
        return null;
    }
    const textureDesc = source.getTextureDescriptor(tile, layer, true);
    if (!textureDesc) {
        return null;
    }
    let {texture, mix, offset, tileSize, buffer, format} = textureDesc;
    if (!texture || !format) {
        return null;
    }
    let scalarData = false;
    if (format === 'uint32') {
        scalarData = true;
        mix[3] = 0;
        mix = computeRasterColorMix(index.dc, mix, [
            0,
            layer.paint.get('raster-particle-max-speed')
        ]);
        offset = computeRasterColorOffset(index.dc, offset, [
            0,
            layer.paint.get('raster-particle-max-speed')
        ]);
    }
    const dataFormatDefine = {
        uint8: 'DATA_FORMAT_UINT8',
        uint16: 'DATA_FORMAT_UINT16',
        uint32: 'DATA_FORMAT_UINT32'
    }[format];
    return {
        texture,
        textureOffset: [
            buffer / (tileSize + 2 * buffer),
            tileSize / (tileSize + 2 * buffer)
        ],
        tileSize,
        scalarData,
        scale: mix,
        offset,
        defines: [
            'RASTER_ARRAY',
            dataFormatDefine
        ]
    };
}
function renderBackground(painter, layer, tiles) {
    const context = painter.context;
    const gl = context.gl;
    const framebuffer = layer.tileFramebuffer;
    context.activeTexture.set(gl.TEXTURE0);
    const textureUnit = 0;
    const opacityValue = fadeOpacityCurve(layer.paint.get('raster-particle-fade-opacity-factor'));
    const uniforms = rasterParticleTextureUniformValues(textureUnit, opacityValue);
    const program = painter.getOrCreateProgram('rasterParticleTexture', {
        defines: [],
        overrideFog: false
    });
    for (const tile of tiles) {
        const [, , particleState, renderBackground2] = tile;
        framebuffer.colorAttachment.set(particleState.targetColorTexture.texture);
        context.viewport.set([
            0,
            0,
            framebuffer.width,
            framebuffer.height
        ]);
        context.clear({ color: index.aj.transparent });
        if (!renderBackground2)
            continue;
        particleState.backgroundColorTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
        program.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniforms, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments);
    }
}
function fadeOpacityCurve(fadeOpacityFactor) {
    const x = fadeOpacityFactor;
    const a = 0.05;
    return (1 + a) * x / (x + a);
}
function resetRateCurve(resetRate) {
    return Math.pow(resetRate, 6);
}
function renderParticles(painter, sourceCache, layer, tiles) {
    const context = painter.context;
    const gl = context.gl;
    const framebuffer = layer.tileFramebuffer;
    const isGlobeProjection = painter.transform.projection.name === 'globe';
    const maxSpeed = layer.paint.get('raster-particle-max-speed');
    for (const targetTile of tiles) {
        const [targetTileID, targetTileData, targetTileState] = targetTile;
        context.activeTexture.set(gl.TEXTURE0 + VELOCITY_TEXTURE_UNIT);
        targetTileData.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        framebuffer.colorAttachment.set(targetTileState.targetColorTexture.texture);
        const defines = targetTileData.defines;
        const program = painter.getOrCreateProgram('rasterParticleDraw', {
            defines,
            overrideFog: false
        });
        context.activeTexture.set(gl.TEXTURE0 + RASTER_PARTICLE_TEXTURE_UNIT);
        const tileIDs = targetTileData.scalarData ? [] : [
            0,
            1,
            2,
            3
        ].map(idx => index.d4[idx](targetTileID));
        tileIDs.push(targetTileID);
        const x = targetTileID.canonical.x;
        const y = targetTileID.canonical.y;
        for (const tileID of tileIDs) {
            const tile = sourceCache.getTile(isGlobeProjection ? tileID.wrapped() : tileID);
            if (!tile)
                continue;
            const state = tile.rasterParticleState;
            if (!state)
                continue;
            const wrapDelta = tileID.wrap - targetTileID.wrap;
            const nx = tileID.canonical.x + (1 << tileID.canonical.z) * wrapDelta;
            const ny = tileID.canonical.y;
            state.particleTexture0.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
            const rasterParticleTextureRes = state.particleTexture0.size;
            const rasterParticleTextureSideLen = rasterParticleTextureRes[0];
            const tileOffset = [
                nx - x,
                ny - y
            ];
            const uniforms = rasterParticleDrawUniformValues(RASTER_PARTICLE_TEXTURE_UNIT, rasterParticleTextureSideLen, tileOffset, VELOCITY_TEXTURE_UNIT, targetTileData.texture.size, RASTER_COLOR_TEXTURE_UNIT, maxSpeed, targetTileData.textureOffset, targetTileData.scale, targetTileData.offset);
            program.draw(painter, gl.POINTS, DepthMode.disabled, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniforms, layer.id, state.particleIndexBuffer, void 0, state.particleSegment);
        }
    }
}
function updateParticles(painter, layer, tiles, frameDeltaSeconds) {
    const context = painter.context;
    const gl = context.gl;
    const maxSpeed = layer.paint.get('raster-particle-max-speed');
    const speedFactor = frameDeltaSeconds * layer.paint.get('raster-particle-speed-factor') * SPEED_MAX_VALUE;
    const resetRateFactor = layer.paint.get('raster-particle-reset-rate-factor');
    const resetRate = resetRateCurve(0.01 + resetRateFactor * 1);
    const particleFramebuffer = layer.particleFramebuffer;
    context.viewport.set([
        0,
        0,
        particleFramebuffer.width,
        particleFramebuffer.height
    ]);
    for (const tile of tiles) {
        const [, data, state] = tile;
        context.activeTexture.set(gl.TEXTURE0 + VELOCITY_TEXTURE_UNIT);
        data.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        context.activeTexture.set(gl.TEXTURE0 + RASTER_PARTICLE_TEXTURE_UNIT);
        const particleTexture = state.particleTexture0;
        particleTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
        const uniforms = rasterParticleUpdateUniformValues(RASTER_PARTICLE_TEXTURE_UNIT, particleTexture.size[0], VELOCITY_TEXTURE_UNIT, data.texture.size, maxSpeed, speedFactor, resetRate, data.textureOffset, data.scale, data.offset);
        particleFramebuffer.colorAttachment.set(state.particleTexture1.texture);
        context.clear({ color: index.aj.transparent });
        const updateProgram = painter.getOrCreateProgram('rasterParticleUpdate', { defines: data.defines });
        updateProgram.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.unblended, CullFaceMode.disabled, uniforms, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments);
    }
}
function renderTextureToMap(painter, sourceCache, layer, tileIDs, _) {
    const context = painter.context;
    const gl = context.gl;
    const tileSize = sourceCache.getSource().tileSize;
    const minLiftForZoom = (1 - index.ac(index.bY, index.bY + 1, painter.transform.zoom)) * 5 * tileSize;
    const rasterElevation = minLiftForZoom + layer.paint.get('raster-particle-elevation');
    const align = !painter.options.moving;
    const isGlobeProjection = painter.transform.projection.name === 'globe';
    if (!tileIDs.length) {
        return;
    }
    const [stencilModes, coords] = painter.stencilConfigForOverlap(tileIDs);
    const defines = [];
    if (isGlobeProjection) {
        defines.push('PROJECTION_GLOBE_VIEW');
    }
    const stencilMode = painter.stencilModeFor3D();
    for (const coord of coords) {
        const unwrappedTileID = coord.toUnwrapped();
        const tile = sourceCache.getTile(coord);
        if (!tile.rasterParticleState)
            continue;
        const particleState = tile.rasterParticleState;
        const rasterFadeDuration = 100;
        tile.registerFadeDuration(rasterFadeDuration);
        const parentTile = sourceCache.findLoadedParent(coord, 0);
        const fade = rasterFade(tile, parentTile, sourceCache, painter.transform, rasterFadeDuration);
        if (painter.terrain)
            painter.terrain.prepareDrawTile();
        context.activeTexture.set(gl.TEXTURE0);
        particleState.targetColorTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        context.activeTexture.set(gl.TEXTURE1);
        let parentScaleBy, parentTL;
        if (parentTile && parentTile.rasterParticleState) {
            parentTile.rasterParticleState.targetColorTexture.bind(gl.LINEAR, 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 {
            particleState.targetColorTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        }
        const projMatrix = isGlobeProjection ? Float32Array.from(painter.transform.expandedFarZProjMatrix) : painter.transform.calculateProjMatrix(unwrappedTileID, align);
        const tr = painter.transform;
        const cutoffParams = cutoffParamsForElevation(tr);
        const tileBounds = index.cE(coord.canonical);
        const latitudinalLod = index.cF(tileBounds.getCenter().lat);
        let normalizeMatrix;
        let globeMatrix;
        let globeMercatorMatrix;
        let mercatorCenter;
        let gridMatrix;
        if (isGlobeProjection) {
            normalizeMatrix = Float32Array.from(index.bb(index.cH(coord.canonical)));
            globeMatrix = Float32Array.from(tr.globeMatrix);
            globeMercatorMatrix = Float32Array.from(index.cD(tr));
            mercatorCenter = [
                index.at(tr.center.lng),
                index.aA(tr.center.lat)
            ];
            gridMatrix = Float32Array.from(index.cG(coord.canonical, tileBounds, latitudinalLod, tr.worldSize / tr._pixelsPerMercatorPixel));
        } else {
            normalizeMatrix = new Float32Array(16);
            globeMatrix = new Float32Array(9);
            globeMercatorMatrix = new Float32Array(16);
            mercatorCenter = [
                0,
                0
            ];
            gridMatrix = new Float32Array(9);
        }
        const uniformValues = rasterParticleUniformValues(projMatrix, normalizeMatrix, globeMatrix, globeMercatorMatrix, gridMatrix, parentTL || [
            0,
            0
        ], index.ae(painter.transform.zoom), mercatorCenter, cutoffParams, parentScaleBy || 1, fade, rasterElevation);
        const overrideFog = painter.isTileAffectedByFog(coord);
        const program = painter.getOrCreateProgram('rasterParticle', {
            defines,
            overrideFog
        });
        painter.uploadCommonUniforms(context, program, unwrappedTileID);
        if (isGlobeProjection) {
            const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadOnly, painter.depthRangeFor3D);
            const skirtHeightValue = 0;
            const sharedBuffers = painter.globeSharedBuffers;
            if (sharedBuffers) {
                const [buffer, indexBuffer, segments] = sharedBuffers.getGridBuffers(latitudinalLod, skirtHeightValue !== 0);
                program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, painter.renderElevatedRasterBackface ? CullFaceMode.frontCCW : CullFaceMode.backCCW, uniformValues, layer.id, buffer, indexBuffer, segments);
            }
        } else {
            const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
            const stencilMode2 = stencilModes[coord.overscaledZ];
            const {tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments} = painter.getTileBoundsBuffers(tile);
            program.draw(painter, gl.TRIANGLES, depthMode, stencilMode2, ColorMode.alphaBlended, CullFaceMode.disabled, uniformValues, layer.id, tileBoundsBuffer, tileBoundsIndexBuffer, tileBoundsSegments);
        }
    }
    painter.resetStencilClippingMasks();
}
function cutoffParamsForElevation(tr) {
    const near = tr._nearZ;
    const far = tr.projection.farthestPixelDistance(tr);
    const zRange = far - near;
    const fadeRangePixels = tr.height * 0.2;
    const cutoffDistance = near + fadeRangePixels;
    const relativeCutoffDistance = (cutoffDistance - near) / zRange;
    const relativeCutoffFadeDistance = (cutoffDistance - fadeRangePixels - near) / zRange;
    return [
        near,
        far,
        relativeCutoffFadeDistance,
        relativeCutoffDistance
    ];
}
function prepare$2(layer, sourceCache, _) {
    const source = sourceCache.getSource();
    if (!(source instanceof RasterArrayTileSource) || !source.loaded())
        return;
    const sourceLayer = layer.sourceLayer || source.rasterLayerIds && source.rasterLayerIds[0];
    if (!sourceLayer)
        return;
    const band = layer.paint.get('raster-particle-array-band') || source.getInitialBand(sourceLayer);
    if (band == null)
        return;
    const tiles = sourceCache.getIds().map(id => sourceCache.getTileByID(id));
    for (const tile of tiles) {
        if (tile.updateNeeded(sourceLayer, band)) {
            source.prepareTile(tile, sourceLayer, band);
        }
    }
}

function drawBackground(painter, sourceCache, layer, coords) {
    const color = layer.paint.get('background-color');
    const ignoreLut = layer.paint.get('background-color-use-theme').constantOr('default') === 'none';
    const opacity = layer.paint.get('background-opacity');
    const emissiveStrength = layer.paint.get('background-emissive-strength');
    const isViewportPitch = layer.paint.get('background-pitch-alignment') === 'viewport';
    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');
    let patternPosition;
    if (image !== void 0) {
        if (image === null) {
            return;
        }
        patternPosition = painter.imageManager.getPattern(image.toString(), layer.scope, painter.style.getLut(layer.scope));
        if (!patternPosition) {
            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);
    }
    if (isViewportPitch) {
        const program = painter.getOrCreateProgram(programName, {
            overrideFog: false,
            overrideRtt: true
        });
        const matrix = new Float32Array(index.ab.mat4.identity([]));
        const tileID = new index.aG(0, 0, 0, 0, 0);
        const uniformValues = image ? backgroundPatternUniformValues(matrix, emissiveStrength, opacity, painter, image, layer.scope, patternPosition, isViewportPitch, {
            tileID,
            tileSize
        }) : backgroundUniformValues(matrix, emissiveStrength, opacity, color.toRenderColor(ignoreLut ? null : layer.lut));
        program.draw(painter, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments);
        return;
    }
    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, patternPosition, isViewportPitch, {
            tileID,
            tileSize
        }) : backgroundUniformValues(matrix, emissiveStrength, opacity, color.toRenderColor(ignoreLut ? null : layer.lut));
        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 index.aj(1, 0, 0, 1);
const btmColor = new index.aj(0, 1, 0, 1);
const leftColor = new index.aj(0, 0, 1, 1);
const rightColor = new index.aj(1, 0, 1, 1);
const centerColor = new index.aj(0, 1, 1, 1);
function drawDebug(painter, sourceCache, coords, color, silhouette, showParseStatus) {
    for (let i = 0; i < coords.length; i++) {
        if (silhouette) {
            const radius = 1;
            const darkenFactor = 0.8;
            const colorMiddle = new index.aj(color.r * darkenFactor, color.g * darkenFactor, color.b * darkenFactor, 1);
            drawDebugTile(painter, sourceCache, coords[i], color, -radius, -radius, showParseStatus);
            drawDebugTile(painter, sourceCache, coords[i], color, -radius, radius, showParseStatus);
            drawDebugTile(painter, sourceCache, coords[i], color, radius, radius, showParseStatus);
            drawDebugTile(painter, sourceCache, coords[i], color, radius, -radius, showParseStatus);
            drawDebugTile(painter, sourceCache, coords[i], colorMiddle, 0, 0, showParseStatus);
        } else {
            drawDebugTile(painter, sourceCache, coords[i], color, 0, 0, showParseStatus);
        }
    }
}
function drawDebugPadding(painter) {
    const padding = painter.transform.padding;
    const lineWidth = 3;
    drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor);
    drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor);
    drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor);
    drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor);
    const center = painter.transform.centerPoint;
    drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor);
}
function drawDebugTile(painter, sourceCache, coord, color, offsetX, offsetY, showParseStatus) {
    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 = index.ab.mat4.clone(coord.projMatrix);
    if (isGlobeProjection && index.ae(tr.zoom) > 0) {
        const bounds = index.ba(coord.canonical, tr);
        const decode = index.dd(bounds);
        posMatrix = index.ab.mat4.multiply(new Float32Array(16), tr.globeMatrix, decode);
        index.ab.mat4.multiply(posMatrix, tr.projMatrix, posMatrix);
    }
    const jitterMatrix = index.ab.mat4.create();
    jitterMatrix[12] += 2 * offsetX / (index.q.devicePixelRatio * tr.width);
    jitterMatrix[13] += 2 * offsetY / (index.q.devicePixelRatio * tr.height);
    index.ab.mat4.multiply(posMatrix, jitterMatrix, 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);
    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), id, debugBuffer, debugIndexBuffer, debugSegments, null, null, null, [tile._globeTileDebugBorderBuffer]);
    if (showParseStatus) {
        const tileRawData = tile.latestRawTileData;
        const tileByteLength = tileRawData && tileRawData.byteLength || 0;
        const tileSizeKb = Math.floor(tileByteLength / 1024);
        let tileLabel = coord.canonical.toString();
        if (coord.overscaledZ !== coord.canonical.z) {
            tileLabel += ` => ${ coord.overscaledZ }`;
        }
        tileLabel += ` ${ tile.state }`;
        tileLabel += ` ${ tileSizeKb }kb`;
        drawTextToOverlay(painter, tileLabel);
    }
    const tileSize = sourceCache.getTile(coord).tileSize;
    const scaleRatio = 512 / Math.min(tileSize, 512) * (coord.overscaledZ / tr.zoom) * 0.5;
    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, index.aj.transparent, scaleRatio), id, debugTextBuffer, debugTextIndexBuffer, debugTextSegments, null, null, null, [tile._globeTileDebugTextBuffer]);
}
function drawCrosshair(painter, x, y, color) {
    const size = 20;
    const lineWidth = 2;
    drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color);
    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 * index.q.devicePixelRatio, y * index.q.devicePixelRatio, width * index.q.devicePixelRatio, height * index.q.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.isDraped(sourceCache))) {
        index.w('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(), index.ae(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 index.aa(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(), index.ae(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 = index.da([{
        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 index.de();
        this.indices = new index.aU();
        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);
        this.indices.emplaceBack(5, 1, 3);
        this.indices.emplaceBack(3, 7, 5);
        this.indices.emplaceBack(6, 2, 0);
        this.indices.emplaceBack(0, 4, 6);
        this.indices.emplaceBack(2, 6, 7);
        this.indices.emplaceBack(7, 3, 2);
        this.indices.emplaceBack(5, 4, 0);
        this.indices.emplaceBack(0, 1, 5);
        this.indices.emplaceBack(0, 2, 3);
        this.indices.emplaceBack(3, 1, 0);
        this.indices.emplaceBack(7, 6, 4);
        this.indices.emplaceBack(4, 5, 7);
        this.vertexBuffer = context.createVertexBuffer(this.vertexArray, members);
        this.indexBuffer = context.createIndexBuffer(this.indices);
        this.segment = index.b7.simpleSegment(0, 0, 36, 12);
    }
}

function drawSky(painter, sourceCache, layer) {
    const tr = painter.transform;
    const transitionOpacity = !painter._atmosphere ? 1 : index.ae(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');
    if (!layer.skyboxGeometry) {
        layer.skyboxGeometry = new SkyboxGeometry(context);
    }
    context.activeTexture.set(gl.TEXTURE0);
    let colorRampTexture = layer.colorRampTexture;
    if (!colorRampTexture) {
        colorRampTexture = layer.colorRampTexture = new index.T(context, layer.colorRamp, gl.RGBA8);
    }
    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(index.ab.mat3.fromMat4(index.ab.mat3.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;
    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;
            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);
    index.ab.mat4.identity(faceRotate);
    index.ab.mat4.rotateY(faceRotate, faceRotate, -Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 0);
    index.ab.mat4.identity(faceRotate);
    index.ab.mat4.rotateY(faceRotate, faceRotate, Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 1);
    index.ab.mat4.identity(faceRotate);
    index.ab.mat4.rotateX(faceRotate, faceRotate, -Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 2);
    index.ab.mat4.identity(faceRotate);
    index.ab.mat4.rotateX(faceRotate, faceRotate, Math.PI * 0.5);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 3);
    index.ab.mat4.identity(faceRotate);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 4);
    index.ab.mat4.identity(faceRotate);
    index.ab.mat4.rotateY(faceRotate, faceRotate, Math.PI);
    drawSkyboxFace(painter, layer, program, faceRotate, sunDirection, 5);
    context.viewport.set([
        0,
        0,
        painter.width,
        painter.height
    ]);
}

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

class AtmosphereBuffer {
    constructor(context) {
        const vertices = new index.df();
        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 index.aU();
        triangles.emplaceBack(0, 1, 2);
        triangles.emplaceBack(2, 3, 0);
        this.vertexBuffer = context.createVertexBuffer(vertices, atmosphereLayout.members);
        this.indexBuffer = context.createIndexBuffer(triangles);
        this.segments = index.b7.simpleSegment(0, 0, 4, 2);
    }
    destroy() {
        this.vertexBuffer.destroy();
        this.indexBuffer.destroy();
        this.segments.destroy();
    }
}

const starsLayout = index.da([
    {
        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 = index.di(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(index.ab.vec3.fromValues(Math.cos(lat) * Math.cos(lon), Math.cos(lat) * Math.sin(lon), Math.sin(lat)));
    }
    return points;
}
class StarsParams {
    constructor() {
        this.starsCount = 16000;
        this.sizeMultiplier = 0.15;
        this.sizeRange = 100;
        this.intensityRange = 200;
    }
}
class Atmosphere {
    constructor(painter) {
        this.colorModeAlphaBlendedWriteRGB = new ColorMode([
            ONE,
            ONE_MINUS_SRC_ALPHA,
            ONE,
            ONE_MINUS_SRC_ALPHA
        ], index.aj.transparent, [
            true,
            true,
            true,
            false
        ]);
        this.colorModeWriteAlpha = new ColorMode([
            ONE,
            ZERO,
            ONE,
            ZERO
        ], index.aj.transparent, [
            false,
            false,
            false,
            true
        ]);
        this.params = new StarsParams();
        this.updateNeeded = true;
        painter.tp.registerParameter(this.params, ['Stars'], 'starsCount', {
            min: 100,
            max: 16000,
            step: 1
        }, () => {
            this.updateNeeded = true;
        });
        painter.tp.registerParameter(this.params, ['Stars'], 'sizeMultiplier', {
            min: 0.01,
            max: 2,
            step: 0.01
        });
        painter.tp.registerParameter(this.params, ['Stars'], 'sizeRange', {
            min: 0,
            max: 200,
            step: 1
        }, () => {
            this.updateNeeded = true;
        });
        painter.tp.registerParameter(this.params, ['Stars'], 'intensityRange', {
            min: 0,
            max: 200,
            step: 1
        }, () => {
            this.updateNeeded = true;
        });
    }
    update(painter) {
        const context = painter.context;
        if (!this.atmosphereBuffer || this.updateNeeded) {
            this.updateNeeded = false;
            this.atmosphereBuffer = new AtmosphereBuffer(context);
            const sizeRange = this.params.sizeRange;
            const intensityRange = this.params.intensityRange;
            const stars = generateUniformDistributedPointsOnSphere(this.params.starsCount);
            const sRand = index.di(300);
            const vertices = new index.dg();
            const triangles = new index.aU();
            let base = 0;
            for (let i = 0; i < stars.length; ++i) {
                const star = index.ab.vec3.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 = index.b7.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 = index.ae(tr.zoom);
        const fogLUT = painter.style.getLut(fog.scope);
        const colorIgnoreLut = fog.properties.get('color-use-theme') === 'none';
        const fogColor = fog.properties.get('color').toRenderColor(colorIgnoreLut ? null : fogLUT).toArray01();
        const hignoreLutIgnoreLut = fog.properties.get('high-color-use-theme') === 'none';
        const highColor = fog.properties.get('high-color').toRenderColor(hignoreLutIgnoreLut ? null : fogLUT).toArray01();
        const spaceColorIgnoreLut = fog.properties.get('space-color-use-theme') === 'none';
        const spaceColor = fog.properties.get('space-color').toRenderColor(spaceColorIgnoreLut ? null : fogLUT).toArray01PremultipliedAlpha();
        const minHorizonBlend = 0.0005;
        const horizonBlend = index.dh(fog.properties.get('horizon-blend'), 0, 1, minHorizonBlend, 0.25);
        const globeRadius = index.cC(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 = index.ab.vec3.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 });
            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);
            }
        };
        draw(false);
        draw(true);
    }
    drawStars(painter, fog) {
        const starIntensity = index.aw(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');
        const orientation = index.ab.quat.identity([]);
        index.ab.quat.rotateX(orientation, orientation, -tr._pitch);
        index.ab.quat.rotateZ(orientation, orientation, -tr.angle);
        index.ab.quat.rotateX(orientation, orientation, index.ai(tr._center.lat));
        index.ab.quat.rotateY(orientation, orientation, -index.ai(tr._center.lng));
        const rotationMatrix = index.ab.mat4.fromQuat(new Float32Array(16), orientation);
        const mvp = index.ab.mat4.multiply([], tr.starsProjMatrix, rotationMatrix);
        const modelView3 = index.ab.mat3.fromMat4([], rotationMatrix);
        const modelviewInv = index.ab.mat3.invert([], modelView3);
        const camUp = [
            0,
            1,
            0
        ];
        index.ab.vec3.transformMat3(camUp, camUp, modelviewInv);
        index.ab.vec3.scale(camUp, camUp, this.params.sizeMultiplier);
        const camRight = [
            1,
            0,
            0
        ];
        index.ab.vec3.transformMat3(camRight, camRight, modelviewInv);
        index.ab.vec3.scale(camRight, camRight, this.params.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) {
    const fogMatrix = [...modelMatrix];
    const scale = transform.cameraWorldSizeForFog / transform.worldSize;
    const scaleMatrix = index.ab.mat4.identity([]);
    index.ab.mat4.scale(scaleMatrix, scaleMatrix, [
        scale,
        scale,
        1
    ]);
    index.ab.mat4.multiply(fogMatrix, scaleMatrix, fogMatrix);
    index.ab.mat4.multiply(fogMatrix, transform.worldToFogMatrix, fogMatrix);
    return fogMatrix;
}
function setupMeshDraw(definesValues, dynamicBuffers, mesh, painter, lut) {
    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);
        }
    }
    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 (lut) {
        if (!lut.texture) {
            lut.texture = new index.dk(painter.context, lut.image, [
                lut.image.height,
                lut.image.height,
                lut.image.height
            ], context.gl.RGBA8);
        }
        context.activeTexture.set(context.gl.TEXTURE0 + TextureSlots.LUT);
        if (lut.texture) {
            lut.texture.bind(context.gl.LINEAR, context.gl.CLAMP_TO_EDGE);
        }
        definesValues.push('APPLY_LUT_ON_GPU');
    }
    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');
    }
    if (!material.defined) {
        definesValues.push('DIFFUSE_SHADED');
    }
    const shadowRenderer = painter.shadowRenderer;
    if (shadowRenderer) {
        definesValues.push('RENDER_SHADOWS', 'DEPTH_TEXTURE');
        if (shadowRenderer.useNormalOffset) {
            definesValues.push('NORMAL_OFFSET');
        }
    }
}
function drawMesh(sortedMesh, painter, layer, modelParameters, stencilMode, colorMode) {
    const opacity = layer.paint.get('model-opacity').constantOr(1);
    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 = index.ab.mat4.multiply([], modelParameters.zScaleMatrix, sortedMesh.nodeModelMatrix);
    }
    index.ab.mat4.multiply(lightingMatrix, modelParameters.negCameraPosMatrix, lightingMatrix);
    const normalMatrix = index.ab.mat4.invert([], lightingMatrix);
    index.ab.mat4.transpose(normalMatrix, normalMatrix);
    const ignoreLut = layer.paint.get('model-color-use-theme').constantOr('default') === 'none';
    const emissiveStrength = layer.paint.get('model-emissive-strength').constantOr(0);
    const uniformValues = modelUniformValues(new Float32Array(sortedMesh.worldViewProjection), new Float32Array(lightingMatrix), new Float32Array(normalMatrix), null, painter, opacity, pbr.baseColorFactor.toRenderColor(null), material.emissiveFactor, pbr.metallicFactor, pbr.roughnessFactor, material, emissiveStrength, layer);
    const programOptions = { defines: [] };
    const dynamicBuffers = [];
    const shadowRenderer = painter.shadowRenderer;
    if (shadowRenderer) {
        shadowRenderer.useNormalOffset = false;
    }
    setupMeshDraw(programOptions.defines, dynamicBuffers, mesh, painter, ignoreLut ? null : layer.lut);
    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, void 0, dynamicBuffers);
}
function prepare$1(layer, sourceCache, painter) {
    const modelSource = sourceCache.getSource();
    if (!modelSource.loaded())
        return;
    if (modelSource.type === 'vector' || modelSource.type === 'geojson') {
        const scope = modelSource.type === 'vector' ? layer.scope : '';
        if (painter.modelManager) {
            painter.modelManager.upload(painter, scope);
        }
        return;
    }
    if (modelSource.type === 'batched-model') {
        return;
    }
    if (modelSource.type !== 'model')
        return;
    const models = modelSource.getModels();
    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 = index.dl(modelMatrix, transform);
    } else {
        nodeModelMatrix = [...modelMatrix];
    }
    index.ab.mat4.multiply(nodeModelMatrix, nodeModelMatrix, node.matrix);
    const worldViewProjection = index.ab.mat4.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 = index.ab.vec3.transformMat4([], mesh.centroid, worldViewProjection);
            if (!transform.isOrthographic && centroidPos[2] <= 0)
                continue;
            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 = painter._shadowMapDebug ? [] : ['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, void 0, void 0);
}
function drawModels(painter, sourceCache, layer, coords) {
    if (painter.renderPass === 'opaque') {
        return;
    }
    const opacity = layer.paint.get('model-opacity').constantOr(1);
    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 index.a9) {
                    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') {
        const scope = modelSource.type === 'vector' ? layer.scope : '';
        drawVectorLayerModels(painter, sourceCache, layer, coords, scope);
        cleanup();
        return;
    }
    if (!modelSource.loaded())
        return;
    if (modelSource.type === 'batched-model') {
        drawBatchedModels(painter, sourceCache, layer, coords);
        cleanup();
        return;
    }
    if (modelSource.type !== 'model')
        return;
    const models = modelSource.getModels();
    const modelParametersVector = [];
    const mercCameraPos = painter.transform.getFreeCameraOptions().position;
    const cameraPos = index.ab.vec3.scale([], [
        mercCameraPos.x,
        mercCameraPos.y,
        mercCameraPos.z
    ], painter.transform.worldSize);
    index.ab.vec3.negate(cameraPos, cameraPos);
    const transparentMeshes = [];
    const opaqueMeshes = [];
    let modelIndex = 0;
    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);
        model.computeModelMatrix(painter, rotation, scale, translation, true, true, false);
        const negCameraPosMatrix = index.ab.mat4.identity([]);
        const modelMetersPerPixel = index.dj(model.position.lat, painter.transform.zoom);
        const modelPixelsPerMeter = 1 / modelMetersPerPixel;
        const zScaleMatrix = index.ab.mat4.fromScaling([], [
            1,
            1,
            modelPixelsPerMeter
        ]);
        index.ab.mat4.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.expandedFarZProjMatrix, modelIndex, transparentMeshes, opaqueMeshes);
        }
        modelIndex++;
    }
    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);
        }
        for (const transparentMesh of transparentMeshes) {
            drawShadowCaster(transparentMesh.mesh, transparentMesh.nodeModelMatrix, painter, layer);
        }
        cleanup();
        return;
    }
    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) {
            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();
    }
    for (const transparentMesh of transparentMeshes) {
        drawMesh(transparentMesh, painter, layer, modelParametersVector[transparentMesh.modelIndex], StencilMode.disabled, painter.colorModeForRenderPass());
    }
    cleanup();
}
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 = index.dn.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: void 0,
        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);
    }
}
const renderData = {
    shadowUniformsInitialized: false,
    useSingleShadowCascade: false,
    tileMatrix: new Float64Array(16),
    shadowTileMatrix: new Float32Array(16),
    aabb: new index.cd([
        0,
        0,
        0
    ], [
        index.ag,
        index.ag,
        0
    ])
};
function calculateTileZoom(id, tr) {
    const tiles = 1 << id.canonical.z;
    const cameraPos = tr.getFreeCameraOptions().position;
    const elevation = tr.elevation;
    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 = index.aw(cameraPos.x, minx, maxx) - cameraPos.x;
    const disty = index.aw(cameraPos.y, miny, maxy) - cameraPos.y;
    const distz = index.bH(height, tr.center.lat) - cameraPos.z;
    return tr._zoomFromMercatorZ(Math.sqrt(distx * distx + disty * disty + distz * distz));
}
function drawVectorLayerModels(painter, source, layer, coords, scope) {
    const tr = painter.transform;
    if (tr.projection.name !== 'mercator') {
        index.w(`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;
    layer.modelManager = modelManager;
    const shadowRenderer = painter.shadowRenderer;
    if (!layer._unevaluatedLayout._values.hasOwnProperty('model-id')) {
        return;
    }
    const modelIdUnevaluatedProperty = layer._unevaluatedLayout._values['model-id'];
    const evaluationParameters = Object.assign({}, layer.layout.get('model-id').parameters);
    const layerIndex = painter.style.order.indexOf(layer.fqid);
    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 modelUris = bucket.getModelUris();
        if (modelUris && !bucket.modelsRequested) {
            modelManager.addModelsFromBucket(modelUris, scope);
            bucket.modelsRequested = true;
        }
        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] = index.ag;
            renderData.aabb.max[2] = 0;
            if (calculateTileShadowPassCulling(bucket, renderData, painter, layer.scope))
                continue;
        }
        const tiles = 1 << coord.canonical.z;
        const cameraPos = [
            ((mercCameraPos.x - coord.wrap) * tiles - coord.canonical.x) * index.ag,
            (mercCameraPos.y * tiles - coord.canonical.y) * index.ag,
            mercCameraPos.z * tiles * index.ag
        ];
        const clippable = painter.conflationActive && Object.keys(bucket.instancesPerModel).length > 0 && painter.style.isLayerClipped(layer, source.getSource());
        if (clippable) {
            if (bucket.updateReplacement(coord, painter.replacementSource, layerIndex, scope)) {
                bucket.uploaded = false;
                bucket.upload(painter.context);
            }
        }
        for (let modelId in bucket.instancesPerModel) {
            const modelInstances = bucket.instancesPerModel[modelId];
            if (modelInstances.features.length > 0) {
                modelId = modelIdProperty.evaluate(modelInstances.features[0].feature, {});
            }
            const model = modelManager.getModel(modelId, 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, renderData2) {
    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(renderData2.shadowTileMatrix, renderData2.shadowTileMatrix, Float32Array.from(node.matrix));
                colorMode = shadowRenderer.getShadowPassColorMode();
            } else {
                const ignoreLut = layer.paint.get('model-color-use-theme').constantOr('default') === 'none';
                setupMeshDraw(definesValues, dynamicBuffers, mesh, painter, ignoreLut ? null : layer.lut);
                program = painter.getOrCreateProgram('model', {
                    defines: definesValues,
                    overrideFog: affectedByFog
                });
                const material = mesh.material;
                const pbr = material.pbrMetallicRoughness;
                const layerOpacity = layer.paint.get('model-opacity').constantOr(1);
                const emissiveStrength = layer.paint.get('model-emissive-strength').constantOr(0);
                uniformValues = modelUniformValues(coord.expandedProjMatrix, Float32Array.from(node.matrix), new Float32Array(16), null, painter, layerOpacity, pbr.baseColorFactor.toRenderColor(null), material.emissiveFactor, pbr.metallicFactor, pbr.roughnessFactor, material, emissiveStrength, layer, cameraPos);
                if (shadowRenderer) {
                    if (!renderData2.shadowUniformsInitialized) {
                        shadowRenderer.setupShadows(coord.toUnwrapped(), program, 'model-tile', coord.overscaledZ);
                        renderData2.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, void 0, dynamicBuffers, modelInstances.instancedDataArray.length);
            } else {
                const instanceUniform = isShadowPass ? 'u_instance' : 'u_normal_matrix';
                for (let i = 0; i < modelInstances.instancedDataArray.length; ++i) {
                    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, void 0, dynamicBuffers);
                }
            }
        }
    }
    if (node.children) {
        for (const child of node.children) {
            drawInstancedNode(painter, layer, child, modelInstances, cameraPos, coord, renderData2);
        }
    }
}
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;
        if (painter.conflationActive)
            bucket.updateReplacement(coord, painter.replacementSource);
        bucket.evaluateScale(painter, layer);
        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) {
    layer.resetLayerRenderingStats(painter);
    const context = painter.context;
    const tr = painter.transform;
    const fog = painter.style.fog;
    const shadowRenderer = painter.shadowRenderer;
    if (tr.projection.name !== 'mercator') {
        index.w(`Drawing 3D landmark models for ${ tr.projection.name } projection is not yet implemented`);
        return;
    }
    const mercCameraPos = painter.transform.getFreeCameraOptions().position;
    const cameraPos = index.ab.vec3.scale([], [
        mercCameraPos.x,
        mercCameraPos.y,
        mercCameraPos.z
    ], painter.transform.worldSize);
    const negCameraPos = index.ab.vec3.negate([], cameraPos);
    const negCameraPosMatrix = index.ab.mat4.identity([]);
    const metersPerPixel = index.dj(tr.center.lat, tr.zoom);
    const pixelsPerMeter = 1 / metersPerPixel;
    const zScaleMatrix = index.ab.mat4.fromScaling([], [
        1,
        1,
        pixelsPerMeter
    ]);
    index.ab.mat4.translate(negCameraPosMatrix, negCameraPosMatrix, negCameraPos);
    const layerOpacity = layer.paint.get('model-opacity').constantOr(1);
    const depthModeRW = new DepthMode(context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
    const depthModeRO = new DepthMode(context.gl.LEQUAL, DepthMode.ReadOnly, painter.depthRangeFor3D);
    const aabb = new index.cd([
        Infinity,
        Infinity,
        Infinity
    ], [
        -Infinity,
        -Infinity,
        -Infinity
    ]);
    const isShadowPass = painter.renderPass === 'shadow';
    const frustum = isShadowPass && shadowRenderer ? shadowRenderer.getCurrentCascadeFrustum() : tr.getFrustum(tr.scaleZoom(tr.worldSize));
    const frontCutoffParams = layer.paint.get('model-front-cutoff');
    const frontCutoffEnabled = frontCutoffParams[2] < 1;
    const cutoffParams = getCutoffParams(painter, layer.paint.get('model-cutoff-fade-range'));
    const stats = layer.getLayerRenderingStats();
    const drawTiles = function () {
        let start, end, step;
        if (frontCutoffEnabled) {
            start = coords.length - 1;
            end = -1;
            step = -1;
        } else {
            start = 0;
            end = coords.length;
            step = 1;
        }
        const invTileMatrix = new Float64Array(16);
        const cameraPosTileCoord = index.ab.vec3.create();
        const cameraPointTileCoord = new index.P(0, 0);
        for (let i = start; i !== end; i += step) {
            const coord = coords[i];
            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;
            if (!isShadowPass && frontCutoffEnabled) {
                index.ab.mat4.invert(invTileMatrix, tileMatrix);
                index.ab.vec3.transformMat4(cameraPosTileCoord, cameraPos, invTileMatrix);
                cameraPointTileCoord.x = cameraPosTileCoord[0];
                cameraPointTileCoord.y = cameraPosTileCoord[1];
            }
            const sortedNodes = [];
            for (const nodeInfo of bucket.getNodesInfo()) {
                if (nodeInfo.hiddenByReplacement)
                    continue;
                if (!nodeInfo.node.meshes)
                    continue;
                const node = nodeInfo.node;
                let elevation = 0;
                if (painter.terrain && node.elevation) {
                    elevation = node.elevation * painter.terrain.exaggeration();
                }
                const calculateNodeAabb = () => {
                    const localBounds = nodeInfo.aabb;
                    aabb.min = [...localBounds.min];
                    aabb.max = [...localBounds.max];
                    aabb.min[2] += elevation;
                    aabb.max[2] += elevation;
                    index.ab.vec3.transformMat4(aabb.min, aabb.min, tileMatrix);
                    index.ab.vec3.transformMat4(aabb.max, aabb.max, tileMatrix);
                    return aabb;
                };
                const nodeAabb = calculateNodeAabb();
                const scale = nodeInfo.evaluatedScale;
                if (scale[0] <= 1 && scale[1] <= 1 && scale[2] <= 1 && nodeAabb.intersects(frustum) === 0) {
                    continue;
                }
                if (!isShadowPass && frontCutoffEnabled) {
                    const opacityChangePerFrame = 1 / 6;
                    if (cameraPos[0] > nodeAabb.min[0] && cameraPos[0] < nodeAabb.max[0] && cameraPos[1] > nodeAabb.min[1] && cameraPos[1] < nodeAabb.max[1] && cameraPos[2] * metersPerPixel < nodeAabb.max[2] && node.footprint && index.bA(cameraPointTileCoord, node.footprint)) {
                        nodeInfo.cameraCollisionOpacity = Math.max(nodeInfo.cameraCollisionOpacity - opacityChangePerFrame, 0);
                    } else {
                        nodeInfo.cameraCollisionOpacity = Math.min(1, nodeInfo.cameraCollisionOpacity + opacityChangePerFrame);
                    }
                }
                const tileModelMatrix = [...tileMatrix];
                const anchorX = node.anchor ? node.anchor[0] : 0;
                const anchorY = node.anchor ? node.anchor[1] : 0;
                index.ab.mat4.translate(tileModelMatrix, tileModelMatrix, [
                    anchorX * (scale[0] - 1),
                    anchorY * (scale[1] - 1),
                    elevation
                ]);
                if (!index.ab.vec3.exactEquals(scale, index.dm)) {
                    index.ab.mat4.scale(tileModelMatrix, tileModelMatrix, scale);
                }
                const nodeModelMatrix = index.ab.mat4.multiply([], tileModelMatrix, node.matrix);
                const wvpForNode = index.ab.mat4.multiply([], tr.expandedFarZProjMatrix, nodeModelMatrix);
                const wvpForTile = index.ab.mat4.multiply([], tr.expandedFarZProjMatrix, tileModelMatrix);
                const anchorPos = index.ab.vec4.transformMat4([], [
                    anchorX,
                    anchorY,
                    elevation,
                    1
                ], wvpForNode);
                const depth = anchorPos[2];
                node.hidden = false;
                let opacity = layerOpacity;
                if (!isShadowPass) {
                    if (frontCutoffEnabled) {
                        opacity *= nodeInfo.cameraCollisionOpacity;
                        opacity *= calculateFrontCutoffOpacity(tileModelMatrix, tr, nodeInfo.aabb, frontCutoffParams);
                    }
                    opacity *= calculateFarCutoffOpacity(cutoffParams, depth);
                }
                if (opacity === 0) {
                    node.hidden = true;
                    continue;
                }
                const sortedNode = {
                    nodeInfo,
                    depth,
                    opacity,
                    wvpForNode,
                    wvpForTile,
                    nodeModelMatrix,
                    tileModelMatrix
                };
                sortedNodes.push(sortedNode);
            }
            if (!isShadowPass) {
                sortedNodes.sort((a, b) => {
                    if (!frontCutoffEnabled || a.opacity === 1 && b.opacity === 1) {
                        return a.depth < b.depth ? -1 : 1;
                    }
                    if (a.opacity === 1) {
                        return -1;
                    }
                    if (b.opacity === 1) {
                        return 1;
                    }
                    return a.depth > b.depth ? -1 : 1;
                });
            }
            for (const sortedNode of sortedNodes) {
                const nodeInfo = sortedNode.nodeInfo;
                const node = nodeInfo.node;
                let lightingMatrix = index.ab.mat4.multiply([], zScaleMatrix, sortedNode.tileModelMatrix);
                index.ab.mat4.multiply(lightingMatrix, negCameraPosMatrix, lightingMatrix);
                const normalMatrix = index.ab.mat4.invert([], lightingMatrix);
                index.ab.mat4.transpose(normalMatrix, normalMatrix);
                index.ab.mat4.scale(normalMatrix, normalMatrix, normalScale);
                lightingMatrix = index.ab.mat4.multiply(lightingMatrix, lightingMatrix, node.matrix);
                const isLightBeamPass = painter.renderPass === 'light-beam';
                const ignoreLut = layer.paint.get('model-color-use-theme').constantOr('default') === 'none';
                const hasMapboxFeatures = modelTraits & index.dp.HasMapboxMeshFeatures;
                const emissiveStrength = hasMapboxFeatures ? 0 : nodeInfo.evaluatedRMEA[0][2];
                for (let i2 = 0; i2 < node.meshes.length; ++i2) {
                    const mesh = node.meshes[i2];
                    const isLight = i2 === node.lightMeshIndex;
                    let worldViewProjection = sortedNode.wvpForNode;
                    if (isLight) {
                        if (!isLightBeamPass && !painter.terrain && painter.shadowRenderer) {
                            if (painter.currentLayer < painter.firstLightBeamLayer) {
                                painter.firstLightBeamLayer = painter.currentLayer;
                            }
                            continue;
                        }
                        worldViewProjection = sortedNode.wvpForTile;
                    } else if (isLightBeamPass) {
                        continue;
                    }
                    const programOptions = { defines: [] };
                    const dynamicBuffers = [];
                    if (!isShadowPass && shadowRenderer) {
                        shadowRenderer.useNormalOffset = !!mesh.normalBuffer;
                    }
                    setupMeshDraw(programOptions.defines, dynamicBuffers, mesh, painter, ignoreLut ? null : layer.lut);
                    if (!hasMapboxFeatures) {
                        programOptions.defines.push('DIFFUSE_SHADED');
                    }
                    if (singleCascade) {
                        programOptions.defines.push('SHADOWS_SINGLE_CASCADE');
                    }
                    if (stats) {
                        if (!isShadowPass) {
                            stats.numRenderedVerticesInTransparentPass += mesh.vertexArray.length;
                        } else {
                            stats.numRenderedVerticesInShadowPass += mesh.vertexArray.length;
                        }
                    }
                    if (isShadowPass) {
                        drawShadowCaster(mesh, sortedNode.nodeModelMatrix, painter, layer);
                        continue;
                    }
                    let fogMatrixArray = null;
                    if (fog) {
                        const fogMatrix = fogMatrixForModel(sortedNode.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 material = mesh.material;
                    let occlusionTextureTransform;
                    if (material.occlusionTexture && material.occlusionTexture.offsetScale) {
                        occlusionTextureTransform = material.occlusionTexture.offsetScale;
                        programOptions.defines.push('OCCLUSION_TEXTURE_TRANSFORM');
                    }
                    const program = painter.getOrCreateProgram('model', programOptions);
                    if (!isShadowPass && shadowRenderer) {
                        shadowRenderer.setupShadowsFromMatrix(sortedNode.tileModelMatrix, program, shadowRenderer.useNormalOffset);
                    }
                    painter.uploadCommonUniforms(context, program, null, fogMatrixArray);
                    const pbr = material.pbrMetallicRoughness;
                    pbr.metallicFactor = 0.9;
                    pbr.roughnessFactor = 0.5;
                    const uniformValues = modelUniformValues(new Float32Array(worldViewProjection), new Float32Array(lightingMatrix), new Float32Array(normalMatrix), new Float32Array(node.matrix), painter, sortedNode.opacity, pbr.baseColorFactor.toRenderColor(null), material.emissiveFactor, pbr.metallicFactor, pbr.roughnessFactor, material, emissiveStrength, layer, [
                        0,
                        0,
                        0
                    ], occlusionTextureTransform);
                    if (!isLight && (nodeInfo.hasTranslucentParts || sortedNode.opacity < 1)) {
                        program.draw(painter, context.gl.TRIANGLES, depthModeRW, StencilMode.disabled, ColorMode.disabled, CullFaceMode.backCCW, uniformValues, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments, layer.paint, painter.transform.zoom, void 0, dynamicBuffers);
                    }
                    const meshNeedsBlending = isLight || sortedNode.opacity < 1 || nodeInfo.hasTranslucentParts;
                    const colorMode = meshNeedsBlending ? ColorMode.alphaBlended : ColorMode.unblended;
                    const depthMode = !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, void 0, dynamicBuffers);
                }
            }
        }
    };
    prepareBatched(painter, source, layer, coords);
    drawTiles();
}
function calculateTileShadowPassCulling(bucket, renderData2, painter, scope) {
    if (!painter.modelManager)
        return true;
    const modelManager = painter.modelManager;
    if (!painter.shadowRenderer)
        return true;
    const shadowRenderer = painter.shadowRenderer;
    const aabb = renderData2.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;
    aabb.min[2] += bucket.terrainElevationMin;
    aabb.max[2] += bucket.terrainElevationMax;
    index.ab.vec3.transformMat4(aabb.min, aabb.min, renderData2.tileMatrix);
    index.ab.vec3.transformMat4(aabb.max, aabb.max, renderData2.tileMatrix);
    const intersection = aabb.intersects(shadowRenderer.getCurrentCascadeFrustum());
    if (painter.currentShadowCascade === 0) {
        bucket.isInsideFirstShadowMapFrustum = intersection === 2;
    }
    return intersection === 0;
}
function calculateFarCutoffOpacity(cutoffParams, depth) {
    const near = cutoffParams.uniformValues.u_cutoff_params[0];
    const far = cutoffParams.uniformValues.u_cutoff_params[1];
    const cutoffStart = cutoffParams.uniformValues.u_cutoff_params[2];
    const cutoffEnd = cutoffParams.uniformValues.u_cutoff_params[3];
    if (far === near || cutoffEnd === cutoffStart) {
        return 1;
    }
    const linearDepth = (depth - near) / (far - near);
    return index.aw((linearDepth - cutoffStart) / (cutoffEnd - cutoffStart), 0, 1);
}
function calculateFrontCutoffOpacity(tileModelMatrix, tr, aabb, cutoffParams) {
    const fullyOpaquePitch = 20;
    const fullyTransparentPitch = 40;
    if (tr.pitch < fullyOpaquePitch) {
        return 1;
    }
    const mat = tr.getWorldToCameraMatrix();
    index.ab.mat4.multiply(mat, mat, tileModelMatrix);
    const p = index.ab.vec4.fromValues(aabb.min[0], aabb.min[1], aabb.min[2], 1);
    let r = index.ab.vec4.transformMat4(index.ab.vec4.create(), p, mat);
    let pMin = r;
    let pMax = r;
    p[1] = aabb.max[1];
    r = index.ab.vec4.transformMat4(index.ab.vec4.create(), p, mat);
    pMin = r[1] < pMin[1] ? r : pMin;
    pMax = r[1] > pMax[1] ? r : pMax;
    p[0] = aabb.max[0];
    r = index.ab.vec4.transformMat4(index.ab.vec4.create(), p, mat);
    pMin = r[1] < pMin[1] ? r : pMin;
    pMax = r[1] > pMax[1] ? r : pMax;
    p[1] = aabb.min[1];
    r = index.ab.vec4.transformMat4(index.ab.vec4.create(), p, mat);
    pMin = r[1] < pMin[1] ? r : pMin;
    pMax = r[1] > pMax[1] ? r : pMax;
    const cutoffStartParam = index.aw(cutoffParams[0], 0, 1);
    const cutoffRangeParam = 100 * tr.pixelsPerMeter * index.aw(cutoffParams[1], 0, 1);
    const finalOpacity = index.aw(cutoffParams[2], 0, 1);
    const cutoffStart = index.ab.vec4.lerp(index.ab.vec4.create(), pMin, pMax, cutoffStartParam);
    const fovScale = Math.tan(tr.fovX * 0.5);
    const yMinLimit = -cutoffStart[2] * fovScale;
    if (cutoffRangeParam === 0) {
        return cutoffStart[1] < -Math.abs(yMinLimit) ? finalOpacity : 1;
    }
    const cutoffFactor = (-Math.abs(yMinLimit) - cutoffStart[1]) / cutoffRangeParam;
    const lerp = (a, b, t) => {
        return (1 - t) * a + t * b;
    };
    const opacity = index.aw(lerp(1, finalOpacity, cutoffFactor), finalOpacity, 1);
    return lerp(1, opacity, index.aw((tr.pitch - fullyOpaquePitch) / (fullyTransparentPitch - fullyOpaquePitch), 0, 1));
}

class CacheEntry {
}
const TimeoutFrames = 30;
class WireframeDebugCache {
    constructor() {
        this._storage = /* @__PURE__ */
        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 index.dq();
        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);
        }
        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) {
                obj.buf.destroy();
                this._storage.delete(key);
            }
        }
    }
    destroy() {
        for (const [key, obj] of this._storage) {
            obj.buf.destroy();
            this._storage.delete(key);
        }
    }
}

class OcclusionParams {
    constructor(tp) {
        this.occluderSize = 30;
        this.depthOffset = -0.0001;
        tp.registerParameter(this, ['Occlusion'], 'occluderSize', {
            min: 1,
            max: 100,
            step: 1
        });
        tp.registerParameter(this, ['Occlusion'], 'depthOffset', {
            min: -0.05,
            max: 0,
            step: 0.00001
        });
    }
}

const rainLayout = index.da([
    {
        type: 'Float32',
        name: 'a_pos_3f',
        components: 3
    },
    {
        type: 'Float32',
        name: 'a_uv',
        components: 2
    },
    {
        type: 'Float32',
        name: 'a_rainParticleData',
        components: 4
    }
]);

class TrackedParametersMock {
    registerParameter() {
    }
    registerButton() {
    }
    registerBinding() {
    }
    refreshUI() {
    }
}

class PrecipitationRevealParams {
    constructor(tp, namespace) {
        this.revealStart = 11;
        this.revealRange = 2;
        tp.registerParameter(this, [
            ...namespace,
            'Reveal'
        ], 'revealStart', {
            min: 0,
            max: 17,
            step: 0.05
        });
        tp.registerParameter(this, [
            ...namespace,
            'Reveal'
        ], 'revealRange', {
            min: 0.1,
            max: 5.1,
            step: 0.05
        });
    }
}

const vignetteLayout = index.da([{
        type: 'Float32',
        name: 'a_pos_2f',
        components: 2
    }]);

class Vignette {
    destroy() {
        if (this.vignetteVx) {
            this.vignetteVx.destroy();
        }
        if (this.vignetteIdx) {
            this.vignetteIdx.destroy();
        }
    }
    draw(painter, params) {
        const program = painter.getOrCreateProgram('vignette');
        if (!this.vignetteVx || !this.vignetteIdx) {
            const vertices = new index.dr();
            const triangles = new index.aU();
            vertices.emplaceBack(-1, -1);
            vertices.emplaceBack(1, -1);
            vertices.emplaceBack(1, 1);
            vertices.emplaceBack(-1, 1);
            triangles.emplaceBack(0, 1, 2);
            triangles.emplaceBack(0, 2, 3);
            this.vignetteVx = painter.context.createVertexBuffer(vertices, vignetteLayout.members);
            this.vignetteIdx = painter.context.createIndexBuffer(triangles);
        }
        const vignetteSegments = index.b7.simpleSegment(0, 0, 4, 6);
        if (this.vignetteVx && this.vignetteIdx) {
            painter.uploadCommonUniforms(painter.context, program);
            const uniforms = vignetteUniformValues({
                vignetteShape: [
                    params.start,
                    params.range,
                    Math.pow(10, params.fadePower)
                ],
                vignetteColor: [
                    params.color.r,
                    params.color.g,
                    params.color.b,
                    params.color.a * params.strength
                ]
            });
            const gl = painter.context.gl;
            program.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniforms, 'vignette', this.vignetteVx, this.vignetteIdx, vignetteSegments, {});
        }
    }
}

class Movement {
    constructor() {
        this._accumulatedOffsetX = 0;
        this._accumulatedOffsetY = 0;
        this._accumulatedElevation = 0;
    }
    update(tr, ppmScaleFactor) {
        const options = tr.getFreeCameraOptions();
        const cameraMercatorPos = options.position;
        const elevation = cameraMercatorPos.toAltitude();
        const latLng = cameraMercatorPos.toLngLat();
        const lng = index.ai(latLng.lng);
        const lat = index.ai(latLng.lat);
        const ppmScale = tr.pixelsPerMeter / ppmScaleFactor;
        const offsetXCur = lng * index.ds;
        const offsetYCur = index.ds * Math.log(Math.tan(Math.PI / 4 + lat / 2));
        if (this._offsetXPrev === void 0) {
            this._offsetXPrev = 0;
            this._offsetYPrev = 0;
            this._elevationPrev = 0;
            this._accumulatedOffsetX = 0;
            this._accumulatedOffsetY = 0;
            this._accumulatedElevation = 0;
        } else {
            const deltaX = -this._offsetXPrev + offsetXCur;
            const deltaY = -this._offsetYPrev + offsetYCur;
            const deltaE = -this._elevationPrev + elevation;
            this._accumulatedOffsetX += deltaX * ppmScale;
            this._accumulatedOffsetY += deltaY * ppmScale;
            this._accumulatedElevation += deltaE * ppmScale;
            this._offsetXPrev = offsetXCur;
            this._offsetYPrev = offsetYCur;
            this._elevationPrev = elevation;
        }
    }
    getPosition() {
        return [
            this._accumulatedOffsetX,
            this._accumulatedOffsetY,
            this._accumulatedElevation
        ];
    }
}
function boxWrap(unwrappedPos, boxSize) {
    const wrappedOffsetX = unwrappedPos[0] - Math.floor(unwrappedPos[0] / boxSize) * boxSize;
    const wrappedOffsetY = unwrappedPos[1] - Math.floor(unwrappedPos[1] / boxSize) * boxSize;
    const wrappedOffsetZ = unwrappedPos[2] - Math.floor(unwrappedPos[2] / boxSize) * boxSize;
    return [
        -wrappedOffsetX,
        -wrappedOffsetY,
        -wrappedOffsetZ
    ];
}
function generateUniformDistributedPointsInsideCube(pointsCount) {
    const sRand = index.di(1323123451230);
    const points = [];
    for (let i = 0; i < pointsCount; ++i) {
        const vx = -1 + 2 * sRand();
        const vy = -1 + 2 * sRand();
        const vz = -1 + 2 * sRand();
        points.push(index.ab.vec3.fromValues(vx, vy, vz));
    }
    return points;
}
function lerpClamp(a, b, t1, t2, tMid) {
    const t = index.aw((tMid - t1) / (t2 - t1), 0, 1);
    return (1 - t) * a + t * b;
}
class PrecipitationBase {
    constructor(ppmScaleFactor) {
        this._movement = new Movement();
        this._accumulatedTimeFromStart = 0;
        this._prevTime = Date.now() / 1000;
        this._vignette = new Vignette();
        this._ppmScaleFactor = ppmScaleFactor;
    }
    destroy() {
        if (this.particlesVx) {
            this.particlesVx.destroy();
        }
        if (this.particlesIdx) {
            this.particlesIdx.destroy();
        }
        if (this._vignette) {
            this._vignette.destroy();
        }
    }
    updateOnRender(painter, timeFactor) {
        const tr = painter.transform;
        this._movement.update(tr, this._ppmScaleFactor);
        const projectionMatrix = tr.starsProjMatrix;
        const orientation = index.ab.quat.identity([]);
        index.ab.quat.rotateX(orientation, orientation, index.ai(90) - tr._pitch);
        index.ab.quat.rotateZ(orientation, orientation, -tr.angle);
        const rotationMatrix = index.ab.mat4.fromQuat(new Float32Array(16), orientation);
        const swapAxesT = index.ab.mat4.fromValues(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1);
        const swapAxes = index.ab.mat4.transpose([], swapAxesT);
        const modelviewMatrix = index.ab.mat4.multiply([], swapAxes, rotationMatrix);
        const curTime = Date.now() / 1000;
        this._accumulatedTimeFromStart += (curTime - this._prevTime) * timeFactor;
        this._prevTime = curTime;
        return {
            projectionMatrix,
            modelviewMatrix
        };
    }
}

class Rain extends PrecipitationBase {
    constructor(painter) {
        super(4.25);
        this._params = {
            overrideStyleParameters: false,
            intensity: 0.5,
            timeFactor: 1,
            velocityConeAperture: 0,
            velocity: 300,
            boxSize: 2500,
            dropletSizeX: 1,
            dropletSizeYScale: 10,
            distortionStrength: 70,
            screenThinning: {
                intensity: 0.57,
                start: 0.46,
                range: 1.17,
                fadePower: 0.17,
                affectedRatio: 1,
                particleOffset: -0.2
            },
            color: {
                r: 0.66,
                g: 0.68,
                b: 0.74,
                a: 0.7
            },
            direction: {
                x: -50,
                y: -35
            },
            shapeDirPower: 2,
            shapeNormalPower: 1
        };
        painter.tp;
        const scope = [
            'Precipitation',
            'Rain'
        ];
        this._revealParams = new PrecipitationRevealParams(painter.tp, scope);
        this._vignetteParams = {
            strength: 1,
            start: 0.7,
            range: 1,
            fadePower: 0.4,
            color: {
                r: 0.27,
                g: 0.27,
                b: 0.27,
                a: 1
            }
        };
        this.particlesCount = 16000;
    }
    update(painter) {
        const context = painter.context;
        if (!this.particlesVx) {
            const positions = generateUniformDistributedPointsInsideCube(this.particlesCount);
            const vertices = new index.dt();
            const triangles = new index.aU();
            let base = 0;
            const sRand = index.di(1323123451230);
            for (let i = 0; i < positions.length; ++i) {
                const p = positions[i];
                const angularVelocityScale = -1 + 2 * sRand();
                const velocityScale = sRand();
                const directionConeHeading = sRand();
                const directionConePitch = sRand();
                const data = [
                    angularVelocityScale,
                    velocityScale,
                    directionConeHeading,
                    directionConePitch
                ];
                vertices.emplaceBack(p[0], p[1], p[2], -1, -1, ...data);
                vertices.emplaceBack(p[0], p[1], p[2], 1, -1, ...data);
                vertices.emplaceBack(p[0], p[1], p[2], 1, 1, ...data);
                vertices.emplaceBack(p[0], p[1], p[2], -1, 1, ...data);
                triangles.emplaceBack(base + 0, base + 1, base + 2);
                triangles.emplaceBack(base + 0, base + 2, base + 3);
                base += 4;
            }
            this.particlesVx = context.createVertexBuffer(vertices, rainLayout.members);
            this.particlesIdx = context.createIndexBuffer(triangles);
        }
    }
    draw(painter) {
        if (!this._params.overrideStyleParameters && !painter.style.rain) {
            return;
        }
        const gp = this._params.overrideStyleParameters ? this._revealParams : {
            revealStart: 0,
            revealRange: 0.01
        };
        const zoom = painter.transform.zoom;
        if (gp.revealStart > zoom) {
            return;
        }
        const revealFactor = lerpClamp(0, 1, gp.revealStart, gp.revealStart + gp.revealRange, zoom);
        if (!this.particlesVx || !this.particlesIdx) {
            return;
        }
        const params = structuredClone(this._params);
        let rainDirection = [
            -params.direction.x,
            params.direction.y,
            -100
        ];
        index.ab.vec3.normalize(rainDirection, rainDirection);
        const vignetteParams = structuredClone(this._vignetteParams);
        vignetteParams.strength *= revealFactor;
        if (!params.overrideStyleParameters) {
            params.intensity = painter.style.rain.state.density;
            params.timeFactor = painter.style.rain.state.intensity;
            params.color = structuredClone(painter.style.rain.state.color);
            rainDirection = structuredClone(painter.style.rain.state.direction);
            params.screenThinning.intensity = painter.style.rain.state.centerThinning;
            params.dropletSizeX = painter.style.rain.state.dropletSize[0];
            params.dropletSizeYScale = painter.style.rain.state.dropletSize[1] / painter.style.rain.state.dropletSize[0];
            params.distortionStrength = painter.style.rain.state.distortionStrength * 100;
            vignetteParams.strength = 1;
            vignetteParams.color = structuredClone(painter.style.rain.state.vignetteColor);
        }
        const drawData = this.updateOnRender(painter, params.timeFactor);
        const context = painter.context;
        const gl = context.gl;
        const tr = painter.transform;
        if (!this.screenTexture || this.screenTexture.size[0] !== painter.width || this.screenTexture.size[1] !== painter.height) {
            this.screenTexture = new index.T(context, {
                width: painter.width,
                height: painter.height,
                data: null
            }, gl.RGBA8);
        }
        if (params.distortionStrength > 0) {
            context.activeTexture.set(gl.TEXTURE0);
            this.screenTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, painter.width, painter.height);
        }
        const program = painter.getOrCreateProgram('rainParticle');
        painter.uploadCommonUniforms(context, program);
        context.activeTexture.set(gl.TEXTURE0);
        this.screenTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        const colorVec = [
            params.color.r,
            params.color.g,
            params.color.b,
            params.color.a
        ];
        const drawParticlesBox = (boxSize, distortionOnly) => {
            const camPos = boxWrap(this._movement.getPosition(), boxSize);
            const sizeX = params.dropletSizeX;
            const sizeY = params.dropletSizeX * params.dropletSizeYScale;
            const thinningX = painter.width / 2;
            const thinningY = painter.height / 2;
            const thinningStart = lerpClamp(0, params.screenThinning.start, 0, 1, params.screenThinning.intensity);
            const thinningRange = lerpClamp(0.001, params.screenThinning.range, 0, 1, params.screenThinning.intensity);
            const thinningParticleOffset = lerpClamp(0, params.screenThinning.particleOffset, 0, 1, params.screenThinning.intensity);
            const uniforms = rainUniformValues({
                modelview: drawData.modelviewMatrix,
                projection: drawData.projectionMatrix,
                time: this._accumulatedTimeFromStart,
                camPos,
                velocityConeAperture: params.velocityConeAperture,
                velocity: params.velocity,
                boxSize,
                rainDropletSize: [
                    sizeX,
                    sizeY
                ],
                distortionStrength: params.distortionStrength,
                rainDirection,
                color: colorVec,
                screenSize: [
                    tr.width,
                    tr.height
                ],
                thinningCenterPos: [
                    thinningX,
                    thinningY
                ],
                thinningShape: [
                    thinningStart,
                    thinningRange,
                    Math.pow(10, params.screenThinning.fadePower)
                ],
                thinningAffectedRatio: params.screenThinning.affectedRatio,
                thinningParticleOffset,
                shapeDirectionalPower: params.shapeDirPower,
                shapeNormalPower: params.shapeNormalPower,
                mode: distortionOnly ? 0 : 1
            });
            const count = Math.round(params.intensity * this.particlesCount);
            const particlesSegments = index.b7.simpleSegment(0, 0, count * 4, count * 2);
            program.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniforms, 'rain_particles', this.particlesVx, this.particlesIdx, particlesSegments, {});
        };
        if (params.distortionStrength > 0) {
            drawParticlesBox(params.boxSize, true);
        }
        drawParticlesBox(params.boxSize, false);
        this._vignette.draw(painter, vignetteParams);
    }
}

const snowLayout = index.da([
    {
        type: 'Float32',
        name: 'a_pos_3f',
        components: 3
    },
    {
        type: 'Float32',
        name: 'a_uv',
        components: 2
    },
    {
        type: 'Float32',
        name: 'a_snowParticleData',
        components: 4
    },
    {
        type: 'Float32',
        name: 'a_snowParticleDataHorizontalOscillation',
        components: 2
    }
]);

class Snow extends PrecipitationBase {
    constructor(painter) {
        super(2.25);
        this._params = {
            overrideStyleParameters: false,
            intensity: 0.85,
            timeFactor: 0.75,
            velocityConeAperture: 70,
            velocity: 40,
            horizontalOscillationRadius: 4,
            horizontalOscillationRate: 1.5,
            boxSize: 2000,
            billboardSize: 2,
            shapeFadeStart: 0.27,
            shapeFadePower: 0.21,
            screenThinning: {
                intensity: 0.4,
                start: 0.15,
                range: 1.4,
                fadePower: 0.24,
                affectedRatio: 1,
                particleOffset: -0.2
            },
            color: {
                r: 1,
                g: 1,
                b: 1,
                a: 1
            },
            direction: {
                x: -50,
                y: -35
            }
        };
        painter.tp;
        const scope = [
            'Precipitation',
            'Snow'
        ];
        this._revealParams = new PrecipitationRevealParams(painter.tp, scope);
        this._vignetteParams = {
            strength: 0.3,
            start: 0.78,
            range: 0.46,
            fadePower: 0.2,
            color: {
                r: 1,
                g: 1,
                b: 1,
                a: 1
            }
        };
        this.particlesCount = 16000;
    }
    update(painter) {
        const context = painter.context;
        if (!this.particlesVx) {
            const positions = generateUniformDistributedPointsInsideCube(this.particlesCount);
            const vertices = new index.du();
            const triangles = new index.aU();
            let base = 0;
            const sRand = index.di(1323123451230);
            for (let i = 0; i < positions.length; ++i) {
                const p = positions[i];
                const velocityScale = sRand();
                const directionConeHeading = sRand();
                const directionConePitch = sRand();
                const data = [
                    i / positions.length,
                    velocityScale,
                    directionConeHeading,
                    directionConePitch
                ];
                const dataHorizontalOscillation = [
                    sRand(),
                    sRand()
                ];
                vertices.emplaceBack(p[0], p[1], p[2], -1, -1, ...data, ...dataHorizontalOscillation);
                vertices.emplaceBack(p[0], p[1], p[2], 1, -1, ...data, ...dataHorizontalOscillation);
                vertices.emplaceBack(p[0], p[1], p[2], 1, 1, ...data, ...dataHorizontalOscillation);
                vertices.emplaceBack(p[0], p[1], p[2], -1, 1, ...data, ...dataHorizontalOscillation);
                triangles.emplaceBack(base + 0, base + 1, base + 2);
                triangles.emplaceBack(base + 0, base + 2, base + 3);
                base += 4;
            }
            this.particlesVx = context.createVertexBuffer(vertices, snowLayout.members);
            this.particlesIdx = context.createIndexBuffer(triangles);
        }
    }
    draw(painter) {
        if (!this._params.overrideStyleParameters && !painter.style.snow) {
            return;
        }
        const params = structuredClone(this._params);
        let snowDirection = [
            -params.direction.x,
            params.direction.y,
            -100
        ];
        index.ab.vec3.normalize(snowDirection, snowDirection);
        const vignetteParams = structuredClone(this._vignetteParams);
        const gp = params.overrideStyleParameters ? this._revealParams : {
            revealStart: 0,
            revealRange: 0.01
        };
        const zoom = painter.transform.zoom;
        if (gp.revealStart > zoom) {
            return;
        }
        const revealFactor = lerpClamp(0, 1, gp.revealStart, gp.revealStart + gp.revealRange, zoom);
        vignetteParams.strength *= revealFactor;
        if (!params.overrideStyleParameters) {
            params.intensity = painter.style.snow.state.density;
            params.timeFactor = painter.style.snow.state.intensity;
            params.color = structuredClone(painter.style.snow.state.color);
            snowDirection = structuredClone(painter.style.snow.state.direction);
            params.screenThinning.intensity = painter.style.snow.state.centerThinning;
            params.billboardSize = 2.79 * painter.style.snow.state.flakeSize;
            vignetteParams.strength = 1;
            vignetteParams.color = structuredClone(painter.style.snow.state.vignetteColor);
        }
        const drawData = this.updateOnRender(painter, params.timeFactor);
        if (!this.particlesVx || !this.particlesIdx) {
            return;
        }
        const context = painter.context;
        const gl = context.gl;
        const tr = painter.transform;
        const program = painter.getOrCreateProgram('snowParticle');
        painter.uploadCommonUniforms(context, program);
        const drawParticlesBox = (boxSize, sizeScale, dp) => {
            const camPos = boxWrap(this._movement.getPosition(), boxSize);
            const thinningX = tr.width / 2;
            const thinningY = tr.height / 2;
            const thinningStart = lerpClamp(0, dp.screenThinning.start, 0, 1, dp.screenThinning.intensity);
            const thinningRange = lerpClamp(0.001, dp.screenThinning.range, 0, 1, dp.screenThinning.intensity);
            const thinningParticleOffset = lerpClamp(0, dp.screenThinning.particleOffset, 0, 1, dp.screenThinning.intensity);
            const uniforms = snowUniformValues({
                modelview: drawData.modelviewMatrix,
                projection: drawData.projectionMatrix,
                time: this._accumulatedTimeFromStart,
                camPos,
                velocityConeAperture: dp.velocityConeAperture,
                velocity: dp.velocity,
                horizontalOscillationRadius: dp.horizontalOscillationRadius,
                horizontalOscillationRate: dp.horizontalOscillationRate,
                boxSize,
                billboardSize: dp.billboardSize * sizeScale,
                simpleShapeParameters: [
                    dp.shapeFadeStart,
                    dp.shapeFadePower
                ],
                screenSize: [
                    tr.width,
                    tr.height
                ],
                thinningCenterPos: [
                    thinningX,
                    thinningY
                ],
                thinningShape: [
                    thinningStart,
                    thinningRange,
                    Math.pow(10, dp.screenThinning.fadePower)
                ],
                thinningAffectedRatio: dp.screenThinning.affectedRatio,
                thinningParticleOffset,
                color: [
                    dp.color.r,
                    dp.color.g,
                    dp.color.b,
                    dp.color.a
                ],
                direction: snowDirection
            });
            const count = Math.round(dp.intensity * this.particlesCount);
            const particlesSegments = index.b7.simpleSegment(0, 0, count * 4, count * 2);
            if (this.particlesVx && this.particlesIdx) {
                program.draw(painter, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniforms, 'snow_particles', this.particlesVx, this.particlesIdx, particlesSegments, {});
            }
        };
        drawParticlesBox(params.boxSize, 1, params);
        this._vignette.draw(painter, vignetteParams);
    }
}

const draw = {
    symbol: drawSymbols,
    circle: drawCircles,
    heatmap: drawHeatmap,
    line: drawLine,
    fill: drawFill,
    'fill-extrusion': draw$1,
    hillshade: drawHillshade,
    raster: drawRaster,
    'raster-particle': drawRasterParticle,
    background: drawBackground,
    sky: drawSky,
    debug: drawDebug,
    custom: drawCustom,
    model: drawModels
};
const prepare = {
    line: prepare$4,
    model: prepare$1,
    raster: prepare$3,
    'raster-particle': prepare$2
};
class Painter {
    constructor(gl, contextCreateOptions, transform, scaleFactor, tp) {
        this.context = new Context(gl, contextCreateOptions);
        this.transform = transform;
        this._tileTextures = {};
        this.frameCopies = [];
        this.loadTimeStamps = [];
        this.tp = tp;
        this._timeStamp = index.q.now();
        this._averageFPS = 0;
        this._fpsHistory = [];
        this._dt = 0;
        this._debugParams = {
            forceEnablePrecipitation: false,
            showTerrainProxyTiles: false,
            fpsWindow: 30,
            continousRedraw: false,
            enabledLayers: {}
        };
        const layerTypes = [
            'fill',
            'line',
            'symbol',
            'circle',
            'heatmap',
            'fill-extrusion',
            'raster',
            'raster-particle',
            'hillshade',
            'model',
            'background',
            'sky'
        ];
        for (const layerType of layerTypes) {
            this._debugParams.enabledLayers[layerType] = true;
        }
        tp.registerParameter(this._debugParams, ['Terrain'], 'showTerrainProxyTiles', {}, () => {
            this.style.map.triggerRepaint();
        });
        tp.registerParameter(this._debugParams, ['Precipitation'], 'forceEnablePrecipitation');
        tp.registerParameter(this._debugParams, ['FPS'], 'fpsWindow', {
            min: 1,
            max: 100,
            step: 1
        });
        tp.registerBinding(this._debugParams, ['FPS'], 'continousRedraw', {
            readonly: true,
            label: 'continuous redraw'
        });
        tp.registerBinding(this, ['FPS'], '_averageFPS', {
            readonly: true,
            label: 'value'
        });
        tp.registerBinding(this, ['FPS'], '_averageFPS', {
            readonly: true,
            label: 'graph',
            view: 'graph',
            min: 0,
            max: 200
        });
        for (const layerType of layerTypes) {
            tp.registerParameter(this._debugParams.enabledLayers, [
                'Debug',
                'Layers'
            ], layerType);
        }
        this.occlusionParams = new OcclusionParams(tp);
        this.setup();
        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 index.dv();
        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;
        this.layersWithOcclusionOpacity = [];
        const emptyDepth = new index.r({
            width: 1,
            height: 1
        }, Uint8Array.of(0, 0, 0, 0));
        this.emptyDepthTexture = new index.T(this.context, emptyDepth, gl.RGBA8);
        this._clippingActiveLastFrame = false;
        this.scaleFactor = scaleFactor;
    }
    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) {
            this.transform.elevation = null;
        }
    }
    _updateFog(style) {
        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;
        }
        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._forceTerrainMode ? this._terrain : null;
    }
    get forceTerrainMode() {
        return this._forceTerrainMode;
    }
    set forceTerrainMode(value) {
        if (value && !this._terrain) {
            this._terrain = new Terrain(this, this.style);
        }
        this._forceTerrainMode = value;
    }
    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 * index.q.devicePixelRatio;
        this.height = height * index.q.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 index.b4();
        tileExtentArray.emplaceBack(0, 0);
        tileExtentArray.emplaceBack(index.ag, 0);
        tileExtentArray.emplaceBack(0, index.ag);
        tileExtentArray.emplaceBack(index.ag, index.ag);
        this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, index.b6.members);
        this.tileExtentSegments = index.b7.simpleSegment(0, 0, 4, 2);
        const debugArray = new index.b4();
        debugArray.emplaceBack(0, 0);
        debugArray.emplaceBack(index.ag, 0);
        debugArray.emplaceBack(0, index.ag);
        debugArray.emplaceBack(index.ag, index.ag);
        this.debugBuffer = context.createVertexBuffer(debugArray, index.b6.members);
        this.debugSegments = index.b7.simpleSegment(0, 0, 4, 5);
        const viewportArray = new index.b4();
        viewportArray.emplaceBack(-1, -1);
        viewportArray.emplaceBack(1, -1);
        viewportArray.emplaceBack(-1, 1);
        viewportArray.emplaceBack(1, 1);
        this.viewportBuffer = context.createVertexBuffer(viewportArray, index.b6.members);
        this.viewportSegments = index.b7.simpleSegment(0, 0, 4, 2);
        const tileBoundsArray = new index.aT();
        tileBoundsArray.emplaceBack(0, 0, 0, 0);
        tileBoundsArray.emplaceBack(index.ag, 0, index.ag, 0);
        tileBoundsArray.emplaceBack(0, index.ag, 0, index.ag);
        tileBoundsArray.emplaceBack(index.ag, index.ag, index.ag, index.ag);
        this.mercatorBoundsBuffer = context.createVertexBuffer(tileBoundsArray, index.b9.members);
        this.mercatorBoundsSegments = index.b7.simpleSegment(0, 0, 4, 2);
        const quadTriangleIndices = new index.aU();
        quadTriangleIndices.emplaceBack(0, 1, 2);
        quadTriangleIndices.emplaceBack(2, 1, 3);
        this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);
        const tileLineStripIndices = new index.b5();
        for (const i of [
                0,
                1,
                3,
                2,
                0
            ])
            tileLineStripIndices.emplaceBack(i);
        this.debugIndexBuffer = context.createIndexBuffer(tileLineStripIndices);
        this.emptyTexture = new index.T(context, new index.r({
            width: 1,
            height: 1
        }, Uint8Array.of(0, 0, 0, 0)), context.gl.RGBA8);
        this.identityMat = index.ab.mat4.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(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 = void 0;
        this._tileClippingMaskIDs = {};
        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 = void 0;
            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;
            for (const coord of tileIDs) {
                if (this._tileClippingMaskIDs[coord.key] === void 0) {
                    dirtyStencilClippingMasks = true;
                    break;
                }
            }
            if (!dirtyStencilClippingMasks) {
                return;
            }
        }
        this.currentStencilSource = sourceCache.id;
        const context = this.context;
        const gl = context.gl;
        if (this.nextStencilID + tileIDs.length > 256) {
            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 = void 0;
        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 = void 0;
            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 index.aj(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 index.aj(0, 0, 0, emissiveStrengthForDrapedLayers === void 0 ? 0 : emissiveStrengthForDrapedLayers), [
                true,
                true,
                true,
                true
            ]);
        } else {
            return this.colorModeForRenderPass();
        }
    }
    depthModeForSublayer(n, mask, func, skipOpaquePassCutoff = false) {
        if (this.depthOcclusion) {
            return new DepthMode(this.context.gl.GREATER, DepthMode.ReadOnly, this.depthRangeFor3D);
        }
        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;
    }
    blitDepth() {
        const gl = this.context.gl;
        const depthWidth = Math.ceil(this.width);
        const depthHeight = Math.ceil(this.height);
        const fboPrev = this.context.bindFramebuffer.get();
        const texturePrev = gl.getParameter(gl.TEXTURE_BINDING_2D);
        if (!this.depthFBO || this.depthFBO.width !== depthWidth || this.depthFBO.height !== depthHeight) {
            if (this.depthFBO) {
                this.depthFBO.destroy();
                this.depthFBO = void 0;
                this.depthTexture = void 0;
            }
            if (depthWidth !== 0 && depthHeight !== 0) {
                this.depthFBO = new Framebuffer(this.context, depthWidth, depthHeight, false, 'texture');
                this.depthTexture = new index.T(this.context, {
                    width: depthWidth,
                    height: depthHeight,
                    data: null
                }, gl.DEPTH24_STENCIL8);
                this.depthFBO.depthAttachment.set(this.depthTexture.texture);
            }
        }
        this.context.bindFramebuffer.set(fboPrev);
        gl.bindTexture(gl.TEXTURE_2D, texturePrev);
        if (this.depthFBO) {
            gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
            gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this.depthFBO.framebuffer);
            gl.blitFramebuffer(0, 0, depthWidth, depthHeight, 0, 0, depthWidth, depthHeight, gl.DEPTH_BUFFER_BIT, gl.NEAREST);
            gl.bindFramebuffer(gl.FRAMEBUFFER, this.context.bindFramebuffer.current);
        }
    }
    updateAverageFPS() {
        const fps = this._dt === 0 ? 0 : 1000 / this._dt;
        this._fpsHistory.push(fps);
        if (this._fpsHistory.length > this._debugParams.fpsWindow) {
            this._fpsHistory.splice(0, this._fpsHistory.length - this._debugParams.fpsWindow);
        }
        this._averageFPS = Math.round(this._fpsHistory.reduce((accum, current) => {
            return accum + current / this._fpsHistory.length;
        }, 0));
    }
    render(style, options) {
        const curTime = index.q.now();
        this._dt = curTime - this._timeStamp;
        this._timeStamp = curTime;
        this._wireframeDebugCache.update(this.frameCounter);
        this._debugParams.continousRedraw = style.map.repaint;
        this.style = style;
        this.options = options;
        const layers = this.style._mergedLayers;
        const drapingEnabled = !!(this.terrain && this.terrain.enabled);
        const getLayerIds = () => this.style._getOrder(drapingEnabled).filter(id => {
            const layer = layers[id];
            if (layer.type in this._debugParams.enabledLayers) {
                return this._debugParams.enabledLayers[layer.type];
            }
            return true;
        });
        let layerIds = getLayerIds();
        let layersRequireTerrainDepth = false;
        let layersRequireFinalDepth = false;
        for (const id of layerIds) {
            const layer = layers[id];
            if (layer.type === 'circle') {
                layersRequireTerrainDepth = true;
            }
            if (layer.type === 'symbol') {
                if (layer.hasInitialOcclusionOpacityProperties) {
                    layersRequireFinalDepth = true;
                } else {
                    layersRequireTerrainDepth = true;
                }
            }
        }
        let orderedLayers = layerIds.map(id => layers[id]);
        const sourceCaches = this.style._mergedSourceCaches;
        this.imageManager = style.imageManager;
        this.modelManager = style.modelManager;
        this.symbolFadeChange = style.placement.symbolFadeChange(index.q.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;
                }
            }
        }
        let clippingActiveThisFrame = false;
        for (const layer of orderedLayers) {
            if (layer.isHidden(this.transform.zoom))
                continue;
            if (layer.type === 'clip') {
                clippingActiveThisFrame = true;
            }
            this.prepareLayer(layer);
        }
        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 || clippingActiveThisFrame || this._clippingActiveLastFrame) {
            const conflationLayersInStyle = [];
            const conflationLayerIndicesInStyle = [];
            let idx = 0;
            for (const layer of orderedLayers) {
                if (this.isSourceForClippingOrConflation(layer, getLayerSource(layer))) {
                    conflationLayersInStyle.push(layer);
                    conflationLayerIndicesInStyle.push(idx);
                }
                idx++;
            }
            if (conflationLayersInStyle && (clippingActiveThisFrame || conflationLayersInStyle.length > 1) || this._clippingActiveLastFrame) {
                clippingActiveThisFrame = false;
                const conflationSources = [];
                for (let i = 0; i < conflationLayersInStyle.length; i++) {
                    const layer = conflationLayersInStyle[i];
                    const layerIdx = conflationLayerIndicesInStyle[i];
                    const sourceCache = this.style.getLayerSourceCache(layer);
                    if (!sourceCache || !sourceCache.used || !sourceCache.getSource().usedInConflation && layer.type !== 'clip') {
                        continue;
                    }
                    let order = index.dx;
                    let clipMask = index.by.None;
                    const clipScope = [];
                    let addToSources = true;
                    if (layer.type === 'clip') {
                        order = layerIdx;
                        for (const mask of layer.layout.get('clip-layer-types')) {
                            clipMask |= mask === 'model' ? index.by.Model : mask === 'symbol' ? index.by.Symbol : index.by.FillExtrusion;
                        }
                        for (const scope of layer.layout.get('clip-layer-scope')) {
                            clipScope.push(scope);
                        }
                        if (layer.isHidden(this.transform.zoom)) {
                            addToSources = false;
                        } else {
                            clippingActiveThisFrame = true;
                        }
                    }
                    if (addToSources) {
                        conflationSources.push({
                            layer: layer.fqid,
                            cache: sourceCache,
                            order,
                            clipMask,
                            clipScope
                        });
                    }
                }
                this.replacementSource.setSources(conflationSources);
                conflationActiveThisFrame = true;
            }
        }
        this._clippingActiveLastFrame = clippingActiveThisFrame;
        if (!conflationActiveThisFrame) {
            this.replacementSource.clear();
        }
        this.conflationActive = conflationActiveThisFrame;
        this.minCutoffZoom = 0;
        this.longestCutoffRange = 0;
        this.opaquePassCutoff = Infinity;
        this._lastOcclusionLayer = -1;
        this.layersWithOcclusionOpacity = [];
        for (let i = 0; i < orderedLayers.length; i++) {
            const layer = orderedLayers[i];
            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);
                }
            }
            if (layer.is3D()) {
                if (this.opaquePassCutoff === Infinity) {
                    this.opaquePassCutoff = i;
                }
                this._lastOcclusionLayer = i;
            }
        }
        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);
            this.opaquePassCutoff = 0;
            layerIds = getLayerIds();
            orderedLayers = layerIds.map(id => layers[id]);
        }
        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;
                    }
                    shadowRenderer.addShadowReceiver(coord.toUnwrapped(), tileHeight.min, tileHeight.max);
                }
            }
        }
        if (this.transform.projection.name === 'globe' && !this.globeSharedBuffers) {
            this.globeSharedBuffers = new index.dw(this.context);
        }
        if (this.style.fog && this.transform.projection.supportsFog) {
            if (!this._atmosphere) {
                this._atmosphere = new Atmosphere(this);
            }
            this._atmosphere.update(this);
        } else {
            if (this._atmosphere) {
                this._atmosphere.destroy();
                this._atmosphere = void 0;
            }
        }
        const snow = this._debugParams.forceEnablePrecipitation || !!(this.style && this.style.snow);
        const rain = this._debugParams.forceEnablePrecipitation || !!(this.style && this.style.rain);
        if (snow && !this._snow) {
            this._snow = new Snow(this);
        }
        if (!snow && this._snow) {
            this._snow.destroy();
            delete this._snow;
        }
        if (rain && !this._rain) {
            this._rain = new Rain(this);
        }
        if (!rain && this._rain) {
            this._rain.destroy();
            delete this._rain;
        }
        if (this._snow) {
            this._snow.update(this);
        }
        if (this._rain) {
            this._rain.update(this);
        }
        if (!isMapAuthenticated(this.context.gl))
            return;
        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] : void 0;
            if (!(layer.type === 'custom' || layer.type === 'raster' || layer.type === 'raster-particle' || layer.isSky()) && !(coords && coords.length))
                continue;
            this.renderLayer(this, sourceCache, layer, coords);
        }
        this.depthRangeFor3D = [
            0,
            1 - (orderedLayers.length + 2) * this.numSublayers * this.depthEpsilon
        ];
        if (this._shadowRenderer) {
            this.renderPass = 'shadow';
            this._shadowRenderer.drawShadowPass(this.style, coordsShadowCasters);
        }
        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();
        const clearColor = ((() => {
            if (options.showOverdrawInspector) {
                return index.aj.black;
            }
            const fog2 = this.style.fog;
            if (fog2 && this.transform.projection.supportsFog) {
                const fogLUT = this.style.getLut(fog2.scope);
                if (!shouldRenderAtmosphere) {
                    const ignoreLutColor = fog2.properties.get('color-use-theme') === 'none';
                    const fogColor = fog2.properties.get('color').toRenderColor(ignoreLutColor ? null : fogLUT).toArray01();
                    return new index.aj(...fogColor);
                }
                if (shouldRenderAtmosphere) {
                    const ignoreLutColor = fog2.properties.get('space-color-use-theme') === 'none';
                    const spaceColor = fog2.properties.get('space-color').toRenderColor(ignoreLutColor ? null : fogLUT).toArray01();
                    return new index.aj(...spaceColor);
                }
            }
            return index.aj.transparent;
        })());
        this.context.clear({
            color: clearColor,
            depth: 1
        });
        this.clearStencil();
        this._showOverdrawInspector = options.showOverdrawInspector;
        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] : void 0;
                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);
        }
        this.renderPass = 'sky';
        const drawSkyOnGlobe = !this._atmosphere || index.ae(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] : void 0;
                this.renderLayer(this, sourceCache, layer, coords);
            }
        }
        this.renderPass = 'translucent';
        function coordsForTranslucentLayer(layer, sourceCache) {
            let coords;
            if (sourceCache) {
                const coordsSet = layer.type === 'symbol' ? coordsDescendingSymbol : layer.is3D() ? coordsSortedByDistance : coordsDescending;
                coords = coordsSet[sourceCache.id];
            }
            return coords;
        }
        const isGlobe = this.transform.projection.name === 'globe';
        if (isGlobe) {
            this.renderElevatedRasterBackface = true;
            this.currentLayer = 0;
            while (this.currentLayer < layerIds.length) {
                const layer = orderedLayers[this.currentLayer];
                if (layer.type === 'raster' || layer.type === 'raster-particle') {
                    const sourceCache = style.getLayerSourceCache(layer);
                    this.renderLayer(this, sourceCache, layer, coordsForTranslucentLayer(layer, sourceCache));
                }
                ++this.currentLayer;
            }
            this.renderElevatedRasterBackface = false;
        }
        this.currentLayer = 0;
        this.firstLightBeamLayer = Number.MAX_SAFE_INTEGER;
        let shadowLayers = 0;
        if (shadowRenderer) {
            shadowLayers = shadowRenderer.getShadowCastingLayerCount();
        }
        let terrainDepthCopied = false;
        let last3DLayerIdx = -1;
        for (let i = 0; i < layerIds.length; ++i) {
            const layer = orderedLayers[i];
            if (layer.isHidden(this.transform.zoom)) {
                continue;
            }
            if (layer.is3D()) {
                last3DLayerIdx = i;
            }
        }
        if (layersRequireFinalDepth && last3DLayerIdx === -1) {
            layersRequireTerrainDepth = true;
        }
        while (this.currentLayer < layerIds.length) {
            const layer = orderedLayers[this.currentLayer];
            const sourceCache = style.getLayerSourceCache(layer);
            if (layer.isSky()) {
                ++this.currentLayer;
                continue;
            }
            if (this.terrain && this.style.isLayerDraped(layer)) {
                if (layer.isHidden(this.transform.zoom)) {
                    ++this.currentLayer;
                    continue;
                }
                this.currentLayer;
                this.currentLayer = this.terrain.renderBatch(this.currentLayer);
                this._lastOcclusionLayer = Math.max(this.currentLayer, this._lastOcclusionLayer);
                continue;
            }
            if (layersRequireTerrainDepth && !terrainDepthCopied && this.terrain && !this.transform.isOrthographic) {
                terrainDepthCopied = true;
                this.blitDepth();
            }
            if (layersRequireFinalDepth && last3DLayerIdx !== -1 && this.currentLayer === last3DLayerIdx + 1 && !this.transform.isOrthographic) {
                this.blitDepth();
            }
            if (!layer.is3D() && !this.terrain) {
                this._renderTileClippingMasks(layer, sourceCache, sourceCache ? coordsAscending[sourceCache.id] : void 0);
            }
            this.renderLayer(this, sourceCache, layer, coordsForTranslucentLayer(layer, sourceCache));
            if (!this.terrain && shadowRenderer && shadowLayers > 0 && layer.hasShadowPass() && --shadowLayers === 0) {
                shadowRenderer.drawGroundShadows();
                if (this.firstLightBeamLayer <= this.currentLayer) {
                    const saveCurrentLayer = this.currentLayer;
                    this.renderPass = 'light-beam';
                    for (this.currentLayer = this.firstLightBeamLayer; this.currentLayer <= saveCurrentLayer; this.currentLayer++) {
                        const layer2 = orderedLayers[this.currentLayer];
                        if (!layer2.hasLightBeamPass())
                            continue;
                        const sourceCache2 = style.getLayerSourceCache(layer2);
                        const coords = sourceCache2 ? coordsDescending[sourceCache2.id] : void 0;
                        this.renderLayer(this, sourceCache2, layer2, coords);
                    }
                    this.currentLayer = saveCurrentLayer;
                    this.renderPass = 'translucent';
                }
            }
            if (this.currentLayer >= this._lastOcclusionLayer && this.layersWithOcclusionOpacity.length > 0) {
                const saveCurrentLayer = this.currentLayer;
                this.depthOcclusion = true;
                for (const current of this.layersWithOcclusionOpacity) {
                    this.currentLayer = current;
                    const layer2 = orderedLayers[this.currentLayer];
                    const sourceCache2 = style.getLayerSourceCache(layer2);
                    const coords = sourceCache2 ? coordsDescending[sourceCache2.id] : void 0;
                    if (!layer2.is3D() && !this.terrain) {
                        this._renderTileClippingMasks(layer2, sourceCache2, sourceCache2 ? coordsAscending[sourceCache2.id] : void 0);
                    }
                    this.renderLayer(this, sourceCache2, layer2, coords);
                }
                this.depthOcclusion = false;
                this.currentLayer = saveCurrentLayer;
                this.renderPass = 'translucent';
                this.layersWithOcclusionOpacity = [];
            }
            ++this.currentLayer;
        }
        if (this.terrain) {
            this.terrain.postRender();
        }
        if (this._snow) {
            this._snow.draw(this);
        }
        if (this._rain) {
            this._rain.draw(this);
        }
        if (this.options.showTileBoundaries || this.options.showQueryGeometry || this.options.showTileAABBs) {
            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(), index.aj.red, false, this.options.showParseStatus);
                }
            }
        }
        if (this.terrain && this._debugParams.showTerrainProxyTiles) {
            draw.debug(this, this.terrain.proxySourceCache, this.terrain.proxyCoords, new index.aj(1, 0.8, 0.1, 1), true, this.options.showParseStatus);
        }
        if (this.options.showPadding) {
            drawDebugPadding(this);
        }
        this.context.setDefault();
        this.frameCounter = (this.frameCounter + 1) % Number.MAX_SAFE_INTEGER;
        if (this.tileLoaded && this.options.speedIndexTiming) {
            this.loadTimeStamps.push(performance.now());
            this.saveCanvasCopy();
        }
        if (!conflationActiveThisFrame) {
            this.conflationActive = false;
        }
    }
    prepareLayer(layer) {
        this.gpuTimingStart(layer);
        const {unsupportedLayers} = this.transform.projection;
        const isLayerSupported = unsupportedLayers ? !unsupportedLayers.includes(layer.type) : true;
        const isCustomLayerWithTerrain = this.terrain && layer.type === 'custom';
        if (prepare[layer.type] && (isLayerSupported || isCustomLayerWithTerrain)) {
            const sourceCache = this.style.getLayerSourceCache(layer);
            prepare[layer.type](layer, sourceCache, this);
        }
        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' && layer.type !== 'raster-particle' && !(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') && layer.type !== 'clip') {
            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;
        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 gl = this.context.gl;
        let gpuTime = 0;
        for (const query of gpuQueries) {
            gpuTime += gl.getQueryParameter(query, gl.QUERY_RESULT) / (1000 * 1000);
            gl.deleteQuery(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] : index.ar(tile, translate[0], this.transform.zoom),
            inViewportPixelUnitsUnits ? translate[1] : index.ar(tile, translate[1], this.transform.zoom),
            0
        ];
        const translatedMatrix = new Float32Array(16);
        index.ab.mat4.translate(translatedMatrix, matrix, translation);
        return translatedMatrix;
    }
    /**
   * Saves the tile texture for re-use when another tile is loaded.
   *
   * @returns true if the tile was cached, false if the tile was not cached and should be destroyed.
   * @private
   */
    saveTileTexture(texture) {
        const tileSize = texture.size[0];
        const textures = this._tileTextures[tileSize];
        if (!textures) {
            this._tileTextures[tileSize] = [texture];
        } else {
            textures.push(texture);
        }
    }
    getTileTexture(size) {
        const textures = this._tileTextures[size];
        return textures && textures.length > 0 ? textures.pop() : null;
    }
    terrainRenderModeElevated() {
        return this.style && !!this.style.getTerrain() && !!this.terrain && !this.terrain.renderingToTexture || this.forceTerrainMode;
    }
    linearFloatFilteringSupported() {
        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 === void 0 ? this.terrain && this.terrain.renderingToTexture : overrideRtt;
        const defines = [];
        if (this.style && this.style.enable3dLights()) {
            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');
        }
        if (this.terrainRenderModeElevated()) {
            defines.push('TERRAIN');
            if (this.linearFloatFilteringSupported())
                defines.push('TERRAIN_DEM_FLOAT_FORMAT');
        }
        if (this.transform.projection.name === 'globe')
            defines.push('GLOBE');
        if (this._fogVisible && !rtt && (overrideFog === void 0 || 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() {
        this.context.unbindVAO();
        this.context.cullFace.setDefault();
        this.context.frontFace.setDefault();
        this.context.cullFaceSide.setDefault();
        this.context.activeTexture.setDefault();
        this.context.pixelStoreUnpack.setDefault();
        this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();
        this.context.pixelStoreUnpackFlipY.setDefault();
    }
    /*
   * 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 = document.createElement('canvas');
            this.debugOverlayCanvas.width = 512;
            this.debugOverlayCanvas.height = 512;
            const gl = this.context.gl;
            this.debugOverlayTexture = new index.T(this.context, this.debugOverlayCanvas, gl.RGBA8);
        }
    }
    destroy() {
        if (this._terrain) {
            this._terrain.destroy();
        }
        if (this._atmosphere) {
            this._atmosphere.destroy();
            this._atmosphere = void 0;
        }
        if (this.globeSharedBuffers) {
            this.globeSharedBuffers.destroy();
        }
        this.emptyTexture.destroy();
        if (this.debugOverlayTexture) {
            this.debugOverlayTexture.destroy();
        }
        this._wireframeDebugCache.destroy();
        if (this.depthFBO) {
            this.depthFBO.destroy();
            this.depthFBO = void 0;
            this.depthTexture = void 0;
        }
        if (this.emptyDepthTexture) {
            this.emptyDepthTexture.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, this.style);
                program.setLightsUniformValues(context, lightsUniforms);
            }
        }
    }
    uploadCommonUniforms(context, program, tileID, fogMatrix, cutoffParams) {
        this.uploadCommonLightUniforms(context, program);
        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 * index.q.devicePixelRatio,
                this.transform.height * index.q.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.
   */
    isSourceForClippingOrConflation(layer, source) {
        if (!layer.is3D()) {
            return false;
        }
        if (layer.type === 'clip') {
            return true;
        }
        if (layer.minzoom && layer.minzoom > this.transform.zoom) {
            return false;
        }
        if (!this.style._clipLayerPresent) {
            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;
    }
    // For native compatibility depth for occlusion is kept as before
    setupDepthForOcclusion(useDepthForOcclusion, program, uniforms) {
        const context = this.context;
        const gl = context.gl;
        const uniformsPresent = !!uniforms;
        if (!uniforms) {
            uniforms = defaultTerrainUniforms();
        }
        context.activeTexture.set(gl.TEXTURE3);
        if (useDepthForOcclusion && this.depthFBO && this.depthTexture) {
            this.depthTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
            uniforms['u_depth_size_inv'] = [
                1 / this.depthFBO.width,
                1 / this.depthFBO.height
            ];
            const getUnpackDepthRangeParams = depthRange => {
                const a = 2 / (depthRange[1] - depthRange[0]);
                const b = -1 - 2 * depthRange[0] / (depthRange[1] - depthRange[0]);
                return [
                    a,
                    b
                ];
            };
            uniforms['u_depth_range_unpack'] = getUnpackDepthRangeParams(this.depthRangeFor3D);
            uniforms['u_occluder_half_size'] = this.occlusionParams.occluderSize * 0.5;
            uniforms['u_occlusion_depth_offset'] = this.occlusionParams.depthOffset;
        } else {
            this.emptyDepthTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
        }
        context.activeTexture.set(gl.TEXTURE0);
        if (!uniformsPresent) {
            program.setTerrainUniformValues(context, uniforms);
        }
    }
}

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;
    };
}

class Hash {
    constructor(hashName) {
        this._hashName = hashName && encodeURIComponent(hashName);
        index.aP([
            '_getCurrentHash',
            '_onHashChange',
            '_updateHash'
        ], this);
        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;
        window.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);
        window.removeEventListener('hashchange', this._onHashChange, false);
        clearTimeout(this._updateHash());
        this._map = void 0;
        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 = 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() {
        const hash = location.hash.replace('#', '');
        if (this._hashName) {
            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() {
        history.replaceState(history.state, '', location.href.replace(/(#.+)?$/, this.getHashString()));
    }
}
function getHashString(map, mapFeedback) {
    const center = map.getCenter(), zoom = Math.round(map.getZoom() * 100) / 100, 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();
    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: index.dy(0, 0, 0.3, 1)
};
const defaultPanInertiaOptions = index.l({
    deceleration: 2500,
    maxSpeed: 1400
}, defaultInertiaOptions);
const defaultZoomInertiaOptions = index.l({
    deceleration: 20,
    maxSpeed: 1400
}, defaultInertiaOptions);
const defaultBearingInertiaOptions = index.l({
    deceleration: 1000,
    maxSpeed: 360
}, defaultInertiaOptions);
const defaultPitchInertiaOptions = index.l({
    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: index.q.now(),
            settings
        });
    }
    _drainInertiaBuffer() {
        const inertia = this._inertiaBuffer, now = index.q.now(), cutoff = 160;
        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 index.P(0, 0),
            pinchAround: void 0,
            around: void 0
        };
        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, index.l({}, 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 + index.aw(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 === void 0 ? deltas.around : deltas.pinchAround;
            easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();
        }
        this.clear();
        easeOptions.noMoveStart = true;
        return easeOptions;
    }
}
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 = index.aw(amount * linearity / (inertiaDuration / 1000), -maxSpeed, maxSpeed);
    const duration = Math.abs(speed) / (deceleration * linearity);
    return {
        easing: inertiaOptions.easing,
        duration: duration * 1000,
        amount: speed * (duration / 2)
    };
}

class MapMouseEvent extends index.z {
    /**
   * 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, index.l({
            point,
            lngLat,
            originalEvent
        }, data));
        this._defaultPrevented = false;
        this.target = map;
    }
}
class MapTouchEvent extends index.z {
    /**
   * 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 index.P(0, 0));
        const lngLat = map.unproject(point);
        super(type, {
            points,
            point,
            lngLats,
            lngLat,
            originalEvent
        });
        this._defaultPrevented = false;
    }
}
class MapWheelEvent extends index.z {
    /**
   * 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(map, originalEvent) {
        super('wheel', { originalEvent });
        this._defaultPrevented = false;
    }
}

class MapEventHandler {
    constructor(map, options) {
        this._map = map;
        this._clickTolerance = options.clickTolerance;
    }
    reset() {
        this._mousedownPos = void 0;
    }
    wheel(e) {
        return this._firePreventable(new MapWheelEvent(this._map, e));
    }
    mousedown(e, point) {
        this._mousedownPos = point;
        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 = index.l({}, 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) {
        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) {
        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) {
            return {};
        }
    }
    isEnabled() {
        return true;
    }
    isActive() {
        return false;
    }
    enable() {
    }
    disable() {
    }
}
class BlockableMapEventHandler {
    constructor(map) {
        this._map = map;
    }
    reset() {
        this._delayContextMenu = false;
        this._contextMenuEvent = void 0;
    }
    mousemove(e) {
        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) {
            this._contextMenuEvent = e;
        } else {
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
        }
        if (this._map.listens('contextmenu')) {
            e.preventDefault();
        }
    }
    isEnabled() {
        return true;
    }
    isActive() {
        return false;
    }
    enable() {
    }
    disable() {
    }
}

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$1('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 index.z('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 index.z(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 index.P(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 = void 0;
        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 = void 0;
        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;
const BUTTONS_FLAGS = {
    [LEFT_BUTTON]: 1,
    [RIGHT_BUTTON]: 2
};
function buttonStillPressed(e, button) {
    const flag = BUTTONS_FLAGS[button];
    return e.buttons === void 0 || (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 = void 0;
        this._eventButton = void 0;
    }
    _correctButton(e, button) {
        return false;
    }
    _move(lastPoint, point) {
        return {};
    }
    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)) {
            this.reset();
            return;
        }
        if (!this._moved && point.dist(lastPoint) < this._clickTolerance)
            return;
        this._moved = true;
        this._lastPoint = point;
        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) {
        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) {
        e.preventDefault();
    }
}

class TouchPanHandler {
    constructor(map, options) {
        this._map = map;
        this._el = map.getCanvasContainer();
        this._minTouches = 1;
        this._clickTolerance = options.clickTolerance || 1;
        this.reset();
        index.aP([
            '_addTouchPanBlocker',
            '_showTouchPanBlockerAlert'
        ], this);
    }
    reset() {
        this._active = false;
        this._touches = {};
        this._sum = new index.P(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 (this._map._cooperativeGestures && !this._map.isMoving()) {
            if (mapTouches.length === 1 && !index.dz()) {
                this._showTouchPanBlockerAlert();
                return;
            } else if (this._alertContainer.style.visibility !== 'hidden') {
                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 index.P(0, 0);
        const touchDeltaSum = new index.P(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();
            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$1('div', 'mapboxgl-touch-pan-blocker', this._map._container);
            this._alertContainer.textContent = this._map._getUIString('TouchPanBlocker.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 = window.setTimeout(() => {
            this._alertContainer.classList.remove('mapboxgl-touch-pan-blocker-show');
            this._alertContainer.removeAttribute('role');
        }, 500);
    }
}

class TwoTouchHandler {
    constructor() {
        this.reset();
    }
    reset() {
        this._active = false;
        this._firstTwoTouches = void 0;
    }
    _start(points) {
    }
    _move(points, pinchAround, e) {
        return {};
    }
    touchstart(e, points, mapTouches) {
        if (this._firstTwoTouches || mapTouches.length < 2)
            return;
        this._firstTwoTouches = [
            mapTouches[0].identifier,
            mapTouches[1].identifier
        ];
        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);
        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];
    }
}
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
        };
    }
}
const ROTATION_THRESHOLD = 25;
function getBearingDelta(a, b) {
    return a.angleWith(b) * 180 / Math.PI;
}
class TouchRotateHandler extends TwoTouchHandler {
    reset() {
        super.reset();
        this._minDiameter = 0;
        this._startVector = void 0;
        this._vector = void 0;
    }
    _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 {
            bearingDelta: getBearingDelta(this._vector, lastVector),
            pinchAround
        };
    }
    _isBelowThreshold(vector) {
        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;
    }
}
function isVertical(vector) {
    return Math.abs(vector.y) > Math.abs(vector.x);
}
const ALLOWED_SINGLE_TOUCH_TIME = 100;
class TouchPitchHandler extends TwoTouchHandler {
    constructor(map) {
        super();
        this._map = map;
    }
    reset() {
        super.reset();
        this._valid = void 0;
        this._firstMove = void 0;
        this._lastPoints = void 0;
    }
    _start(points) {
        this._lastPoints = points;
        if (isVertical(points[0].sub(points[1]))) {
            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 && !index.dz() && 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 !== void 0)
            return this._valid;
        const threshold = 2;
        const movedA = vectorA.mag() >= threshold;
        const movedB = vectorB.mag() >= threshold;
        if (!movedA && !movedB)
            return;
        if (!movedA || !movedB) {
            if (this._firstMove == null) {
                this._firstMove = timeStamp;
            }
            if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) {
                return void 0;
            } 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
};
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);
}

const wheelZoomDelta = 4.000244140625;
const defaultZoomRate = 1 / 100;
const wheelZoomRate = 1 / 450;
const maxScalePerFrame = 2;
class ScrollZoomHandler {
    /**
   * @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;
        index.aP([
            '_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(wheelZoomRate2) {
        this._wheelZoomRate = wheelZoomRate2;
    }
    /**
   * 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 !== void 0;
    }
    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() && !index.dz()) {
                this._showBlockerAlert();
                return;
            } else if (this._alertContainer.style.visibility !== 'hidden') {
                this._alertContainer.style.visibility = 'hidden';
                clearTimeout(this._alertTimer);
            }
        }
        let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;
        const now = index.q.now(), timeDelta = now - (this._lastWheelEventTime || 0);
        this._lastWheelEventTime = now;
        if (value !== 0 && value % wheelZoomDelta === 0) {
            this._type = 'wheel';
        } else if (value !== 0 && Math.abs(value) < 4) {
            this._type = 'trackpad';
        } else if (timeDelta > 400) {
            this._type = null;
            this._lastValue = value;
            this._timeout = window.setTimeout(this._onTimeout, 40, e);
        } else if (!this._type) {
            this._type = Math.abs(timeDelta * value) < 200 ? 'trackpad' : 'wheel';
            if (this._timeout) {
                clearTimeout(this._timeout);
                this._timeout = null;
                value += this._lastValue;
            }
        }
        if (e.shiftKey && value)
            value = value / 4;
        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 = void 0;
        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 (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 (this._delta !== 0) {
            const zoomRate = this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta ? this._wheelZoomRate : this._defaultZoomRate;
            let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));
            if (this._delta < 0 && scale !== 0) {
                scale = 1 / scale;
            }
            const startZoom2 = startingZoom();
            const startScale = Math.pow(2, startZoom2);
            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._type === 'wheel') {
                this._startZoom = startZoom2;
                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((index.q.now() - this._lastWheelEventTime) / 200, 1);
            const k = easing(t);
            zoom = index.af(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 = window.setTimeout(() => {
                this._zooming = false;
                this._handler._triggerRenderFrame();
                delete this._targetZoom;
                delete this._finishTimeout;
            }, 200);
        }
        let zoomDelta = zoom - startingZoom();
        if (zoomDelta * this._lastDelta < 0) {
            zoomDelta = 0;
        }
        return {
            noInertia: true,
            needsRenderFrame: !finished,
            zoomDelta,
            around: this._aroundPoint,
            aroundCoord: this._aroundCoord,
            originalEvent: this._lastWheelEvent
        };
    }
    _smoothOutEasing(duration) {
        let easing = index.dA;
        if (this._prevEase) {
            const ease = this._prevEase, t = (index.q.now() - ease.start) / ease.duration, speed = ease.easing(t + 0.01) - ease.easing(t), x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01, y = Math.sqrt(0.27 * 0.27 - x * x);
            easing = index.dy(x, y, 0.25, 1);
        }
        this._prevEase = {
            start: index.q.now(),
            duration,
            easing
        };
        return easing;
    }
    blur() {
        this.reset();
    }
    reset() {
        this._active = false;
    }
    _addScrollZoomBlocker() {
        if (this._map && !this._alertContainer) {
            this._alertContainer = create$1('div', 'mapboxgl-scroll-zoom-blocker', this._map._container);
            if (/(Mac|iPad)/i.test(navigator.userAgent)) {
                this._alertContainer.textContent = this._map._getUIString('ScrollZoomBlocker.CmdMessage');
            } else {
                this._alertContainer.textContent = this._map._getUIString('ScrollZoomBlocker.CtrlMessage');
            }
            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 = window.setTimeout(() => {
            this._alertContainer.classList.remove('mapboxgl-scroll-zoom-blocker-show');
            this._alertContainer.removeAttribute('role');
        }, 200);
    }
}

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 = void 0;
        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;
    }
}

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();
    }
}

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();
    }
}

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 index.z {
}
class TrackingEllipsoid {
    constructor() {
        this.constants = [
            1,
            1,
            0.01
        ];
        this.radius = 0;
    }
    setup(center, pointOnSurface) {
        const centerToSurface = index.ab.vec3.sub([], pointOnSurface, center);
        if (centerToSurface[2] < 0) {
            this.radius = index.ab.vec3.length(index.ab.vec3.div([], centerToSurface, this.constants));
        } else {
            this.radius = index.ab.vec3.length([
                centerToSurface[0],
                centerToSurface[1],
                0
            ]);
        }
    }
    // Cast a ray from the center of the ellipsoid and the intersection point.
    projectRay(dir) {
        index.ab.vec3.div(dir, dir, this.constants);
        index.ab.vec3.normalize(dir, dir);
        index.ab.vec3.mul(dir, dir, this.constants);
        const intersection = index.ab.vec3.scale([], dir, this.radius);
        if (intersection[2] > 0) {
            const h = index.ab.vec3.scale([], [
                0,
                0,
                1
            ], index.ab.vec3.dot(intersection, [
                0,
                0,
                1
            ]));
            const r = index.ab.vec3.scale([], index.ab.vec3.normalize([], [
                intersection[0],
                intersection[1],
                0
            ]), this.radius);
            const p = index.ab.vec3.add([], intersection, index.ab.vec3.scale([], index.ab.vec3.sub([], index.ab.vec3.add([], r, h), intersection), 2));
            intersection[0] = p[0];
            intersection[1] = p[1];
        }
        return intersection;
    }
}
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;
        this._eventsInProgress = {};
        this._addDefaultHandlers(options);
        index.aP([
            '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',
                void 0
            ],
            [
                el,
                'touchcancel',
                void 0
            ],
            [
                el,
                'mousedown',
                void 0
            ],
            [
                el,
                'mousemove',
                void 0
            ],
            [
                el,
                'mouseup',
                void 0
            ],
            // 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.
            [
                document,
                'mousemove',
                { capture: true }
            ],
            [
                document,
                'mouseup',
                void 0
            ],
            [
                el,
                'mouseover',
                void 0
            ],
            [
                el,
                'mouseout',
                void 0
            ],
            [
                el,
                'dblclick',
                void 0
            ],
            [
                el,
                'click',
                void 0
            ],
            [
                el,
                'keydown',
                { capture: false }
            ],
            [
                el,
                'keyup',
                void 0
            ],
            [
                el,
                'wheel',
                { passive: false }
            ],
            [
                el,
                'contextmenu',
                void 0
            ],
            [
                window,
                'blur',
                void 0
            ]
        ];
        for (const [target, type, listenerOptions] of this._listeners) {
            const listener = target === document ? this.handleWindowEvent : this.handleEvent;
            target.addEventListener(type, listener, listenerOptions);
        }
    }
    destroy() {
        for (const [target, type, listenerOptions] of this._listeners) {
            const listener = target === document ? this.handleWindowEvent : this.handleEvent;
            target.removeEventListener(type, listener, listenerOptions);
        }
    }
    _addDefaultHandlers(options) {
        const map = this._map;
        const el = map.getCanvasContainer();
        this._add('mapEvent', new MapEventHandler(map, options));
        const boxZoom = map.boxZoom = new BoxZoomHandler(map, options);
        this._add('boxZoom', boxZoom);
        const tapZoom = new TapZoomHandler();
        const clickZoom = new ClickZoomHandler();
        map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);
        this._add('tapZoom', tapZoom);
        this._add('clickZoom', clickZoom);
        const tapDragZoom = new TapDragZoomHandler();
        this._add('tapDragZoom', tapDragZoom);
        const touchPitch = map.touchPitch = new TouchPitchHandler(map);
        this._add('touchPitch', touchPitch);
        const mouseRotate = new MouseRotateHandler(options);
        const mousePitch = new MousePitchHandler(options);
        map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch);
        this._add('mouseRotate', mouseRotate, ['mousePitch']);
        this._add('mousePitch', mousePitch, ['mouseRotate']);
        const mousePan = new MousePanHandler(options);
        const touchPan = new TouchPanHandler(map, options);
        map.dragPan = new DragPanHandler(el, mousePan, touchPan);
        this._add('mousePan', mousePan);
        this._add('touchPan', touchPan, [
            'touchZoom',
            'touchRotate'
        ]);
        const touchRotate = new TouchRotateHandler();
        const touchZoom = new TouchZoomHandler();
        map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);
        this._add('touchRotate', touchRotate, [
            'touchPan',
            'touchZoom'
        ]);
        this._add('touchZoom', touchZoom, [
            'touchPan',
            'touchRotate'
        ]);
        this._add('blockableMapEvent', new BlockableMapEventHandler(map));
        const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this);
        this._add('scrollZoom', scrollZoom, ['mousePan']);
        const keyboard = map.keyboard = new KeyboardHandler();
        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) {
        if (this._updatingCamera)
            return;
        for (const {handler} of this._handlers) {
            handler.reset();
        }
        this._inertia.clear();
        this._fireEvents({}, {}, allowEndAnimation);
        this._changes = [];
        this._originalZoom = void 0;
    }
    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 ? void 0 : e;
        const mergedHandlerResult = { needsRenderFrame: false };
        const eventsInProgress = {};
        const activeHandlers = {};
        const mapTouches = e.touches ? this._getMapTouches(e.touches) : void 0;
        const points = mapTouches ? touchPos(this._el, mapTouches) : isRenderFrame ? void 0 : // 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;
        index.l(mergedHandlerResult, handlerResult);
        const eventData = {
            handlerName: name,
            originalEvent: handlerResult.originalEvent || e
        };
        if (handlerResult.zoomDelta !== void 0) {
            eventsInProgress.zoom = eventData;
        }
        if (handlerResult.panDelta !== void 0) {
            eventsInProgress.drag = eventData;
        }
        if (handlerResult.pitchDelta !== void 0) {
            eventsInProgress.pitch = eventData;
        }
        if (handlerResult.bearingDelta !== void 0) {
            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 index.P(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 !== void 0)
                combined.around = change.around;
            if (change.aroundCoord !== void 0)
                combined.aroundCoord = change.aroundCoord;
            if (change.pinchAround !== void 0)
                combined.pinchAround = change.pinchAround;
            if (change.noInertia)
                combined.noInertia = change.noInertia;
            index.l(combinedEventsInProgress, eventsInProgress);
            index.l(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) {
                tr.cameraElevationReference = 'ground';
                tr.zoom = this._originalZoom;
            } else {
                tr.recenterOnTerrain();
                tr.cameraElevationReference = 'ground';
            }
            if (preZoom !== tr.zoom)
                this._map._update(true);
        }
        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) {
            if (zoomDelta > 0)
                zoomDelta = 0;
            tr._isCameraConstrained = false;
        }
        if (pinchAround !== void 0) {
            around = pinchAround;
        }
        if ((zoomDelta || eventStarted('drag')) && around) {
            this._dragOrigin = toVec3(tr.pointCoordinate3D(around));
            this._originalZoom = tr.zoom;
            this._trackingEllipsoid.setup(tr._camera.position, this._dragOrigin);
        }
        tr.cameraElevationReference = 'sea';
        map._stop(true);
        around = around || map.transform.centerPoint;
        if (bearingDelta)
            tr.bearing += bearingDelta;
        if (pitchDelta)
            tr.pitch += pitchDelta;
        tr._updateCameraState();
        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') {
                    panDelta = panDelta.rotate(-tr.angle);
                    const scale = tr._pixelsPerMercatorPixel / tr.worldSize;
                    panVec[0] = -panDelta.x * index.dB(index.aS(startPoint.y)) * scale;
                    panVec[1] = -panDelta.y * index.dB(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;
        const zoomVec = [
            0,
            0,
            0
        ];
        if (zoomDelta) {
            const pickedPosition = aroundCoord ? toVec3(aroundCoord) : toVec3(tr.pointCoordinate3D(around));
            const aroundRay = { dir: index.ab.vec3.normalize([], index.ab.vec3.sub([], pickedPosition, tr._camera.position)) };
            if (aroundRay.dir[2] < 0) {
                const movement = tr.zoomDeltaToMovement(pickedPosition, zoomDelta);
                index.ab.vec3.scale(zoomVec, aroundRay.dir, movement);
            }
        }
        const translation = index.ab.vec3.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];
        }
        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 index.z('moveend', { originalEvent: originalEndEvent }));
                if (shouldSnapToNorth(this._map.getBearing())) {
                    this._map.resetNorth();
                }
            }
            this._updatingCamera = false;
        }
    }
    _fireEvent(type, event) {
        const eventData = event ? { originalEvent: event } : {};
        this._map.fire(new index.z(type, eventData));
    }
    _requestFrame() {
        this._map.triggerRepaint();
        return this._map._renderTaskQueue.add(timeStamp => {
            this._frameId = void 0;
            this.handleEvent(new RenderFrameEvent('renderFrame', { timeStamp }));
            this._applyChanges();
        });
    }
    _triggerRenderFrame() {
        if (this._frameId === void 0) {
            this._frameId = this._requestFrame();
        }
    }
}

const freeCameraNotSupportedWarning = 'map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.';
class Camera extends index.E {
    constructor(transform, options) {
        super();
        this._moving = false;
        this._zooming = false;
        this.transform = transform;
        this._bearingSnap = options.bearingSnap;
        this._respectPrefersReducedMotion = options.respectPrefersReducedMotion !== false;
        index.aP(['_renderFrameCallback'], 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 index.bO(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 = index.P.convert(offset).mult(-1);
        return this.panTo(this.transform.center, index.l({ 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(index.l({ 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(index.l({ 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(index.l({ 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, index.l({ 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(index.l({
            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 = index.az.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);
    }
    _extendPadding(padding) {
        const defaultPadding = {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        };
        if (padding == null)
            return index.l({}, defaultPadding, this.transform.padding);
        if (typeof padding === 'number') {
            return {
                top: padding,
                bottom: padding,
                right: padding,
                left: padding
            };
        }
        return index.l({}, defaultPadding, padding);
    }
    _extendCameraOptions(options) {
        options = index.l({
            offset: [
                0,
                0
            ],
            maxZoom: this.transform.maxZoom
        }, options);
        options.padding = this._extendPadding(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 = index.bO.convert(p0);
        const coord1 = index.bO.convert(p1);
        const midLat = (coord0.lat + coord1.lat) * 0.5;
        const midLng = (coord0.lng + coord1.lng) * 0.5;
        const origin = index.dC(midLat, midLng);
        const zAxis = index.ab.vec3.normalize([], origin);
        const xAxis = index.ab.vec3.normalize([], index.ab.vec3.cross([], zAxis, [
            0,
            1,
            0
        ]));
        const yAxis = index.ab.vec3.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,
            index.dC(coord0.lat, coord0.lng),
            index.dC(coord1.lat, coord0.lng),
            index.dC(coord1.lat, coord1.lng),
            index.dC(coord0.lat, coord1.lng),
            index.dC(midLat, coord0.lng),
            index.dC(midLat, coord1.lng),
            index.dC(coord0.lat, midLng),
            index.dC(coord1.lat, midLng)
        ];
        let aabb = index.cd.fromPoints(ecefCoords.map(p => [
            index.ab.vec3.dot(xAxis, p),
            index.ab.vec3.dot(yAxis, p),
            index.ab.vec3.dot(zAxis, p)
        ]));
        const center = index.ab.vec3.transformMat4([], aabb.center, aabbOrientation);
        if (index.ab.vec3.squaredLength(center) === 0) {
            index.ab.vec3.set(center, 0, 0, 1);
        }
        index.ab.vec3.normalize(center, center);
        index.ab.vec3.scale(center, center, index.ax);
        tr.center = index.dD(center);
        const worldToCamera = tr.getWorldToCameraMatrix();
        const cameraToWorld = index.ab.mat4.invert(new Float64Array(16), worldToCamera);
        aabb = index.cd.applyTransform(aabb, index.ab.mat4.multiply([], worldToCamera, aabbOrientation));
        const extendedAabb = this._extendAABB(aabb, tr, eOptions, bearing);
        if (!extendedAabb) {
            index.w('Map cannot fit within canvas with the given bounds, padding, and/or offset.');
            return;
        }
        aabb = extendedAabb;
        index.ab.vec3.transformMat4(center, center, worldToCamera);
        const aabbHalfExtentZ = (aabb.max[2] - aabb.min[2]) * 0.5;
        const frustumDistance = this._minimumAABBFrustumDistance(tr, aabb);
        const offsetZ = index.ab.vec3.scale([], [
            0,
            0,
            1
        ], aabbHalfExtentZ);
        const aabbClosestPoint = index.ab.vec3.add(offsetZ, center, offsetZ);
        const offsetDistance = frustumDistance + (tr.pitch === 0 ? 0 : index.ab.vec3.distance(center, aabbClosestPoint));
        const globeCenter = tr.globeCenterInViewSpace;
        const normal = index.ab.vec3.sub([], center, [
            globeCenter[0],
            globeCenter[1],
            globeCenter[2]
        ]);
        index.ab.vec3.normalize(normal, normal);
        index.ab.vec3.scale(normal, normal, offsetDistance);
        const cameraPosition = index.ab.vec3.add([], center, normal);
        index.ab.vec3.transformMat4(cameraPosition, cameraPosition, cameraToWorld);
        const meterPerECEF = index.ds / index.ax;
        const altitudeECEF = index.ab.vec3.length(cameraPosition);
        const altitudeMeter = altitudeECEF * meterPerECEF - index.ds;
        const mercatorZ = index.bH(Math.max(altitudeMeter, Number.EPSILON), 0);
        const zoom = Math.min(tr.zoomFromMercatorZAdjusted(mercatorZ), eOptions.maxZoom);
        const halfZoomTransition = (index.c6 + index.bY) * 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
        };
    }
    /**
   * Extends the AABB with padding, offset, and bearing.
   *
   * @param {Aabb} aabb The AABB.
   * @param {Transform} tr The transform.
   * @param {FullCameraOptions} options Camera options.
   * @param {number} bearing The bearing.
   * @returns {Aabb | null} The extended AABB or null if couldn't scale.
   * @private
   */
    _extendAABB(aabb, tr, options, bearing) {
        const padL = options.padding.left || 0;
        const padR = options.padding.right || 0;
        const padB = options.padding.bottom || 0;
        const padT = options.padding.top || 0;
        const halfScreenPadX = (padL + padR) * 0.5;
        const halfScreenPadY = (padT + padB) * 0.5;
        const top = halfScreenPadY;
        const left = halfScreenPadX;
        const right = halfScreenPadX;
        const bottom = halfScreenPadY;
        const width = tr.width - (left + right);
        const height = tr.height - (top + bottom);
        const aabbSize = index.ab.vec3.sub([], aabb.max, aabb.min);
        const scaleX = width / aabbSize[0];
        const scaleY = height / aabbSize[1];
        const scale = Math.min(scaleX, scaleY);
        const zoomRef = Math.min(tr.scaleZoom(tr.scale * scale), options.maxZoom);
        if (isNaN(zoomRef)) {
            return null;
        }
        const scaleRatio = tr.scale / tr.zoomScale(zoomRef);
        const extendedAABB = new index.cd([
            aabb.min[0] - left * scaleRatio,
            aabb.min[1] - bottom * scaleRatio,
            aabb.min[2]
        ], [
            aabb.max[0] + right * scaleRatio,
            aabb.max[1] + top * scaleRatio,
            aabb.max[2]
        ]);
        const centerOffset = typeof options.offset.x === 'number' && typeof options.offset.y === 'number' ? new index.P(options.offset.x, options.offset.y) : index.P.convert(options.offset);
        const rotatedOffset = centerOffset.rotate(-index.ai(bearing));
        extendedAABB.center[0] -= rotatedOffset.x * scaleRatio;
        extendedAABB.center[1] += rotatedOffset.y * scaleRatio;
        return extendedAABB;
    }
    /** @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 = index.l({}, { exaggerated: true }, options);
            return elevation.getAtPoint(index.aa.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 transform The current transform
   * @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);
        tr.bearing = bearing;
        tr.pitch = pitch;
        const coord0 = index.bO.convert(p0);
        const coord1 = index.bO.convert(p1);
        const coord2 = new index.bO(coord0.lng, coord1.lat);
        const coord3 = new index.bO(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 = index.cd.fromPoints(worldCoords);
        const worldToCamera = tr.getWorldToCameraMatrix();
        const cameraToWorld = index.ab.mat4.invert(new Float64Array(16), worldToCamera);
        aabb = index.cd.applyTransform(aabb, worldToCamera);
        const extendedAabb = this._extendAABB(aabb, tr, eOptions, bearing);
        if (!extendedAabb) {
            index.w('Map cannot fit within canvas with the given bounds, padding, and/or offset.');
            return;
        }
        aabb = extendedAabb;
        const size = index.ab.vec3.sub([], aabb.max, aabb.min);
        const aabbHalfExtentZ = size[2] * 0.5;
        const frustumDistance = this._minimumAABBFrustumDistance(tr, aabb);
        const normalZ = [
            0,
            0,
            1,
            0
        ];
        index.ab.vec4.transformMat4(normalZ, normalZ, worldToCamera);
        index.ab.vec4.normalize(normalZ, normalZ);
        const offset = index.ab.vec3.scale([], normalZ, frustumDistance + aabbHalfExtentZ);
        const cameraPosition = index.ab.vec3.add([], aabb.center, offset);
        index.ab.vec3.transformMat4(aabb.center, aabb.center, cameraToWorld);
        index.ab.vec3.transformMat4(cameraPosition, cameraPosition, cameraToWorld);
        const center = tr.unproject(new index.P(aabb.center[0], aabb.center[1]));
        const zoomAdjustment = index.dE(tr.projection, center);
        const scaleAdjustment = Math.pow(2, zoomAdjustment);
        const mercatorZ = cameraPosition[2] * tr.pixelsPerMeter * scaleAdjustment / tr.worldSize;
        const zoom = Math.min(tr._zoomFromMercatorZ(mercatorZ), eOptions.maxZoom);
        const halfZoomTransition = (index.c6 + index.bY) * 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 = index.P.convert(p0);
        const screen1 = index.P.convert(p1);
        const min = new index.P(Math.min(screen0.x, screen1.x), Math.min(screen0.y, screen1.y));
        const max = new index.P(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 index.P(min.x, max.y));
        const lnglat3 = this.transform.pointLocation3D(new index.P(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) {
        if (!calculatedOptions)
            return this;
        options = index.l(calculatedOptions, options);
        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 !== void 0) {
            tr.center = index.bO.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;
        }
        const padding = typeof options.padding === 'number' ? this._extendPadding(options.padding) : options.padding;
        if (options.padding != null && !tr.isPaddingEqual(padding)) {
            if (options.retainPadding === false) {
                const transformForPadding = tr.clone();
                transformForPadding.padding = padding;
                tr.setLocationAtPoint(tr.center, transformForPadding.centerPoint);
            } else {
                tr.padding = padding;
            }
        }
        if (options.preloadOnly) {
            this._preloadTiles(tr);
            return this;
        }
        this.fire(new index.z('movestart', eventData)).fire(new index.z('move', eventData));
        if (zoomChanged) {
            this.fire(new index.z('zoomstart', eventData)).fire(new index.z('zoom', eventData)).fire(new index.z('zoomend', eventData));
        }
        if (bearingChanged) {
            this.fire(new index.z('rotatestart', eventData)).fire(new index.z('rotate', eventData)).fire(new index.z('rotateend', eventData));
        }
        if (pitchChanged) {
            this.fire(new index.z('pitchstart', eventData)).fire(new index.z('pitch', eventData)).fire(new index.z('pitchend', eventData));
        }
        return this.fire(new index.z('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) {
            index.w(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) {
            index.w(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 index.z('movestart', eventData)).fire(new index.z('move', eventData));
        if (zoomChanged) {
            this.fire(new index.z('zoomstart', eventData)).fire(new index.z('zoom', eventData)).fire(new index.z('zoomend', eventData));
        }
        if (bearingChanged) {
            this.fire(new index.z('rotatestart', eventData)).fire(new index.z('rotate', eventData)).fire(new index.z('rotateend', eventData));
        }
        if (pitchChanged) {
            this.fire(new index.z('pitchstart', eventData)).fire(new index.z('pitch', eventData)).fire(new index.z('pitchend', eventData));
        }
        this.fire(new index.z('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 = index.l({
            offset: [
                0,
                0
            ],
            duration: 500,
            easing: index.dA
        }, 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 = this._extendPadding(options.padding);
        const offsetAsPoint = index.P.convert(options.offset);
        let pointAtOffset;
        let from;
        let delta;
        if (tr.projection.name === 'globe') {
            const centerCoord = index.aa.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 = index.bO.convert(options.center || locationAtOffset);
            this._normalizeCenter(center);
            pointAtOffset = tr.centerPoint.add(rotatedOffset);
            from = new index.P(centerCoord.x, centerCoord.y).mult(tr.worldSize);
            delta = new index.P(index.at(center.lng), index.aA(center.lat)).mult(tr.worldSize).sub(from);
        } else {
            pointAtOffset = tr.centerPoint.add(offsetAsPoint);
            const locationAtOffset = tr.pointLocation(pointAtOffset);
            const center = index.bO.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 = index.bO.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 transformForPadding = options.retainPadding === false ? tr.clone() : tr;
        const frame = tr2 => k => {
            if (zoomChanged) {
                tr2.zoom = index.af(startZoom, zoom, k);
            }
            if (bearingChanged) {
                tr2.bearing = index.af(startBearing, bearing, k);
            }
            if (pitchChanged) {
                tr2.pitch = index.af(startPitch, pitch, k);
            }
            if (paddingChanged) {
                transformForPadding.interpolatePadding(startPadding, padding, k);
                pointAtOffset = transformForPadding.centerPoint.add(offsetAsPoint);
            }
            if (around) {
                tr2.setLocationAtPoint(around, aroundPoint);
            } else {
                const scale = tr2.zoomScale(tr2.zoom - startZoom);
                const base = zoom > startZoom ? Math.min(2, finalScale) : Math.max(0.5, finalScale);
                const speedup = Math.pow(base, 1 - k);
                const newCenter = tr2.unproject(from.add(delta.mult(k * speedup)).mult(scale));
                tr2.setLocationAtPoint(tr2.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
            }
            if (!options.preloadOnly) {
                this._fireMoveEvents(eventData);
            }
            return tr2;
        };
        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') {
            this.transform.cameraElevationReference = 'ground';
        }
        if (!noMoveStart && !currently.moving) {
            this.fire(new index.z('movestart', eventData));
        }
        if (this._zooming && !currently.zooming) {
            this.fire(new index.z('zoomstart', eventData));
        }
        if (this._rotating && !currently.rotating) {
            this.fire(new index.z('rotatestart', eventData));
        }
        if (this._pitching && !currently.pitching) {
            this.fire(new index.z('pitchstart', eventData));
        }
    }
    _fireMoveEvents(eventData) {
        this.fire(new index.z('move', eventData));
        if (this._zooming) {
            this.fire(new index.z('zoom', eventData));
        }
        if (this._rotating) {
            this.fire(new index.z('rotate', eventData));
        }
        if (this._pitching) {
            this.fire(new index.z('pitch', eventData));
        }
    }
    _afterEase(eventData, easeId) {
        if (this._easeId && easeId && this._easeId === easeId) {
            return;
        }
        this._easeId = void 0;
        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 index.z('zoomend', eventData));
        }
        if (wasRotating) {
            this.fire(new index.z('rotateend', eventData));
        }
        if (wasPitching) {
            this.fire(new index.z('pitchend', eventData));
        }
        this.fire(new index.z('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) {
        if (this._prefersReducedMotion(options)) {
            const coercedOptions = index.ay(options, [
                'center',
                'zoom',
                'bearing',
                'pitch',
                'around',
                'padding',
                'retainPadding'
            ]);
            return this.jumpTo(coercedOptions, eventData);
        }
        this.stop();
        options = index.l({
            offset: [
                0,
                0
            ],
            speed: 1.2,
            curve: 1.42,
            easing: index.dA
        }, options);
        const tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding();
        const zoom = 'zoom' in options ? index.aw(+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 = this._extendPadding(options.padding);
        const scale = tr.zoomScale(zoom - startZoom);
        const offsetAsPoint = index.P.convert(options.offset);
        let pointAtOffset = tr.centerPoint.add(offsetAsPoint);
        const locationAtOffset = tr.pointLocation(pointAtOffset);
        const center = index.bO.convert(options.center || locationAtOffset);
        this._normalizeCenter(center);
        const from = tr.project(locationAtOffset);
        const delta = tr.project(center).sub(from);
        let rho = options.curve;
        const w0 = Math.max(tr.width, tr.height), w1 = w0 / scale, u1 = delta.mag();
        if ('minZoom' in options) {
            const minZoom = index.aw(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom);
            const wMax = w0 / tr.zoomScale(minZoom - startZoom);
            rho = Math.sqrt(wMax / u1 * 2);
        }
        const rho2 = rho * rho;
        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);
        }
        const r0 = r(0);
        let w = function (s) {
            return cosh(r0) / cosh(r0 + rho * s);
        };
        let u = function (s) {
            return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1;
        };
        let S = (r(1) - r0) / rho;
        if (Math.abs(u1) < 0.000001 || !isFinite(S)) {
            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 transformForPadding = options.retainPadding === false ? tr.clone() : tr;
        const frame = tr2 => k => {
            const s = k * S;
            const scale2 = 1 / w(s);
            tr2.zoom = k === 1 ? zoom : startZoom + tr2.scaleZoom(scale2);
            if (bearingChanged) {
                tr2.bearing = index.af(startBearing, bearing, k);
            }
            if (pitchChanged) {
                tr2.pitch = index.af(startPitch, pitch, k);
            }
            if (paddingChanged) {
                transformForPadding.interpolatePadding(startPadding, padding, k);
                pointAtOffset = transformForPadding.centerPoint.add(offsetAsPoint);
            }
            const newCenter = k === 1 ? center : tr2.unproject(from.add(delta.mult(u(s))).mult(scale2));
            tr2.setLocationAtPoint(tr2.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
            tr2._updateCameraOnTerrain();
            if (!options.preloadOnly) {
                this._fireMoveEvents(eventData);
            }
            return tr2;
        };
        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();
    }
    // @ts-expect-error - No-op in the Camera class, implemented by the Map class
    _requestRenderFrame(_callback) {
    }
    // No-op in the Camera class, implemented by the Map class
    _cancelRenderFrame(_) {
    }
    _stop(allowGestures, easeId) {
        if (this._easeFrameId) {
            this._cancelRenderFrame(this._easeFrameId);
            this._easeFrameId = void 0;
            this._onEaseFrame = void 0;
        }
        if (this._onEaseEnd) {
            const onEaseEnd = this._onEaseEnd;
            this._onEaseEnd = void 0;
            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 = index.q.now();
            this._easeOptions = options;
            this._onEaseFrame = frame;
            this._onEaseEnd = finish;
            this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
        }
    }
    // Callback for map._requestRenderFrame
    _renderFrameCallback() {
        const t = Math.min((index.q.now() - this._easeStart) / this._easeOptions.duration, 1);
        const frame = this._onEaseFrame;
        if (frame)
            frame(this._easeOptions.easing(t));
        if (t < 1) {
            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 = index.bF(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.maxBounds)
            return;
        const isGlobe = tr.projection.name === 'globe';
        if (!isGlobe && !tr.renderWorldCopies)
            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 && index.q.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;
    }
    // No-op in the Camera class, implemented by the Map class
    _preloadTiles(_transform, _callback) {
    }
}

class AttributionControl {
    constructor(options = {}) {
        this.options = options;
        index.aP([
            '_toggleAttribution',
            '_updateEditLink',
            '_updateData',
            '_updateCompact'
        ], this);
    }
    getDefaultPosition() {
        return 'bottom-right';
    }
    onAdd(map) {
        const compact = this.options && this.options.compact;
        const title = map._getUIString('AttributionControl.ToggleAttribution');
        this._map = map;
        this._container = create$1('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib');
        this._compactButton = create$1('button', 'mapboxgl-ctrl-attrib-button', this._container);
        this._compactButton.type = 'button';
        this._compactButton.addEventListener('click', this._toggleAttribution);
        this._compactButton.setAttribute('aria-label', title);
        const buttonIcon = create$1('span', `mapboxgl-ctrl-icon`, this._compactButton);
        buttonIcon.setAttribute('aria-hidden', 'true');
        buttonIcon.setAttribute('title', title);
        this._innerContainer = create$1('div', 'mapboxgl-ctrl-attrib-inner', this._container);
        if (compact) {
            this._container.classList.add('mapboxgl-compact');
        }
        this._updateAttributions();
        this._updateEditLink();
        this._map.on('styledata', this._updateData);
        this._map.on('sourcedata', this._updateData);
        this._map.on('moveend', this._updateEditLink);
        if (compact === void 0) {
            this._map.on('resize', this._updateCompact);
            this._updateCompact();
        }
        return this._container;
    }
    onRemove() {
        this._container.remove();
        this._map.off('styledata', this._updateData);
        this._map.off('sourcedata', this._updateData);
        this._map.off('moveend', this._updateEditLink);
        this._map.off('resize', this._updateCompact);
        this._map = void 0;
        this._attribHTML = void 0;
    }
    _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 || index.e.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 = `${ index.e.FEEDBACK_URL }/${ paramString }#${ getHashString(this._map, true) }`;
            editLink.rel = 'noopener nofollow';
        }
    }
    _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) {
                    attributions.push(source.attribution);
                }
            }
        }
        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);
            }
        }
        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');
        }
        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');
        }
    }
}

class LogoControl {
    constructor() {
        index.aP([
            '_updateLogo',
            '_updateCompact'
        ], this);
    }
    onAdd(map) {
        this._map = map;
        this._container = create$1('div', 'mapboxgl-ctrl');
        const anchor = create$1('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';
        this._map.on('sourcedata', this._updateLogo);
        this._updateLogo();
        this._map.on('resize', this._updateCompact);
        this._updateCompact();
        return this._container;
    }
    onRemove() {
        this._container.remove();
        this._map.off('sourcedata', this._updateLogo);
        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');
            }
        }
    }
}

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;
        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 = [];
    }
}

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 = index.cB((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',
    'FullscreenControl.Enter': 'Enter fullscreen',
    'FullscreenControl.Exit': 'Exit fullscreen',
    'GeolocateControl.FindMyLocation': 'Find my location',
    'GeolocateControl.LocationNotAvailable': 'Location not available',
    'LogoControl.Title': 'Mapbox homepage',
    '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'
};

class InteractionEvent extends index.z {
    /**
   * @private
   */
    constructor(e, id, interaction, feature) {
        const {point, lngLat, originalEvent, target} = e;
        super(e.type, {
            point,
            lngLat,
            originalEvent,
            target
        });
        this.preventDefault = () => {
            e.preventDefault();
        };
        this.id = id;
        this.interaction = interaction;
        this.feature = feature;
    }
}
class InteractionSet {
    constructor(map) {
        this.map = map;
        this.interactionsByType = /* @__PURE__ */
        new Map();
        this.delegatedInteractions = /* @__PURE__ */
        new Map();
        this.typeById = /* @__PURE__ */
        new Map();
        this.filters = /* @__PURE__ */
        new Map();
        this.handleType = this.handleType.bind(this);
        this.handleMove = this.handleMove.bind(this);
        this.handleOut = this.handleOut.bind(this);
        this.hoveredFeatures = /* @__PURE__ */
        new Map();
        this.prevHoveredFeatures = /* @__PURE__ */
        new Map();
    }
    add(id, interaction) {
        if (this.typeById.has(id)) {
            throw new Error(`Interaction id "${ id }" already exists.`);
        }
        const filter = interaction.filter;
        let type = interaction.type;
        if (filter) {
            this.filters.set(id, index.aZ(filter));
        }
        if (type === 'mouseover')
            type = 'mouseenter';
        if (type === 'mouseout')
            type = 'mouseleave';
        const interactions = this.interactionsByType.get(type) || /* @__PURE__ */
        new Map();
        if (type === 'mouseenter' || type === 'mouseleave') {
            if (this.delegatedInteractions.size === 0) {
                this.map.on('mousemove', this.handleMove);
                this.map.on('mouseout', this.handleOut);
            }
            this.delegatedInteractions.set(id, interaction);
        } else if (interactions.size === 0) {
            this.map.on(type, this.handleType);
        }
        if (interactions.size === 0) {
            this.interactionsByType.set(type, interactions);
        }
        interactions.set(id, interaction);
        this.typeById.set(id, type);
    }
    get(id) {
        const type = this.typeById.get(id);
        if (!type)
            return;
        const interactions = this.interactionsByType.get(type);
        if (!interactions)
            return;
        return interactions.get(id);
    }
    remove(id) {
        const type = this.typeById.get(id);
        if (!type)
            return;
        this.typeById.delete(id);
        this.filters.delete(id);
        const interactions = this.interactionsByType.get(type);
        if (!interactions)
            return;
        interactions.delete(id);
        if (type === 'mouseenter' || type === 'mouseleave') {
            this.delegatedInteractions.delete(id);
            if (this.delegatedInteractions.size === 0) {
                this.map.off('mousemove', this.handleMove);
                this.map.off('mouseout', this.handleOut);
            }
        } else if (interactions.size === 0) {
            this.map.off(type, this.handleType);
        }
    }
    queryTargets(point, interactions) {
        const targets = [];
        for (const [targetId, interaction] of interactions) {
            if (interaction.target) {
                targets.push({
                    targetId,
                    target: interaction.target,
                    filter: this.filters.get(targetId)
                });
            }
        }
        return this.map.style.queryRenderedTargets(point, targets, this.map.transform);
    }
    handleMove(event) {
        this.prevHoveredFeatures = this.hoveredFeatures;
        this.hoveredFeatures = /* @__PURE__ */
        new Map();
        const features = this.queryTargets(event.point, Array.from(this.delegatedInteractions).reverse());
        if (features.length) {
            event.type = 'mouseenter';
            this.handleType(event, features);
        }
        const featuresLeaving = /* @__PURE__ */
        new Map();
        for (const [id, {feature}] of this.prevHoveredFeatures) {
            if (!this.hoveredFeatures.has(id)) {
                featuresLeaving.set(feature.id, feature);
            }
        }
        if (featuresLeaving.size) {
            event.type = 'mouseleave';
            this.handleType(event, Array.from(featuresLeaving.values()));
        }
    }
    handleOut(event) {
        const featuresLeaving = Array.from(this.hoveredFeatures.values()).map(({feature}) => feature);
        if (featuresLeaving.length) {
            event.type = 'mouseleave';
            this.handleType(event, featuresLeaving);
        }
        this.hoveredFeatures.clear();
    }
    handleType(event, features) {
        const interactions = Array.from(this.interactionsByType.get(event.type)).reverse();
        const delegated = !!features;
        features = features || this.queryTargets(event.point, interactions);
        const isMouseEnter = event.type === 'mouseenter';
        let eventHandled = false;
        const uniqueFeatureSet = /* @__PURE__ */
        new Set();
        for (const feature of features) {
            for (const [id, interaction] of interactions) {
                if (!interaction.target)
                    continue;
                const variants = feature.variants ? feature.variants[id] : null;
                if (!variants)
                    continue;
                for (const variant of variants) {
                    if (shouldSkipFeatureVariant(variant, feature, uniqueFeatureSet, id)) {
                        continue;
                    }
                    const targetFeature = new index.cw(feature, variant);
                    const targetFeatureId = getFeatureTargetKey(variant, feature, id);
                    if (delegated)
                        targetFeature.state = this.map.getFeatureState(targetFeature);
                    const hovered = isMouseEnter ? this.prevHoveredFeatures.get(targetFeatureId) : null;
                    const interactionEvent = new InteractionEvent(event, id, interaction, targetFeature);
                    const stop = hovered ? hovered.stop : interaction.handler(interactionEvent);
                    if (isMouseEnter) {
                        this.hoveredFeatures.set(targetFeatureId, {
                            feature,
                            stop
                        });
                    }
                    if (stop !== false) {
                        eventHandled = true;
                        break;
                    }
                }
                if (eventHandled)
                    break;
            }
            if (eventHandled)
                break;
        }
        if (eventHandled)
            return;
        for (const [id, interaction] of interactions) {
            const {handler, target} = interaction;
            if (target)
                continue;
            const stop = handler(new InteractionEvent(event, id, interaction, null));
            if (stop !== false) {
                break;
            }
        }
    }
}

const AVERAGE_ELEVATION_SAMPLING_INTERVAL = 500;
const AVERAGE_ELEVATION_EASE_TIME = 300;
const AVERAGE_ELEVATION_EASE_THRESHOLD = 1;
const AVERAGE_ELEVATION_CHANGE_THRESHOLD = 0.0001;
function areTargetsEqual(a, b) {
    if (Array.isArray(a) && Array.isArray(b)) {
        const aSet = new Set(a);
        const bSet = new Set(b);
        return aSet.size === bSet.size && a.every(id => bSet.has(id));
    } else {
        return index.bn(a, b);
    }
}
const defaultMinZoom = -2;
const defaultMaxZoom = 22;
const defaultMinPitch = 0;
const defaultMaxPitch = 85;
const defaultOptions$4 = {
    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,
    precompilePrograms: true,
    scaleFactor: 1,
    spriteFormat: 'auto'
};
let Map$1 = class Map extends Camera {
    constructor(options) {
        LivePerformanceUtils.mark(LivePerformanceMarkers.create);
        const initialOptions = options;
        options = index.l({}, defaultOptions$4, 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 }`);
        }
        if (options.antialias && index.dF(window)) {
            options.antialias = false;
            index.w('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._repaint = !!options.repaint;
        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 = index.aV();
        this._locale = index.l({}, defaultLocale, options.locale);
        this._clickTolerance = options.clickTolerance;
        this._cooperativeGestures = options.cooperativeGestures;
        this._performanceMetricsCollection = options.performanceMetricsCollection;
        this._tessellationStep = options.tessellationStep;
        this._containerWidth = 0;
        this._containerHeight = 0;
        this._showParseStatus = true;
        this._precompilePrograms = options.precompilePrograms;
        this._scaleFactorChanged = false;
        this._averageElevationLastSampledAt = -Infinity;
        this._averageElevationExaggeration = 0;
        this._averageElevation = new EasedVariable(0);
        this._interactionRange = [
            Infinity,
            -Infinity
        ];
        this._visibilityHidden = 0;
        this._useExplicitProjection = false;
        this._frameId = 0;
        this._scaleFactor = options.scaleFactor;
        this._requestManager = new RequestManager(options.transformRequest, options.accessToken, options.testMode);
        this._silenceAuthErrors = !!options.testMode;
        if (options.contextCreateOptions) {
            this._contextCreateOptions = Object.assign({}, options.contextCreateOptions);
        } else {
            this._contextCreateOptions = {};
        }
        if (typeof options.container === 'string') {
            const container = document.getElementById(options.container);
            if (container) {
                this._container = container;
            } else {
                throw new Error(`Container '${ options.container.toString() }' not found.`);
            }
        } else if (options.container instanceof HTMLElement) {
            this._container = options.container;
        } else {
            throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);
        }
        if (this._container.childNodes.length > 0) {
            index.w(`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);
        }
        this._spriteFormat = options.spriteFormat;
        index.aP([
            '_onWindowOnline',
            '_onWindowResize',
            '_onVisibilityChange',
            '_onMapScroll',
            '_contextLost',
            '_contextRestored'
        ], this);
        this._setupContainer();
        if (!this._tp) {
            this._tp = new TrackedParametersMock();
        }
        this._tp.registerParameter(this, ['Debug'], 'showOverdrawInspector');
        this._tp.registerParameter(this, ['Debug'], 'showTileBoundaries');
        this._tp.registerParameter(this, ['Debug'], 'showParseStatus');
        this._tp.registerParameter(this, ['Debug'], 'repaint');
        this._tp.registerParameter(this, ['Debug'], 'showTileAABBs');
        this._tp.registerParameter(this, ['Debug'], 'showPadding');
        this._tp.registerParameter(this, ['Debug'], 'showCollisionBoxes', { noSave: true });
        this._tp.registerParameter(this.transform, ['Debug'], 'freezeTileCoverage', { noSave: true }, () => {
            this._update();
        });
        this._tp.registerParameter(this, [
            'Debug',
            'Wireframe'
        ], 'showTerrainWireframe');
        this._tp.registerParameter(this, [
            'Debug',
            'Wireframe'
        ], 'showLayers2DWireframe');
        this._tp.registerParameter(this, [
            'Debug',
            'Wireframe'
        ], 'showLayers3DWireframe');
        this._tp.registerParameter(this, ['Scaling'], '_scaleFactor', {
            min: 0.1,
            max: 10,
            step: 0.1
        }, () => {
            this.setScaleFactor(this._scaleFactor);
        });
        this._setupPainter();
        if (this.painter === void 0) {
            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));
        this._fullscreenchangeEvent = 'onfullscreenchange' in document ? 'fullscreenchange' : 'webkitfullscreenchange';
        window.addEventListener('online', this._onWindowOnline, false);
        window.addEventListener('resize', this._onWindowResize, false);
        window.addEventListener('orientationchange', this._onWindowResize, false);
        window.addEventListener(this._fullscreenchangeEvent, this._onWindowResize, false);
        window.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 || index.e.DEFAULT_STYLE;
            this.setStyle(style, {
                config: options.config,
                localFontFamily: this._localFontFamily,
                localIdeographFontFamily: this._localIdeographFontFamily
            });
        }
        if (options.projection) {
            this.setProjection(options.projection);
        }
        this.indoor = new IndoorManager(this);
        const hashName = typeof options.hash === 'string' && options.hash || void 0;
        if (options.hash)
            this._hash = new Hash(hashName).addTo(this);
        if (!this._hash || !this._hash._onHashChange()) {
            if (initialOptions.center != null || initialOptions.zoom != null) {
                this.transform._unmodified = false;
            }
            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, index.l({}, options.fitBoundsOptions, { duration: 0 }));
            }
        }
        this.resize();
        if (options.attributionControl)
            this.addControl(new AttributionControl({ customAttribution: options.customAttribution }));
        this._logoControl = new LogoControl();
        this.addControl(this._logoControl, options.logoPosition);
        this.on('style.load', () => {
            if (this.transform.unmodified) {
                this.jumpTo(this.style.stylesheet);
            }
            this._postStyleLoadEvent();
        });
        this.on('data', event => {
            this._update(event.dataType === 'style');
            this.fire(new index.z(`${ event.dataType }data`, event));
        });
        this.on('dataloading', event => {
            this.fire(new index.z(`${ event.dataType }dataloading`, event));
        });
        this._interactions = new InteractionSet(this);
    }
    /*
  * 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'`, `'top-right'`, `'right'`, `'bottom-right'`,
   * `'bottom'`, `'bottom-left'`, and `'left'`. 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 === void 0) {
            if (control.getDefaultPosition) {
                position = control.getDefaultPosition();
            } else {
                position = 'top-right';
            }
        }
        if (!control || !control.onAdd) {
            return this.fire(new index.y(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 index.y(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();
        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 index.z('movestart', eventData)).fire(new index.z('move', eventData));
        }
        this.fire(new index.z('resize', eventData));
        if (fireMoving)
            this.fire(new index.z('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(index.az.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 === void 0 ? 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 index.z('zoomstart')).fire(new index.z('zoom')).fire(new index.z('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 === void 0 ? defaultMaxZoom : maxZoom;
        if (maxZoom >= this.transform.minZoom) {
            this.transform.maxZoom = maxZoom;
            this._update();
            if (this.getZoom() > maxZoom) {
                this.setZoom(maxZoom);
            } else {
                this.fire(new index.z('zoomstart')).fire(new index.z('zoom')).fire(new index.z('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 === void 0 ? 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 index.z('pitchstart')).fire(new index.z('pitch')).fire(new index.z('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 === void 0 ? 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 index.z('pitchstart')).fire(new index.z('pitch')).fire(new index.z('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 map's current scale factor.
   *
   * @returns {number} Returns the map's scale factor.
   * @private
   *
   * @example
   * const scaleFactor = map.getScaleFactor();
   */
    getScaleFactor() {
        return this._scaleFactor;
    }
    /**
   * Sets the map's scale factor.
   *
   * @param {number} scaleFactor The scale factor to set.
   * @returns {Map} Returns itself to allow for method chaining.
   * @private
   *
   * @example
   *
   * map.setScaleFactor(2);
   */
    setScaleFactor(scaleFactor) {
        this._scaleFactor = scaleFactor;
        this.painter.scaleFactor = scaleFactor;
        this._tp.refreshUI();
        this._scaleFactorChanged = true;
        this.style._updateFilteredLayers(layer => layer.type === 'symbol');
        this._update(true);
        return this;
    }
    /**
   * 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 navigator.language;
        if (Array.isArray(language))
            return language.length === 0 ? void 0 : language.map(l => l === 'auto' ? 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.reloadSources();
        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.reloadSources();
        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() {
        if (this.getProjection().name !== 'globe') {
            return;
        }
        const tr = this.transform;
        const projection = tr.projection.name;
        let projectionHasChanged;
        if (projection === 'globe' && tr.zoom >= index.bY) {
            tr.setMercatorFromTransition();
            projectionHasChanged = true;
        } else if (projection === 'mercator' && tr.zoom < index.bY) {
            tr.setProjection({ name: 'globe' });
            projectionHasChanged = true;
        }
        if (projectionHasChanged) {
            this.style.applyProjectionUpdate();
            this.style._forceSymbolLayerUpdate();
        }
    }
    _prioritizeAndUpdateProjection(explicitProjection, styleProjection) {
        const prioritizedProjection = explicitProjection || styleProjection || { name: 'mercator' };
        return this._updateProjection(prioritizedProjection);
    }
    _updateProjection(projection) {
        let projectionHasChanged;
        if (projection.name === 'globe' && this.transform.zoom >= index.bY) {
            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(index.bO.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(index.P.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, targets, listener) {
        const queryRenderedFeatures = point => {
            let features = [];
            if (Array.isArray(targets)) {
                const filteredLayers = targets.filter(layerId => this.getLayer(layerId));
                features = filteredLayers.length ? this.queryRenderedFeatures(point, { layers: filteredLayers }) : [];
            } else {
                features = this.queryRenderedFeatures(point, { target: targets });
            }
            return features;
        };
        if (type === 'mouseenter' || type === 'mouseover') {
            let mousein = false;
            const mousemove = e => {
                const features = queryRenderedFeatures(e.point);
                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 {
                listener,
                targets,
                delegates: {
                    mousemove,
                    mouseout
                }
            };
        } else if (type === 'mouseleave' || type === 'mouseout') {
            let mousein = false;
            const mousemove = e => {
                const features = queryRenderedFeatures(e.point);
                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 {
                listener,
                targets,
                delegates: {
                    mousemove,
                    mouseout
                }
            };
        } else {
            const delegate = e => {
                const features = queryRenderedFeatures(e.point);
                if (features.length) {
                    e.features = features;
                    listener.call(this, e);
                    delete e.features;
                }
            };
            return {
                listener,
                targets,
                delegates: { [type]: delegate }
            };
        }
    }
    on(type, targets, listener) {
        if (typeof targets === 'function' || listener === void 0) {
            return super.on(type, targets);
        }
        if (typeof targets === 'string')
            targets = [targets];
        if (!this._areTargetsValid(targets)) {
            return this;
        }
        const delegatedListener = this._createDelegatedListener(type, targets, 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;
    }
    once(type, targets, listener) {
        if (typeof targets === 'function' || listener === void 0) {
            return super.once(type, targets);
        }
        if (typeof targets === 'string')
            targets = [targets];
        if (!this._areTargetsValid(targets)) {
            return this;
        }
        const delegatedListener = this._createDelegatedListener(type, targets, listener);
        for (const event in delegatedListener.delegates) {
            this.once(event, delegatedListener.delegates[event]);
        }
        return this;
    }
    off(type, targets, listener) {
        if (typeof targets === 'function' || listener === void 0) {
            return super.off(type, targets);
        }
        if (typeof targets === 'string')
            targets = [targets];
        if (!this._areTargetsValid(targets)) {
            return this;
        }
        const removeDelegatedListeners = listeners => {
            for (let i = 0; i < listeners.length; i++) {
                const delegatedListener = listeners[i];
                if (delegatedListener.listener === listener && areTargetsEqual(delegatedListener.targets, targets)) {
                    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] : void 0;
        if (delegatedListeners) {
            removeDelegatedListeners(delegatedListeners);
        }
        return this;
    }
    queryRenderedFeatures(geometry, options) {
        if (!this.style) {
            return [];
        }
        if (geometry !== void 0 && !(geometry instanceof index.P) && !Array.isArray(geometry) && options === void 0) {
            options = geometry;
            geometry = void 0;
        }
        geometry = geometry || [
            [
                0,
                0
            ],
            [
                this.transform.width,
                this.transform.height
            ]
        ];
        if (!options) {
            const features2 = this.style.queryRenderedFeatures(geometry, void 0, this.transform);
            const targetFeatures = this.style.queryRenderedFeatureset(geometry, void 0, this.transform);
            return features2.concat(targetFeatures);
        }
        let featuresetIsValid = true;
        if (options.target) {
            featuresetIsValid = this._isTargetValid(options.target);
            if (featuresetIsValid && !options.layers) {
                return this.style.queryRenderedFeatureset(geometry, options, this.transform);
            }
        }
        let layersAreValid = true;
        if (options.layers && Array.isArray(options.layers)) {
            for (const layerId of options.layers) {
                if (!this._isValidId(layerId)) {
                    layersAreValid = false;
                    break;
                }
            }
            if (layersAreValid && !options.target) {
                return this.style.queryRenderedFeatures(geometry, options, this.transform);
            }
        }
        let features = [];
        if (layersAreValid) {
            features = features.concat(this.style.queryRenderedFeatures(geometry, options, this.transform));
        }
        if (featuresetIsValid) {
            features = features.concat(this.style.queryRenderedFeatureset(geometry, options, this.transform));
        }
        return features;
    }
    /**
   * 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 (!sourceId || typeof sourceId === 'string' && !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') {
            index.w(`${ name } projection does not support isPointOnSurface, this API may behave unexpectedly.`);
        }
        return this.transform.isPointOnSurface(index.P.convert(point));
    }
    /**
   * Add an interaction — a named gesture handler of a given type.
   * *This API is experimental and subject to change in future versions*.
   *
   * @experimental
   * @param {string} id The ID of the interaction.
   * @param {Object} interaction The interaction object with the following properties.
   * @param {string} interaction.type The type of gesture to handle (e.g. 'click').
   * @param {Object} [interaction.filter] Filter expression to narrow down the interaction to a subset of features under the pointer.
   * @param {TargetDescriptor} [interaction.target] The interaction target, which can be either a reference to a layer or a reference to a featureset in a style import.
   * Use `{layerId: string}` to reference features in the root style layer, or `{featuresetId: string, importId?: string}` to reference features in an imported style.
   * @param {Function} interaction.handler A handler function that will be invoked on the gesture and receive a `{feature, interaction}` object as a parameter.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * map.addInteraction('poi-click', {
   *   type: 'click',
   *   target: {featuresetId: 'poi', importId: 'basemap'},
   *   handler(e) {
   *     console.log(e.feature);
   *   }
   * });
   *
   * @example
   * map.addInteraction('building-mouseenter', {
   *   type: 'mouseenter',
   *   target: {featuresetId: 'buildings', importId: 'basemap'},
   *   handler: (e) => {
   *     map.setFeatureState(e.feature, {highlight: true});
   *   }
   * });
   *
   * @example
   * map.addInteraction('building-mouseleave', {
   *   type: 'mouseleave',
   *   target: {featuresetId: 'buildings', importId: 'basemap'},
   *   handler: (e) => {
   *     map.setFeatureState(e.feature, {highlight: true});
   *     // Propagate the event so that the handler is called for each feature.
   *     return false;
   *   }
   * });
   */
    addInteraction(id, interaction) {
        this._interactions.add(id, interaction);
        return this;
    }
    /**
   * Remove an interaction previously added with `addInteraction`.
   * *This API is experimental and subject to change in future versions*.
   *
   * @experimental
   * @param {string} id The id of the interaction to remove.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * map.removeInteraction('poi-click');
   */
    removeInteraction(id) {
        this._interactions.remove(id);
        return this;
    }
    /** @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.
   * @param {Object} [options.config=null] The initial configuration options for the style fragments.
   * Each key in the object is a fragment ID (e.g., `basemap`) and each value is a configuration object.
   * @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/)
   *
   * @example
   * map.setStyle("mapbox://styles/mapbox/standard", {
   *     "config": {
   *         "basemap": {
   *             "lightPreset": "night"
   *         }
   *     }
   * });
   */
    setStyle(style, options) {
        options = index.l({}, {
            localIdeographFontFamily: this._localIdeographFontFamily,
            localFontFamily: this._localFontFamily
        }, options);
        const diffNeeded = options.diff !== false && options.localFontFamily === this._localFontFamily && options.localIdeographFontFamily === this._localIdeographFontFamily && !options.config;
        if (this.style && style && diffNeeded) {
            this.style._diffStyle(style, (e, isUpdateNeeded) => {
                if (e) {
                    index.w(`Unable to perform style diff: ${ String(e.message || e.error || e) }. Rebuilding the style from scratch.`);
                    this._updateStyle(style, options);
                } else if (isUpdateNeeded) {
                    this._update(true);
                }
            }, () => {
                this._postStyleLoadEvent();
            });
            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 = void 0;
        }
        if (style) {
            const styleOptions = index.l({}, options);
            if (options && options.config) {
                styleOptions.initialConfig = options.config;
                delete styleOptions.config;
            }
            this.style = new Style(this, styleOptions).load(style);
            this.style.setEventedParent(this, { style: this.style });
        }
        this._updateTerrain();
        return this;
    }
    _lazyInitEmptyStyle() {
        if (!this.style) {
            this.style = new Style(this, {});
            this.style.setEventedParent(this, { style: this.style });
            this.style.loadEmpty();
        }
    }
    /**
   * 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.
   *
   * For the Mapbox Standard style or any "fragment" style (which is a style with `fragment: true`
   * or a `schema` property defined), this method returns an empty style with no layers or sources.
   * The original style is wrapped into an import with the ID `basemap` as a fragment style and is not intended
   * to be used directly. This design ensures that user logic is not tied to style internals, allowing Mapbox
   * to roll out style updates seamlessly and consistently.
   *
   * @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) {
            index.w('There is no style added to the map.');
            return false;
        }
        return this.style.loaded();
    }
    _isValidId(id) {
        if (id == null) {
            this.fire(new index.y(new Error(`IDs can't be empty.`)));
            return false;
        }
        if (index.cr(id)) {
            this.fire(new index.y(new Error(`IDs can't contain special symbols: "${ id }".`)));
            return false;
        }
        return true;
    }
    /**
   * Checks if the given target is a valid featureset descriptor.
   * @private
   */
    _isTargetValid(target) {
        if ('featuresetId' in target) {
            if ('importId' in target)
                return this._isValidId(target.importId);
            return this._isValidId(target.featuresetId);
        }
        if ('layerId' in target) {
            return this._isValidId(target.layerId);
        }
        return false;
    }
    /**
   * Checks if the given targets are either list of valid layerIds or a valid featureset descriptor.
   * @private
   */
    _areTargetsValid(targets) {
        if (Array.isArray(targets)) {
            for (const layerId of targets) {
                if (!this._isValidId(layerId)) {
                    return false;
                }
            }
            return true;
        }
        return this._isTargetValid(targets);
    }
    /** @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() {
        return this.style.areTilesLoaded();
    }
    /**
   * 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 version2 = 0;
        if (image instanceof HTMLImageElement || ImageBitmap && image instanceof ImageBitmap) {
            const {width, height, data} = index.q.getImageData(image);
            this.style.addImage(id, {
                data: new index.r({
                    width,
                    height
                }, data),
                pixelRatio,
                stretchX,
                stretchY,
                content,
                sdf,
                version: version2,
                usvg: false
            });
        } else if (image.width === void 0 || image.height === void 0) {
            this.fire(new index.y(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 index.r({
                    width,
                    height
                }, new Uint8Array(data)),
                pixelRatio,
                stretchX,
                stretchY,
                content,
                sdf,
                usvg: false,
                version: version2,
                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 index.y(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 HTMLImageElement || ImageBitmap && image instanceof ImageBitmap ? index.q.getImageData(image) : image;
        const {width, height, data} = imageData;
        if (width === void 0 || height === void 0) {
            this.fire(new index.y(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;
        }
        const existingImageWidth = existingImage.usvg ? existingImage.icon.usvg_tree.width : existingImage.data.width;
        const existingImageHeight = existingImage.usvg ? existingImage.icon.usvg_tree.height : existingImage.data.height;
        if (width !== existingImageWidth || height !== existingImageHeight) {
            this.fire(new index.y(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 HTMLImageElement || ImageBitmap && image instanceof ImageBitmap);
        let performSymbolLayout = false;
        if (existingImage.usvg) {
            existingImage.data = new index.r({
                width,
                height
            }, new Uint8Array(data));
            existingImage.usvg = false;
            existingImage.icon = void 0;
            performSymbolLayout = true;
        } else {
            existingImage.data.replace(data, copy);
        }
        this.style.updateImage(id, existingImage, performSymbolLayout);
    }
    /**
   * 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 index.y(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) {
        index.o(this._requestManager.transformRequest(url, index.R.Image), (err, img) => {
            callback(err, img instanceof HTMLImageElement ? index.q.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 index.y(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 {string} [layer.slot] (optional) The identifier of a [`slot`](https://docs.mapbox.com/style-spec/reference/slots/) layer that will be used to position this style layer.
   * A `slot` layer serves as a predefined position in the layer order for inserting associated layers.
   * *Note*: During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance.
   * This process might lead to a rearrangement of layers. Layers draped over globe and terrain,
   * such as `fill`, `line`, `background`, `hillshade`, and `raster`, are rendered first.
   * These layers are rendered underneath symbols, regardless of whether they are placed
   * in the middle or top slots or without a designated slot.
   * @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.
   * *Note*: Layers can only be rearranged within the same `slot`. The new layer must share the
   * same `slot` as the existing layer to be positioned underneath it. If the
   * layers are in different slots, the `beforeId` parameter will be ignored and
   * the new layer will be appended to the end of the layers array.
   * During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance.
   * This process might lead to a rearrangement of layers. Layers draped over globe and terrain,
   * such as `fill`, `line`, `background`, `hillshade`, and `raster`, are rendered first.
   * These layers are rendered underneath symbols, regardless of whether they are placed
   * in the middle or top slots or without a designated slot.
   *
   * @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 to a slot
   * map.addLayer({
   *     id: 'states',
   *     // References a source that's already been defined
   *     source: 'state-data',
   *     type: 'symbol',
   *     // Add the layer to the existing `top` slot
   *     slot: 'top',
   *     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);
    }
    /**
   * Returns current slot of the layer.
   *
   * @param {string} layerId Identifier of the layer to retrieve its current slot.
   * @returns {string | null} The slot identifier or `null` if layer doesn't have it.
   *
   * @example
   * map.getSlot('roads');
   */
    getSlot(layerId) {
        const layer = this.getLayer(layerId);
        if (!layer) {
            return null;
        }
        return layer.slot || null;
    }
    /**
   * Sets or removes [a slot](https://docs.mapbox.com/style-spec/reference/slots/) of style layer.
   *
   * @param {string} layerId Identifier of style layer.
   * @param {string} slot Identifier of slot. If `null` or `undefined` is provided, the method removes slot.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * // Sets new slot for style layer
   * map.setSlot("heatmap", "top");
   */
    setSlot(layerId, slot) {
        this.style.setSlot(layerId, slot);
        this.style.mergeLayers();
        return this._update(true);
    }
    /**
   * Adds new [import](https://docs.mapbox.com/style-spec/reference/imports/) to current style.
   *
   * @param {ImportSpecification} importSpecification Specification of import.
   * @param {string} beforeId (optional) Identifier of an existing import to insert the new import before.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * // Add streets style to empty map
   * new Map({style: {version: 8, sources: {}, layers: []}})
   *     .addImport({id: 'basemap', url: 'mapbox://styles/mapbox/streets-v12'});
   *
   * @example
   * // Add new style before already added
   * const map = new Map({
   *     imports: [
   *         {
   *             id: 'basemap',
   *             url: 'mapbox://styles/mapbox/standard'
   *         }
   *     ],
   *     style: {
   *         version: 8,
   *         sources: {},
   *         layers: []
   *     }
   * });
   *
   * map.addImport({
   *     id: 'lakes',
   *     url: 'https://styles/mapbox/streets-v12'
   * }, 'basemap');
   */
    addImport(importSpecification, beforeId) {
        this.style.addImport(importSpecification, beforeId);
        return this;
    }
    /**
   * Updates already added to style import.
   *
   * @param {string} importId Identifier of import to update.
   * @param {ImportSpecification | string} importSpecification Import specification or URL of style.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * // Update import with new data
   * map.updateImport('basemap', {
   *     data: {
   *         version: 8,
   *         sources: {},
   *         layers: [
   *             {
   *                 id: 'background',
   *                 type: 'background',
   *                 paint: {
   *                     'background-color': '#eee'
   *                 }
   *             }
   *         ]
   *     }
   * });
   *
   * @example
   * // Change URL of imported style
   * map.updateImport('basemap', 'mapbox://styles/mapbox/other-standard');
   */
    updateImport(importId, importSpecification) {
        if (typeof importSpecification !== 'string' && importSpecification.id !== importId) {
            this.removeImport(importId);
            return this.addImport(importSpecification);
        }
        this.style.updateImport(importId, importSpecification);
        return this._update(true);
    }
    /**
   * Removes added to style import.
   *
   * @param {string} importId Identifier of import to remove.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * // Removes imported style
   * map.removeImport('basemap');
   */
    removeImport(importId) {
        this.style.removeImport(importId);
        return this;
    }
    /**
   * Moves import to position before another import, specified with `beforeId`. Order of imported styles corresponds to order of their layers.
   *
   * @param {string} importId Identifier of import to move.
   * @param {string} beforeId The identifier of an existing import to move the new import before.
   * @returns {Map} Returns itself to allow for method chaining.
   *
   * @example
   * const map = new Map({
   *     style: {
   *         imports: [
   *             {
   *                 id: 'basemap',
   *                 url: 'mapbox://styles/mapbox/standard'
   *             },
   *             {
   *                 id: 'streets-v12',
   *                 url: 'mapbox://styles/mapbox/streets-v12'
   *             }
   *         ]
   *     }
   * });
   * // Place `streets-v12` import before `basemap`
   * map.moveImport('streets-v12', 'basemap');
   */
    moveImport(importId, beforeId) {
        this.style.moveImport(importId, 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.
   * *Note*: Layers can only be rearranged within the same `slot`. The new layer must share the
   * same `slot` as the existing layer to be positioned underneath it. If the
   * layers are in different slots, the `beforeId` parameter will be ignored and
   * the new layer will be appended to the end of the layers array.
   * During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance.
   * This process might lead to a rearrangement of layers. Layers draped over globe and terrain,
   * such as `fill`, `line`, `background`, `hillshade`, and `raster`, are rendered first.
   * These layers are rendered underneath symbols, regardless of whether they are placed
   * in the middle or top slots or without a designated slot.
   * @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;
        }
        const layer = this.style.getOwnLayer(id);
        if (!layer)
            return;
        if (layer.type === 'custom')
            return layer.implementation;
        return layer.serialize();
    }
    /**
   * Returns the IDs of all slots in the map's style.
   *
   * @returns {Array<string>} The IDs of all slots in the map's style.
   *
   * @example
   * const slots = map.getSlots();
   */
    getSlots() {
        return this.style.getSlots();
    }
    /**
   * 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} */
    /**
   * Returns the imported style schema.
   *
   * @param {string} importId The name of the imported style (e.g. `basemap`).
   * @returns {*} Returns the imported style schema.
   * @private
   *
   * @example
   * map.getSchema('basemap');
   */
    getSchema(importId) {
        return this.style.getSchema(importId);
    }
    /**
   * Sets the imported style schema value.
   *
   * @param {string} importId The name of the imported style (e.g. `basemap`).
   * @param {SchemaSpecification} schema The imported style schema.
   * @returns {Map} Returns itself to allow for method chaining.
   * @private
   *
   * @example
   * map.setSchema('basemap', {lightPreset: {type: 'string', default: 'night', values: ['day', 'night']}});
   */
    setSchema(importId, schema) {
        this.style.setSchema(importId, schema);
        return this._update(true);
    }
    /**
   * Returns the imported style configuration.
   *
   * @param {string} importId The name of the imported style (e.g. `basemap`).
   * @returns {*} Returns the imported style configuration.
   * @example
   * map.getConfig('basemap');
   */
    getConfig(importId) {
        return this.style.getConfig(importId);
    }
    /**
   * Sets the imported style configuration value.
   *
   * @param {string} importId The name of the imported style (e.g. `basemap`).
   * @param {ConfigSpecification} config The imported style configuration value.
   * @returns {Map} Returns itself to allow for method chaining.
   * @example
   * map.setConfig('basemap', {lightPreset: 'night', showPointOfInterestLabels: false});
   */
    setConfig(importId, config2) {
        this.style.setConfig(importId, config2);
        return this._update(true);
    }
    /**
   * Returns the value of a configuration property in the imported style.
   *
   * @param {string} importId The name of the imported style (e.g. `basemap`).
   * @param {string} configName The name of the configuration property from the style.
   * @returns {*} Returns the value of the configuration property.
   * @example
   * map.getConfigProperty('basemap', 'showLabels');
   */
    getConfigProperty(importId, configName) {
        return this.style.getConfigProperty(importId, configName);
    }
    /**
   * 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);
    }
    /**
   * Returns a list of featureset descriptors for querying, interaction, and state management on the map.
   * Each featureset descriptor can reference either individual layer or subset of layers within the map's style.
   *
   * @private
   * @experimental
   * @returns {FeaturesetDescriptor[]} The list of featuresets.
   * @example
   * const featuresetDescriptors = map.getFeaturesetDescriptors('basemap');
   */
    getFeaturesetDescriptors(importId) {
        return this.style.getFeaturesetDescriptors(importId);
    }
    /**
   * 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.
   * Exaggeration could be updated for the existing terrain without explicitly specifying the `source`.
   * @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});
   * // update the exaggeration for the existing terrain
   * map.setTerrain({'exaggeration': 2});
   */
    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 snow property of the style.
   * *This API is experimental, not production ready and subject to change in future versions*.
   *
   * @experimental
   * @param {SnowSpecification} snow The snow properties to set.
   * If `null` or `undefined` is provided, this function call removes the snow from the map.
   * @returns {Map} Returns itself to allow for method chaining.
   * @example
   *   map.setSnow({
   *       density: 1,
   *       intensity: 0.3
   *   });
   * */
    setSnow(snow) {
        this._lazyInitEmptyStyle();
        this.style.setSnow(snow);
        return this._update(true);
    }
    /**
   * Returns the snow specification or `null` if snow is not set on the map.
   * *This API is experimental, not production ready and subject to change in future versions*.
   *
   * @experimental
   * @returns {SnowSpecification} Snow specification properties of the style.
   * @example
   * const snow = map.getSnow();
   */
    getSnow() {
        return this.style ? this.style.getSnow() : null;
    }
    /**
   * Sets the rain property of the style.
   * *This API is experimental, not production ready and subject to change in future versions*.
   *
   * @experimental
   * @param {RainSpecification} rain The rain properties to set.
   * If `null` or `undefined` is provided, this function call removes the rain from the map.
   * @returns {Map} Returns itself to allow for method chaining.
   * @example
   *   map.setRain({
   *       density: 1,
   *       intensity: 0.3,
   *       "distortion-strength": 0.3
   *   });
   * */
    setRain(rain) {
        this._lazyInitEmptyStyle();
        this.style.setRain(rain);
        return this._update(true);
    }
    /**
   * Returns the rain specification or `null` if rain is not set on the map.
   * *This API is experimental, not production ready and subject to change in future versions*.
   *
   * @experimental
   * @returns {RainSpecification} Rain specification properties of the style.
   * @example
   * const rain = map.getRain();
   */
    getRain() {
        return this.style ? this.style.getRain() : null;
    }
    /**
   * Sets the color-theme property of the style.
   *
   * @param {ColorThemeSpecification} colorTheme The color-theme properties to set.
   * If `null` or `undefined` is provided, this function call removes the color-theme from the map.
   * Note: Calling this function triggers a full reload of tiles.
   * @returns {Map} Returns itself to allow for method chaining.
   * @example
   * map.setColorTheme({
   *     "data": "iVBORw0KGgoAA..."
   * });
   */
    setColorTheme(colorTheme) {
        this._lazyInitEmptyStyle();
        this.style.setColorTheme(colorTheme);
        return this._update(true);
    }
    /**
   * Sets the color-theme property of an import, which overrides the color-theme property of the imported style data.
   *
   * @param {string} importId Identifier of import to update.
   * @param {ColorThemeSpecification} colorTheme The color-theme properties to set.
   * If `null` or `undefined` is provided, this function call removes the color-theme override.
   * Note: Calling this function triggers a full reload of tiles.
   * @returns {Map} Returns itself to allow for method chaining.
   * @example
   * map.setImportColorTheme("someImportId", {
   *     "data": "iVBORw0KGgoAA..."
   * });
   */
    setImportColorTheme(importId, colorTheme) {
        this._lazyInitEmptyStyle();
        this.style.setImportColorTheme(importId, colorTheme);
        return this._update(true);
    }
    /**
   * 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(index.bO.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 (feature.source && !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 (feature.source && !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 (feature.source && !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.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.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color');
        if (computedColor !== 'rgb(250, 128, 114)') {
            index.w('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$1('div', 'mapboxgl-canary', container);
        missingCSSCanary.style.visibility = 'hidden';
        this._detectMissingCSS();
        const canvasContainer = this._canvasContainer = create$1('div', 'mapboxgl-canvas-container', container);
        this._canvas = create$1('canvas', 'mapboxgl-canvas', canvasContainer);
        if (this._interactive) {
            canvasContainer.classList.add('mapboxgl-interactive');
            this._canvas.setAttribute('tabindex', '0');
        }
        this._canvas.addEventListener('webglcontextlost', this._contextLost, false);
        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$1('div', 'mapboxgl-control-container', container);
        const positions = this._controlPositions = {};
        [
            'top-left',
            'top',
            'top-right',
            'right',
            'bottom-right',
            'bottom',
            'bottom-left',
            'left'
        ].forEach(positionName => {
            positions[positionName] = create$1('div', `mapboxgl-ctrl-${ positionName }`, controlContainer);
        });
        this._container.addEventListener('scroll', this._onMapScroll, false);
    }
    _resizeCanvas(width, height) {
        const pixelRatio = index.q.devicePixelRatio || 1;
        this._canvas.width = pixelRatio * Math.ceil(width);
        this._canvas.height = pixelRatio * Math.ceil(height);
        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 = index.l({}, mapboxGlSupportedExports.supported.webGLContextAttributes, {
            failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,
            preserveDrawingBuffer: this._preserveDrawingBuffer,
            antialias: this._antialias || false
        });
        const gl = this._canvas.getContext('webgl2', attributes);
        if (!gl) {
            this.fire(new index.y(new Error('Failed to initialize WebGL')));
            return;
        }
        storeAuthState(gl, true);
        this.painter = new Painter(gl, this._contextCreateOptions, this.transform, this._scaleFactor, this._tp);
        this.on('data', event => {
            if (event.dataType === 'source') {
                this.painter.setTileLoadedFlag(true);
            }
        });
        index.m.testSupport(gl);
    }
    _contextLost(event) {
        event.preventDefault();
        if (this._frame) {
            this._frame.cancel();
            this._frame = null;
        }
        this.fire(new index.z('webglcontextlost', { originalEvent: event }));
    }
    _contextRestored(event) {
        this._setupPainter();
        this.painter.resize(Math.ceil(this._containerWidth), Math.ceil(this._containerHeight));
        this._updateTerrain();
        this.style.reloadModels();
        this.style.clearSources();
        this._update();
        this.fire(new index.z('webglcontextrestored', { originalEvent: event }));
    }
    _onMapScroll(event) {
        if (event.target !== this._container)
            return;
        this._container.scrollTop = 0;
        this._container.scrollLeft = 0;
        return false;
    }
    /** @section {Lifecycle} */
    /**
   * Returns a Boolean indicating whether the map is in idle state:
   * - No camera transitions are in progress.
   * - All currently requested tiles have loaded.
   * - All fade/transition animations have completed.
   *
   * Returns `false` if there are any camera or animation transitions in progress,
   * 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.
   *
   * If the map.repaint is set to `true`, the map will never be idle.
   *
   * @returns {boolean} A Boolean indicating whether the map is idle.
   * @example
   * const isIdle = map.idle();
   */
    idle() {
        return !this.isMoving() && this.loaded();
    }
    /**
   * 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();
    }
    /**
   * Returns a Boolean indicating whether the map is finished rendering, meaning all animations are finished.
   *
   * @returns {boolean} A Boolean indicating whether map finished rendering.
   * @example
   * const frameReady = map.frameReady();
   */
    frameReady() {
        return this.loaded() && !this._placementDirty;
    }
    /**
   * 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
   */
    _requestRenderFrame(callback) {
        this._update();
        return this._renderTaskQueue.add(callback);
    }
    _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) {
        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 index.z('renderstart'));
        ++this._frameId;
        let gpuTimer;
        const extTimerQuery = this.painter.context.extTimerQuery;
        const frameStartTime = index.q.now();
        const gl = this.painter.context.gl;
        if (this.listens('gpu-timing-frame')) {
            gpuTimer = gl.createQuery();
            gl.beginQuery(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);
        }
        this.painter.context.setDirty();
        this.painter.setBaseState();
        if (this.isMoving() || this.isRotating() || this.isZooming()) {
            this._interactionRange[0] = Math.min(this._interactionRange[0], performance.now());
            this._interactionRange[1] = Math.max(this._interactionRange[1], performance.now());
        }
        this._renderTaskQueue.run(paintStartTimeStamp);
        this._domRenderTaskQueue.run(paintStartTimeStamp);
        if (this._removed)
            return;
        this._updateProjectionTransition();
        const fadeDuration = this._isInitialLoad ? 0 : this._fadeDuration;
        if (this.style && this._styleDirty) {
            this._styleDirty = false;
            const zoom = this.transform.zoom;
            const pitch = this.transform.pitch;
            const now = index.q.now();
            const parameters = new index.a8(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;
        }
        let averageElevationChanged = false;
        if (this.style && this._sourcesDirty) {
            this._sourcesDirty = false;
            this.painter._updateFog(this.style);
            this._updateTerrain();
            averageElevationChanged = this._updateAverageElevation(frameStartTime);
            this.style.updateSources(this.transform);
            this._forceMarkerAndPopupUpdate();
        } else {
            averageElevationChanged = this._updateAverageElevation(frameStartTime);
        }
        const updatePlacementResult = this.style && this.style._updatePlacement(this.painter, this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions, this.painter.replacementSource, this._scaleFactorChanged);
        if (this._scaleFactorChanged) {
            this._scaleFactorChanged = false;
        }
        if (updatePlacementResult) {
            this._placementDirty = updatePlacementResult.needsRerender;
        }
        if (this.style) {
            this.painter.render(this.style, {
                showTileBoundaries: this.showTileBoundaries,
                showParseStatus: this.showParseStatus,
                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 index.z('render'));
        if (this.loaded() && !this._loaded) {
            this._loaded = true;
            LivePerformanceUtils.mark(LivePerformanceMarkers.load);
            this.fire(new index.z('load'));
        }
        if (this.style && this.style.hasTransitions()) {
            this._styleDirty = true;
        }
        if (this.style && (this.style.snow || this.style.rain)) {
            this._styleDirty = true;
        }
        if (this.style && !this._placementDirty) {
            this.style._releaseSymbolFadeTiles();
        }
        if (gpuTimer) {
            const renderCPUTime = index.q.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 index.z('gpu-timing-frame', {
                    cpuTime: renderCPUTime,
                    gpuTime: renderGPUTime
                }));
            }, 50);
        }
        if (this.listens('gpu-timing-layer')) {
            const frameLayerQueries = this.painter.collectGpuTimers();
            setTimeout(() => {
                const renderedLayerTimes = this.painter.queryGpuTimers(frameLayerQueries);
                this.fire(new index.z('gpu-timing-layer', { layerTimes: renderedLayerTimes }));
            }, 50);
        }
        if (this.listens('gpu-timing-deferred-render')) {
            const deferredRenderQueries = this.painter.collectDeferredRenderGpuQueries();
            setTimeout(() => {
                const gpuTime = this.painter.queryGpuTimeDeferredRender(deferredRenderQueries);
                this.fire(new index.z('gpu-timing-deferred-render', { gpuTime }));
            }, 50);
        }
        const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty || averageElevationChanged;
        if (somethingDirty || this._repaint) {
            this.triggerRepaint();
        } else {
            const willIdle = this.idle();
            if (willIdle) {
                averageElevationChanged = this._updateAverageElevation(frameStartTime, true);
            }
            if (averageElevationChanged) {
                this.triggerRepaint();
            } else {
                this._triggerFrame(false);
                if (willIdle) {
                    this.fire(new index.z('idle'));
                    this._isInitialLoad = false;
                    if (this.speedIndexTiming) {
                        const speedIndexNumber = this._calculateSpeedIndex();
                        this.fire(new index.z('speedindexcompleted', { speedIndex: speedIndexNumber }));
                        this.speedIndexTiming = false;
                    }
                }
            }
        }
        if (this._loaded && !this._fullyLoaded && !somethingDirty) {
            this._fullyLoaded = true;
            LivePerformanceUtils.mark(LivePerformanceMarkers.fullLoad);
            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) {
            if (shouldWrap && !this.getRenderWorldCopies()) {
                marker._lngLat = marker._lngLat.wrap();
            }
            marker._update();
        }
        for (const popup of this._popups) {
            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 != null) {
                this._averageElevationExaggeration = this.transform.elevation.exaggeration();
            }
            if (isNaN(newElevation)) {
                newElevation = 0;
            } else {
                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) {
                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 index.y(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  ******/
    _postStyleLoadEvent() {
        if (!this.style.globalId) {
            return;
        }
        postStyleLoadEvent(this._requestManager._customAccessToken, {
            map: this,
            // @ts-expect-error - TS2353 - Object literal may only specify known properties, and 'skuToken' does not exist in type 'StyleLoadEventInput'.
            skuToken: this._requestManager._skuToken,
            style: this.style.globalId,
            importedStyles: this.style.getImportGlobalIds()
        });
    }
    _updateTerrain() {
        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;
                }
            }
            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.indoor.destroy();
        this.painter.destroy();
        if (this.handlers)
            this.handlers.destroy();
        this.handlers = void 0;
        this.setStyle(null);
        window.removeEventListener('resize', this._onWindowResize, false);
        window.removeEventListener('orientationchange', this._onWindowResize, false);
        window.removeEventListener(this._fullscreenchangeEvent, this._onWindowResize, false);
        window.removeEventListener('online', this._onWindowOnline, false);
        window.removeEventListener('visibilitychange', this._onVisibilityChange, false);
        const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');
        if (extension)
            extension.loseContext();
        this._canvas.removeEventListener('webglcontextlost', this._contextLost, false);
        this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false);
        this._canvasContainer.remove();
        this._controlContainer.remove();
        this._missingCSSCanary.remove();
        this._canvas = void 0;
        this._canvasContainer = void 0;
        this._controlContainer = void 0;
        this._missingCSSCanary = void 0;
        this._container.classList.remove('mapboxgl-map');
        this._container.removeEventListener('scroll', this._onMapScroll, false);
        removeAuthState(this.painter.context.gl);
        mapSessionAPI.remove();
        mapLoadEvent.remove();
        this._removed = true;
        this.fire(new index.z('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 = index.q.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.
   */
    _preloadTiles(transform) {
        const sourceCaches = this.style ? this.style.getSourceCaches() : [];
        index.bl(sourceCaches, (sourceCache, done) => sourceCache._preloadTiles(transform, done), () => {
            this.triggerRepaint();
        });
        return this;
    }
    _onWindowOnline() {
        this._update();
    }
    _onWindowResize(event) {
        if (this._trackResize) {
            this.resize({ originalEvent: event })._update();
        }
    }
    _onVisibilityChange() {
        if (document.visibilityState === 'hidden') {
            this._visibilityHidden++;
        }
    }
    /** @section {Debug features} */
    /**
   * Gets and sets a Boolean indicating whether the map will render an outline
   * around each tile. These tile boundaries are useful for debugging.
   *
   * @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._tp.refreshUI();
        this._update();
    }
    /**
   * Gets and sets a Boolean indicating whether the map will render the tile ID
   * and the status of the tile in their corner when `showTileBoundaries` is on.
   *
   * 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 showParseStatus
   * @type {boolean}
   * @instance
   * @memberof Map
   * @example
   * map.showParseStatus = true;
   */
    get showParseStatus() {
        return !!this._showParseStatus;
    }
    set showParseStatus(value) {
        if (this._showParseStatus === value)
            return;
        this._showParseStatus = value;
        this._tp.refreshUI();
        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._tp.refreshUI();
        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._tp.refreshUI();
        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._tp.refreshUI();
        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._tp.refreshUI();
        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;
        this._tp.refreshUI();
        if (value) {
            this.style._generateCollisionBoxes();
        } else {
            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._tp.refreshUI();
        this._update();
    }
    /**
   * Gets and sets a Boolean indicating whether the map will
   * continuously repaint. This information is useful for analyzing performance.
   * The map will never be idle when this option is set to `true`.
   *
   * @name repaint
   * @type {boolean}
   * @instance
   * @memberof Map
   */
    get repaint() {
        return !!this._repaint;
    }
    set repaint(value) {
        if (this._repaint !== value) {
            this._repaint = value;
            this._tp.refreshUI();
            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;
        this._tp.refreshUI();
        if (!value) {
            return;
        }
        this._update();
    }
    // for cache browser tests
    _setCacheLimits(limit, checkThreshold) {
        index.dG(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;
    }
};

const defaultOptions$3 = {
    showCompass: true,
    showZoom: true,
    visualizePitch: false
};
class NavigationControl {
    constructor(options = {}) {
        this.options = index.l({}, defaultOptions$3, options);
        this._container = create$1('div', 'mapboxgl-ctrl mapboxgl-ctrl-group');
        this._container.addEventListener('contextmenu', e => e.preventDefault());
        if (this.options.showZoom) {
            index.aP([
                '_setButtonTitle',
                '_updateZoomButtons'
            ], this);
            this._zoomInButton = this._createButton('mapboxgl-ctrl-zoom-in', e => {
                if (this._map)
                    this._map.zoomIn({}, { originalEvent: e });
            });
            create$1('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$1('span', `mapboxgl-ctrl-icon`, this._zoomOutButton).setAttribute('aria-hidden', 'true');
        }
        if (this.options.showCompass) {
            index.aP(['_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$1('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');
            map.on('zoom', this._updateZoomButtons);
            this._updateZoomButtons();
        }
        if (this.options.showCompass) {
            this._setButtonTitle(this._compass, 'ResetBearing');
            if (this.options.visualizePitch) {
                map.on('pitch', this._rotateCompassArrow);
            }
            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) {
            map.off('zoom', this._updateZoomButtons);
        }
        if (this.options.showCompass) {
            if (this.options.visualizePitch) {
                map.off('pitch', this._rotateCompassArrow);
            }
            map.off('rotate', this._rotateCompassArrow);
            if (this._handler)
                this._handler.off();
            this._handler = void 0;
        }
        this._map = void 0;
    }
    _createButton(className, fn) {
        const a = create$1('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 });
        index.aP([
            'mousedown',
            'mousemove',
            'mouseup',
            'touchstart',
            'touchmove',
            'touchend',
            'reset'
        ], this);
        element.addEventListener('mousedown', this.mousedown);
        element.addEventListener('touchstart', this.touchstart, { passive: false });
        element.addEventListener('touchmove', this.touchmove);
        element.addEventListener('touchend', this.touchend);
        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 delta2 = p && p.pitchDelta;
            if (delta2)
                map.setPitch(map.getPitch() + delta2);
        }
    }
    off() {
        const element = this.element;
        element.removeEventListener('mousedown', this.mousedown);
        element.removeEventListener('touchstart', this.touchstart, { passive: false });
        element.removeEventListener('touchmove', this.touchmove);
        element.removeEventListener('touchend', this.touchend);
        element.removeEventListener('touchcancel', this.reset);
        this.offTemp();
    }
    offTemp() {
        enableDrag();
        window.removeEventListener('mousemove', this.mousemove);
        window.removeEventListener('mouseup', this.mouseup);
    }
    mousedown(e) {
        this.down(index.l({}, e, {
            ctrlKey: true,
            preventDefault: () => e.preventDefault()
        }), mousePos(this.element, e));
        window.addEventListener('mousemove', this.mousemove);
        window.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();
    }
}

function smartWrap (lngLat, priorPos, transform) {
    lngLat = new index.bO(lngLat.lng, lngLat.lat);
    if (priorPos) {
        const left = new index.bO(lngLat.lng - 360, lngLat.lat);
        const right = new index.bO(lngLat.lng + 360, lngLat.lat);
        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;
        }
    }
    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%)'
};

class Marker extends index.E {
    constructor(options, legacyOptions) {
        super();
        if (options instanceof HTMLElement || legacyOptions) {
            options = index.l({ element: options }, legacyOptions);
        }
        index.aP([
            '_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$1('div');
            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);
            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);
            this._offset = index.P.convert(options && options.offset || [
                0,
                -14
            ]);
        } else {
            this._element = options.element;
            this._offset = index.P.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 => {
            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);
        map.on('moveend', this._update);
        map.on('remove', this._clearFadeTimer);
        map._addMarker(this);
        this.setDraggable(this._draggable);
        this._update();
        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) {
            map.off('click', this._onMapClick);
            map.off('move', this._updateMoving);
            map.off('moveend', this._update);
            map.off('mousedown', this._addDragHandler);
            map.off('touchstart', this._addDragHandler);
            map.off('mouseup', this._onUp);
            map.off('touchend', this._onUp);
            map.off('mousemove', this._onMove);
            map.off('touchmove', this._onMove);
            map.off('remove', this._clearFadeTimer);
            map._removeMarker(this);
            this._map = void 0;
        }
        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 = index.bO.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');
            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');
            }
            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) {
            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() && index.dH(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();
        if (!map || !pos || alignment !== 'map') {
            return ``;
        }
        if (!map._showingGlobe()) {
            const pitch = map.getPitch();
            return pitch ? `rotateX(${ pitch }deg)` : '';
        }
        const tilt = index.c4(index.dI(map.transform, this._lngLat));
        const posFromCenter = pos.sub(index.dJ(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 index.bO(this._lngLat.lng, this._lngLat.lat + 0.001));
                const south = map.project(new index.bO(this._lngLat.lng, this._lngLat.lat - 0.001));
                const diff = south.sub(north);
                rotation = index.c4(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 = index.ac(ALIGN_TO_HORIZON_BELOW_ZOOM, ALIGN_TO_SCREEN_ABOVE_ZOOM, map.getZoom());
            const centerPoint = index.dJ(map.transform);
            centerPoint.y += smooth * map.transform.height;
            const rel = pos.sub(centerPoint);
            const angle = index.c4(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) {
        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);
        if (delaySnap === true) {
            this._updateFrameId = 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) {
                this._fadeTimer = window.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 = index.P.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);
        this._element.style.pointerEvents = 'none';
        if (this._state === 'pending') {
            this._state = 'active';
            this.fire(new index.z('dragstart'));
        }
        this.fire(new index.z('drag'));
    }
    _onUp() {
        this._element.style.pointerEvents = 'auto';
        this._positionDelta = null;
        this._pointerdownPos = null;
        this._isDragging = false;
        const map = this._map;
        if (map) {
            map.off('mousemove', this._onMove);
            map.off('touchmove', this._onMove);
        }
        if (this._state === 'active') {
            this.fire(new index.z('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();
            this._positionDelta = e.point.sub(pos);
            this._pointerdownPos = e.point;
            this._state = 'pending';
            map.on('mousemove', this._onMove);
            map.on('touchmove', this._onMove);
            map.once('mouseup', this._onUp);
            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;
        const map = this._map;
        if (map) {
            if (shouldBeDraggable) {
                map.on('mousedown', this._addDragHandler);
                map.on('touchstart', this._addDragHandler);
            } else {
                map.off('mousedown', this._addDragHandler);
                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$2 = {
    positionOptions: {
        enableHighAccuracy: false,
        maximumAge: 0,
        timeout: 6000    /* 6 sec */
    },
    fitBoundsOptions: { maxZoom: 15 },
    trackUserLocation: false,
    showAccuracyCircle: true,
    showUserLocation: true,
    showUserHeading: false
};
class GeolocateControl extends index.E {
    constructor(options = {}) {
        super();
        const geolocation = navigator.geolocation;
        this.options = index.l({ geolocation }, defaultOptions$2, options);
        index.aP([
            '_onSuccess',
            '_onError',
            '_onZoom',
            '_finish',
            '_setupUI',
            '_updateCamera',
            '_updateMarker',
            '_updateMarkerRotation',
            '_onDeviceOrientation'
        ], this);
        this._updateMarkerRotationThrottled = throttle(this._updateMarkerRotation, 20);
        this._numberOfWatches = 0;
    }
    onAdd(map) {
        this._map = map;
        this._container = create$1('div', `mapboxgl-ctrl mapboxgl-ctrl-group`);
        this._checkGeolocationSupport(this._setupUI);
        return this._container;
    }
    onRemove() {
        if (this._geolocationWatchID !== void 0) {
            this.options.geolocation.clearWatch(this._geolocationWatchID);
            this._geolocationWatchID = void 0;
        }
        if (this.options.showUserLocation && this._userLocationDotMarker) {
            this._userLocationDotMarker.remove();
        }
        if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {
            this._accuracyCircleMarker.remove();
        }
        this._container.remove();
        this._map.off('zoom', this._onZoom);
        this._map = void 0;
        this._numberOfWatches = 0;
        this._noTimeout = false;
    }
    _checkGeolocationSupport(callback) {
        const updateSupport = (supported = !!this.options.geolocation) => {
            this._supportsGeolocation = supported;
            callback(supported);
        };
        if (this._supportsGeolocation !== void 0) {
            callback(this._supportsGeolocation);
        } else if (navigator.permissions !== void 0) {
            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');
            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');
            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) {
            return;
        }
        if (this._isOutOfMapMaxBounds(position)) {
            this._setErrorState();
            this.fire(new index.z('outofmaxbounds', position));
            this._updateMarker();
            this._finish();
            return;
        }
        if (this.options.trackUserLocation) {
            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 (this.options.showUserLocation && this._watchState !== 'OFF') {
            this._updateMarker(position);
        }
        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 index.z('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 index.bO(position.coords.longitude, position.coords.latitude);
        const radius = position.coords.accuracy;
        const bearing = this._map.getBearing();
        const options = index.l({ 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 index.bO(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 = index.bH(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) {
            return;
        }
        if (this.options.trackUserLocation) {
            if (error.code === 1) {
                this._watchState = 'OFF';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');
                this._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 !== void 0) {
                    this._clearWatch();
                }
            } else if (error.code === 3 && this._noTimeout) {
                return;
            } else {
                this._setErrorState();
            }
        }
        if (this._watchState !== 'OFF' && this.options.showUserLocation) {
            this._userLocationDotMarker.addClassName('mapboxgl-user-location-dot-stale');
        }
        this.fire(new index.z('error', error));
        this._finish();
    }
    _finish() {
        if (this._timeoutId) {
            clearTimeout(this._timeoutId);
        }
        this._timeoutId = void 0;
    }
    _setupUI(supported) {
        if (this._map === void 0) {
            return;
        }
        this._container.addEventListener('contextmenu', e => e.preventDefault());
        this._geolocateButton = create$1('button', `mapboxgl-ctrl-geolocate`, this._container);
        create$1('span', `mapboxgl-ctrl-icon`, this._geolocateButton).setAttribute('aria-hidden', 'true');
        this._geolocateButton.type = 'button';
        if (supported === false) {
            index.w('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';
        }
        if (this.options.showUserLocation) {
            this._dotElement = create$1('div', 'mapboxgl-user-location');
            this._dotElement.appendChild(create$1('div', 'mapboxgl-user-location-dot'));
            this._dotElement.appendChild(create$1('div', 'mapboxgl-user-location-heading'));
            this._userLocationDotMarker = new Marker({
                element: this._dotElement,
                rotationAlignment: 'map',
                pitchAlignment: 'map'
            });
            this._circleElement = create$1('div', 'mapboxgl-user-location-accuracy-circle');
            this._accuracyCircleMarker = new Marker({
                element: this._circleElement,
                pitchAlignment: 'map'
            });
            if (this.options.trackUserLocation)
                this._watchState = 'OFF';
            this._map.on('zoom', this._onZoom);
        }
        this._geolocateButton.addEventListener('click', this.trigger.bind(this));
        this._setup = true;
        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 index.z('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) {
        if (this._userLocationDotMarker) {
            if (deviceOrientationEvent.webkitCompassHeading) {
                this._heading = deviceOrientationEvent.webkitCompassHeading;
            } else if (deviceOrientationEvent.absolute === true) {
                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) {
            index.w('Geolocate control triggered before added to a map');
            return false;
        }
        if (this.options.trackUserLocation) {
            switch (this._watchState) {
            case 'OFF':
                this._watchState = 'WAITING_ACTIVE';
                this.fire(new index.z('trackuserlocationstart'));
                break;
            case 'WAITING_ACTIVE':
            case 'ACTIVE_LOCK':
            case 'ACTIVE_ERROR':
            case 'BACKGROUND_ERROR':
                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 index.z('trackuserlocationend'));
                break;
            case 'BACKGROUND':
                this._watchState = 'ACTIVE_LOCK';
                this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');
                if (this._lastKnownPosition)
                    this._updateCamera(this._lastKnownPosition);
                this.fire(new index.z('trackuserlocationstart'));
                break;
            }
            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;
            // @ts-expect-error - TS2678 - Type '"ACTIVE_ERROR"' is not comparable to type '"OFF" | "ACTIVE_LOCK" | "WAITING_ACTIVE"'.
            case 'ACTIVE_ERROR':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');
                break;
            // @ts-expect-error - TS2678 - Type '"BACKGROUND"' is not comparable to type '"OFF" | "ACTIVE_LOCK" | "WAITING_ACTIVE"'.
            case 'BACKGROUND':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');
                break;
            // @ts-expect-error - TS2678 - Type '"BACKGROUND_ERROR"' is not comparable to type '"OFF" | "ACTIVE_LOCK" | "WAITING_ACTIVE"'.
            case 'BACKGROUND_ERROR':
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');
                break;
            }
            if (this._watchState === 'OFF' && this._geolocationWatchID !== void 0) {
                this._clearWatch();
            } else if (this._geolocationWatchID === void 0) {
                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 {
            this.options.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions);
            this._timeoutId = window.setTimeout(this._finish, 10000    /* 10sec */);
        }
        return true;
    }
    _addDeviceOrientationListener() {
        const addListener = () => {
            if ('ondeviceorientationabsolute' in window) {
                window.addEventListener('deviceorientationabsolute', this._onDeviceOrientation);
            } else {
                window.addEventListener('deviceorientation', this._onDeviceOrientation);
            }
        };
        if (typeof DeviceMotionEvent !== 'undefined' && typeof DeviceMotionEvent.requestPermission === 'function') {
            DeviceOrientationEvent.requestPermission().then(response => {
                if (response === 'granted') {
                    addListener();
                }
            }).catch(console.error);
        } else {
            addListener();
        }
    }
    _clearWatch() {
        this.options.geolocation.clearWatch(this._geolocationWatchID);
        window.removeEventListener('deviceorientation', this._onDeviceOrientation);
        window.removeEventListener('deviceorientationabsolute', this._onDeviceOrientation);
        this._geolocationWatchID = void 0;
        this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');
        this._geolocateButton.setAttribute('aria-pressed', 'false');
        if (this.options.showUserLocation) {
            this._updateMarker(null);
        }
    }
}

const defaultOptions$1 = {
    maxWidth: 100,
    unit: 'metric'
};
const unitAbbr = {
    kilometer: 'km',
    meter: 'm',
    mile: 'mi',
    foot: 'ft',
    'nautical-mile': 'nm'
};
class ScaleControl {
    constructor(options = {}) {
        this.options = index.l({}, defaultOptions$1, options);
        this._isNumberFormatSupported = isNumberFormatSupported();
        index.aP([
            '_update',
            '_setScale',
            'setUnit'
        ], this);
    }
    getDefaultPosition() {
        return 'bottom-left';
    }
    _update() {
        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);
        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') {
                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$1('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', map.getContainer());
        this._container.dir = 'auto';
        this._map.on('move', this._update);
        this._update();
        return this._container;
    }
    onRemove() {
        this._container.remove();
        this._map.off('move', this._update);
        this._map = void 0;
    }
    _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 {
        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;
}

class FullscreenControl {
    constructor(options = {}) {
        this._fullscreen = false;
        if (options && options.container) {
            if (options.container instanceof HTMLElement) {
                this._container = options.container;
            } else {
                index.w('Full screen control \'container\' must be a DOM element.');
            }
        }
        index.aP([
            '_onClickFullscreen',
            '_changeIcon'
        ], this);
        if ('onfullscreenchange' in document) {
            this._fullscreenchange = 'fullscreenchange';
        } else if ('onwebkitfullscreenchange' in document) {
            this._fullscreenchange = 'webkitfullscreenchange';
        }
    }
    onAdd(map) {
        this._map = map;
        if (!this._container)
            this._container = this._map.getContainer();
        this._controlContainer = create$1('div', `mapboxgl-ctrl mapboxgl-ctrl-group`);
        if (this._checkFullscreenSupport()) {
            this._setupUI();
        } else {
            this._controlContainer.style.display = 'none';
            index.w('This device does not support fullscreen mode.');
        }
        return this._controlContainer;
    }
    onRemove() {
        this._controlContainer.remove();
        this._map = null;
        document.removeEventListener(this._fullscreenchange, this._changeIcon);
    }
    _checkFullscreenSupport() {
        return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled);
    }
    _setupUI() {
        const button = this._fullscreenButton = create$1('button', `mapboxgl-ctrl-fullscreen`, this._controlContainer);
        create$1('span', `mapboxgl-ctrl-icon`, button).setAttribute('aria-hidden', 'true');
        button.type = 'button';
        this._updateTitle();
        this._fullscreenButton.addEventListener('click', this._onClickFullscreen);
        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 = document.fullscreenElement || 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 (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
        } else if (this._container.requestFullscreen) {
            this._container.requestFullscreen();
        } else if (this._container.webkitRequestFullscreen) {
            this._container.webkitRequestFullscreen();
        }
    }
}

const defaultOptions = {
    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(', ');
class Popup extends index.E {
    constructor(options) {
        super();
        this.options = index.l(Object.create(defaultOptions), options);
        index.aP([
            '_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) {
            map.on('preclick', this._onClose);
        }
        if (this.options.closeOnMove) {
            map.on('move', this._onClose);
        }
        map.on('remove', this.remove);
        this._update();
        map._addPopup(this);
        this._focusFirstElement();
        if (this._trackPointer) {
            map.on('mousemove', this._onMouseEvent);
            map.on('mouseup', this._onMouseEvent);
            map._canvasContainer.classList.add('mapboxgl-track-pointer');
        } else {
            map.on('move', this._update);
        }
        this.fire(new index.z('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 = void 0;
        }
        const map = this._map;
        if (map) {
            map.off('move', this._update);
            map.off('move', this._onClose);
            map.off('preclick', this._onClose);
            map.off('click', this._onClose);
            map.off('remove', this.remove);
            map.off('mousemove', this._onMouseEvent);
            map.off('mouseup', this._onMouseEvent);
            map.off('drag', this._onMouseEvent);
            if (map._canvasContainer) {
                map._canvasContainer.classList.remove('mapboxgl-track-pointer');
            }
            map._removePopup(this);
            this._map = void 0;
        }
        this.fire(new index.z('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 = index.bO.convert(lnglat);
        this._pos = null;
        this._trackPointer = false;
        this._update();
        const map = this._map;
        if (map) {
            map.on('move', this._update);
            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) {
            map.off('move', this._update);
            map.on('mousemove', this._onMouseEvent);
            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(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 = document.createDocumentFragment();
        const temp = 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) {
            while (content.hasChildNodes()) {
                if (content.firstChild) {
                    content.removeChild(content.firstChild);
                }
            }
        } else {
            content = this._content = create$1('div', 'mapboxgl-popup-content', this._container || void 0);
        }
        content.appendChild(htmlNode);
        if (this.options.closeButton) {
            const button = this._closeButton = create$1('button', 'mapboxgl-popup-close-button', content);
            button.type = 'button';
            button.setAttribute('aria-label', 'Close popup');
            button.innerHTML = '<span aria-hidden="true">&#215;</span>';
            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$1('div', 'mapboxgl-popup', map.getContainer());
            this._tip = create$1('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 instanceof index.P ? 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 = index.dH(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';
        }
    }
}
function normalizeOffset(offset = new index.P(0, 0), anchor = 'bottom') {
    if (typeof offset === 'number') {
        const cornerOffset = Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));
        switch (anchor) {
        case 'top':
            return new index.P(0, offset);
        case 'top-left':
            return new index.P(cornerOffset, cornerOffset);
        case 'top-right':
            return new index.P(-cornerOffset, cornerOffset);
        case 'bottom':
            return new index.P(0, -offset);
        case 'bottom-left':
            return new index.P(cornerOffset, -cornerOffset);
        case 'bottom-right':
            return new index.P(-cornerOffset, -cornerOffset);
        case 'left':
            return new index.P(offset, 0);
        case 'right':
            return new index.P(-offset, 0);
        }
        return new index.P(0, 0);
    }
    if (offset instanceof index.P || Array.isArray(offset)) {
        return index.P.convert(offset);
    }
    return index.P.convert(offset[anchor] || [
        0,
        0
    ]);
}

const exported = {
    version,
    supported: mapboxGlSupportedExports.supported,
    setRTLTextPlugin: index.dK,
    getRTLTextPluginStatus: index.dL,
    Map: Map$1,
    NavigationControl,
    GeolocateControl,
    AttributionControl,
    ScaleControl,
    FullscreenControl,
    Popup,
    Marker,
    Style,
    LngLat: index.bO,
    LngLatBounds: index.az,
    Point: index.P,
    MercatorCoordinate: index.aa,
    FreeCameraOptions,
    Evented: index.E,
    config: index.e,
    /**
   * 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: index.dM,
    /**
   * 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: index.dN,
    /**
   * 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 index.e.ACCESS_TOKEN;
    },
    set accessToken(token) {
        index.e.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 index.e.API_URL;
    },
    set baseApiUrl(url) {
        index.e.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 index.dO.workerCount;
    },
    set workerCount(count) {
        index.dO.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 index.e.MAX_PARALLEL_IMAGE_REQUESTS;
    },
    set maxParallelImageRequests(numRequests) {
        index.e.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) {
        index.dP(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/guides/browsers/#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>
   */
    get workerUrl() {
        return index.dQ.workerUrl;
    },
    set workerUrl(url) {
        index.dQ.workerUrl = url;
    },
    /**
   * 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';
   * import MapboxGLWorker from 'mapbox-gl/dist/mapbox-gl-csp-worker';
   *
   * mapboxgl.workerClass = MapboxGLWorker;
   */
    get workerClass() {
        return index.dQ.workerClass;
    },
    set workerClass(klass) {
        index.dQ.workerClass = klass;
    },
    get workerParams() {
        return index.dQ.workerParams;
    },
    set workerParams(params) {
        index.dQ.workerParams = params;
    },
    /**
   * 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/guides/browsers/#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 index.dR();
    },
    set dracoUrl(url) {
        index.dS(url);
    },
    get meshoptUrl() {
        return index.dT();
    },
    set meshoptUrl(url) {
        index.dU(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: index.q.setNow,
    /**
   * Restores the internal animation timing to follow regular computer time (`performance.now()`).
   */
    restoreNow: index.q.restoreNow
};

return exported;

}));

//
// 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
