Skip to content

Instantly share code, notes, and snippets.

@IagoLast
Last active March 8, 2018 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IagoLast/e01e3113b75b7744968aad6deb95b55c to your computer and use it in GitHub Desktop.
Save IagoLast/e01e3113b75b7744968aad6deb95b55c to your computer and use it in GitHub Desktop.
/*!
* CARTO GL js https://carto.com/
* Version: 0.0.0-alpha.1
*
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["carto"] = factory();
else
root["carto"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 30);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__schema__ = __webpack_require__(10);
class Expression {
/**
* @hideconstructor
* @param {*} children
* @param {*} inlineMaker
* @param {*} preface
*/
constructor(children) {
this.childrenNames = Object.keys(children);
Object.keys(children).map(name => this[name] = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(children[name]));
this._getChildren().map(child => child.parent = this);
this._metaBindings = [];
this.preface = '';
}
_bind(metadata) {
this._metaBindings.push(metadata);
this._compile(metadata);
return this;
}
_compile(metadata) {
this._getChildren().map(child => child._compile(metadata));
}
_setGenericGLSL(inlineMaker, preface) {
this.inlineMaker = inlineMaker;
this.preface = (preface ? preface : '');
}
/**
* Generate GLSL code
* @param {*} uniformIDMaker fn to get unique IDs
* @param {*} propertyTIDMaker fn to get property IDs and inform of used properties
*/
_applyToShaderSource(uniformIDMaker, propertyTIDMaker) {
const childSources = this.childrenNames.map(name => this[name]._applyToShaderSource(uniformIDMaker, propertyTIDMaker));
let childInlines = {};
childSources.map((source, index) => childInlines[this.childrenNames[index]] = source.inline);
return {
preface: childSources.map(s => s.preface).reduce((a, b) => a + b, '') + this.preface,
inline: this.inlineMaker(childInlines, uniformIDMaker, propertyTIDMaker)
};
}
/**
* Inform about a successful shader compilation. One-time post-compilation WebGL calls should be done here.
* @param {*} program
*/
_postShaderCompile(program, gl) {
this.childrenNames.forEach(name => this[name]._postShaderCompile(program, gl));
}
_getDrawMetadataRequirements() {
// Depth First Search => reduce using union
return this._getChildren().map(child => child._getDrawMetadataRequirements()).reduce(__WEBPACK_IMPORTED_MODULE_2__schema__["union"], __WEBPACK_IMPORTED_MODULE_2__schema__["IDENTITY"]);
}
/**
* Pre-rendering routine. Should establish related WebGL state as needed.
* @param {*} l
*/
_preDraw(...args) {
this.childrenNames.forEach(name => this[name]._preDraw(...args));
}
/**
* @jsapi
* @returns true if the evaluation of the function at styling time won't be the same every time.
*/
isAnimated() {
return this._getChildren().some(child => child.isAnimated());
}
/**
* Replace child *toReplace* by *replacer*
* @param {*} toReplace
* @param {*} replacer
*/
_replaceChild(toReplace, replacer) {
const name = this.childrenNames.find(name => this[name] == toReplace);
this[name] = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
}
/**
* Linear interpolation between this and finalValue with the specified duration
* @jsapi
* @param {Expression} final
* @param {Expression} duration
* @param {Expression} blendFunc
*/
//TODO blendFunc = 'linear'
blendTo(final, duration = 500) {
final = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(final);
const parent = this.parent;
const blender = Object(__WEBPACK_IMPORTED_MODULE_1__functions__["blend"])(this, final, Object(__WEBPACK_IMPORTED_MODULE_1__functions__["animate"])(duration));
this._metaBindings.map(m => blender._bind(m));
parent._replaceChild(this, blender);
blender.notify();
}
blendFrom(final, duration = 500, interpolator = null) {
final = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(final);
const parent = this.parent;
const blender = Object(__WEBPACK_IMPORTED_MODULE_1__functions__["blend"])(final, this, Object(__WEBPACK_IMPORTED_MODULE_1__functions__["animate"])(duration), interpolator);
this._metaBindings.map(m => blender._bind(m));
parent._replaceChild(this, blender);
blender.notify();
}
/**
* @returns a list with the expression children
*/
_getChildren() {
return this.childrenNames.map(name => this[name]);
}
_getMinimumNeededSchema() {
// Depth First Search => reduce using union
return this._getChildren().map(child => child._getMinimumNeededSchema()).reduce(__WEBPACK_IMPORTED_MODULE_2__schema__["union"], __WEBPACK_IMPORTED_MODULE_2__schema__["IDENTITY"]);
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Expression;
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "in", function() { return _in; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expressions_palettes__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__expressions_animate__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__expressions_blend__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__expressions_buckets__ = __webpack_require__(36);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__expressions_CIELab__ = __webpack_require__(37);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__expressions_float__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__expressions_floatConstant__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__expressions_category__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__expressions_hsv__ = __webpack_require__(38);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__expressions_linear__ = __webpack_require__(39);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__expressions_near__ = __webpack_require__(40);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__expressions_now__ = __webpack_require__(41);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__expressions_property__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__expressions_ramp__ = __webpack_require__(42);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__expressions_rgba__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__expressions_opacity__ = __webpack_require__(44);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__expressions_top__ = __webpack_require__(45);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__expressions_xyz__ = __webpack_require__(46);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__expressions_zoom__ = __webpack_require__(47);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__expressions_belongs_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__expressions_between__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__expressions_unary__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__expressions_binary__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__expressions_aggregation__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__expressions_quantiles__ = __webpack_require__(48);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__expressions_interpolators__ = __webpack_require__(19);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Cubic", function() { return __WEBPACK_IMPORTED_MODULE_25__expressions_interpolators__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__ = __webpack_require__(49);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__ = __webpack_require__(50);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "palettes", function() { return __WEBPACK_IMPORTED_MODULE_0__expressions_palettes__["b"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Asc", function() { return __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Desc", function() { return __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__["b"]; });
/**
* @api
* @namespace carto.style.expressions
*
*/
// Unary ops
// Binary ops
// Aggregation ops
// Classifiers
// Interpolators
// Expose classes as constructor functions
const asc = (...args) => new __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__["a" /* Asc */](...args);
/* harmony export (immutable) */ __webpack_exports__["asc"] = asc;
const desc = (...args) => new __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__["b" /* Desc */](...args);
/* harmony export (immutable) */ __webpack_exports__["desc"] = desc;
const noOrder = (...args) => new __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__["c" /* NoOrder */](...args);
/* harmony export (immutable) */ __webpack_exports__["noOrder"] = noOrder;
const width = (...args) => new __WEBPACK_IMPORTED_MODULE_27__expressions_ordering__["d" /* Width */](...args);
/* harmony export (immutable) */ __webpack_exports__["width"] = width;
const floatMul = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["f" /* FloatMul */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatMul"] = floatMul;
const floatDiv = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["d" /* FloatDiv */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatDiv"] = floatDiv;
const floatAdd = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["c" /* FloatAdd */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatAdd"] = floatAdd;
const floatSub = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["h" /* FloatSub */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatSub"] = floatSub;
const floatPow = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["g" /* FloatPow */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatPow"] = floatPow;
const floatMod = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["e" /* FloatMod */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatMod"] = floatMod;
const log = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["c" /* Log */](...args);
/* harmony export (immutable) */ __webpack_exports__["log"] = log;
const sqrt = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["g" /* Sqrt */](...args);
/* harmony export (immutable) */ __webpack_exports__["sqrt"] = sqrt;
const sin = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["f" /* Sin */](...args);
/* harmony export (immutable) */ __webpack_exports__["sin"] = sin;
const cos = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["b" /* Cos */](...args);
/* harmony export (immutable) */ __webpack_exports__["cos"] = cos;
const tan = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["h" /* Tan */](...args);
/* harmony export (immutable) */ __webpack_exports__["tan"] = tan;
const sign = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["e" /* Sign */](...args);
/* harmony export (immutable) */ __webpack_exports__["sign"] = sign;
const near = (...args) => new __WEBPACK_IMPORTED_MODULE_10__expressions_near__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["near"] = near;
const blend = (...args) => new __WEBPACK_IMPORTED_MODULE_2__expressions_blend__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["blend"] = blend;
const rgba = (...args) => new __WEBPACK_IMPORTED_MODULE_14__expressions_rgba__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["rgba"] = rgba;
const property = (...args) => new __WEBPACK_IMPORTED_MODULE_12__expressions_property__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["property"] = property;
const animate = (...args) => new __WEBPACK_IMPORTED_MODULE_1__expressions_animate__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["animate"] = animate;
const hsv = (...args) => new __WEBPACK_IMPORTED_MODULE_8__expressions_hsv__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["hsv"] = hsv;
const opacity = (...args) => new __WEBPACK_IMPORTED_MODULE_15__expressions_opacity__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["opacity"] = opacity;
const ramp = (...args) => new __WEBPACK_IMPORTED_MODULE_13__expressions_ramp__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["ramp"] = ramp;
const float = (...args) => new __WEBPACK_IMPORTED_MODULE_5__expressions_float__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["float"] = float;
const category = (...args) => new __WEBPACK_IMPORTED_MODULE_7__expressions_category__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["category"] = category;
const max = (...args) => new __WEBPACK_IMPORTED_MODULE_23__expressions_aggregation__["b" /* Max */](...args);
/* harmony export (immutable) */ __webpack_exports__["max"] = max;
const min = (...args) => new __WEBPACK_IMPORTED_MODULE_23__expressions_aggregation__["c" /* Min */](...args);
/* harmony export (immutable) */ __webpack_exports__["min"] = min;
const sum = (...args) => new __WEBPACK_IMPORTED_MODULE_23__expressions_aggregation__["e" /* Sum */](...args);
/* harmony export (immutable) */ __webpack_exports__["sum"] = sum;
const avg = (...args) => new __WEBPACK_IMPORTED_MODULE_23__expressions_aggregation__["a" /* Avg */](...args);
/* harmony export (immutable) */ __webpack_exports__["avg"] = avg;
const mode = (...args) => new __WEBPACK_IMPORTED_MODULE_23__expressions_aggregation__["d" /* Mode */](...args);
/* harmony export (immutable) */ __webpack_exports__["mode"] = mode;
const top = (...args) => new __WEBPACK_IMPORTED_MODULE_16__expressions_top__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["top"] = top;
const linear = (...args) => new __WEBPACK_IMPORTED_MODULE_9__expressions_linear__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["linear"] = linear;
const cubic = (...args) => new __WEBPACK_IMPORTED_MODULE_25__expressions_interpolators__["a" /* Cubic */](...args);
/* harmony export (immutable) */ __webpack_exports__["cubic"] = cubic;
const ilinear = (...args) => new __WEBPACK_IMPORTED_MODULE_25__expressions_interpolators__["b" /* ILinear */](...args);
/* harmony export (immutable) */ __webpack_exports__["ilinear"] = ilinear;
const now = (...args) => new __WEBPACK_IMPORTED_MODULE_11__expressions_now__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["now"] = now;
const zoom = (...args) => new __WEBPACK_IMPORTED_MODULE_18__expressions_zoom__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["zoom"] = zoom;
const cielab = (...args) => new __WEBPACK_IMPORTED_MODULE_4__expressions_CIELab__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["cielab"] = cielab;
const xyz = (...args) => new __WEBPACK_IMPORTED_MODULE_17__expressions_xyz__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["xyz"] = xyz;
const abs = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["a" /* Abs */](...args);
/* harmony export (immutable) */ __webpack_exports__["abs"] = abs;
const greaterThan = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["i" /* GreaterThan */](...args);
/* harmony export (immutable) */ __webpack_exports__["greaterThan"] = greaterThan;
const greaterThanOrEqualTo = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["j" /* GreaterThanOrEqualTo */](...args);
/* harmony export (immutable) */ __webpack_exports__["greaterThanOrEqualTo"] = greaterThanOrEqualTo;
const lessThan = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["k" /* LessThan */](...args);
/* harmony export (immutable) */ __webpack_exports__["lessThan"] = lessThan;
const lessThanOrEqualTo = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["l" /* LessThanOrEqualTo */](...args);
/* harmony export (immutable) */ __webpack_exports__["lessThanOrEqualTo"] = lessThanOrEqualTo;
const equals = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["b" /* Equals */](...args);
/* harmony export (immutable) */ __webpack_exports__["equals"] = equals;
const notEquals = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["m" /* NotEquals */](...args);
/* harmony export (immutable) */ __webpack_exports__["notEquals"] = notEquals;
const buckets = (...args) => new __WEBPACK_IMPORTED_MODULE_3__expressions_buckets__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["buckets"] = buckets;
const quantiles = (...args) => new __WEBPACK_IMPORTED_MODULE_24__expressions_quantiles__["b" /* Quantiles */](...args);
/* harmony export (immutable) */ __webpack_exports__["quantiles"] = quantiles;
const globalQuantiles = (...args) => new __WEBPACK_IMPORTED_MODULE_24__expressions_quantiles__["a" /* GlobalQuantiles */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalQuantiles"] = globalQuantiles;
const viewportMax = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["i" /* ViewportMax */](...args);
/* harmony export (immutable) */ __webpack_exports__["viewportMax"] = viewportMax;
const viewportMin = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["j" /* ViewportMin */](...args);
/* harmony export (immutable) */ __webpack_exports__["viewportMin"] = viewportMin;
const viewportAvg = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["g" /* ViewportAvg */](...args);
/* harmony export (immutable) */ __webpack_exports__["viewportAvg"] = viewportAvg;
const viewportSum = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["l" /* ViewportSum */](...args);
/* harmony export (immutable) */ __webpack_exports__["viewportSum"] = viewportSum;
const viewportCount = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["h" /* ViewportCount */](...args);
/* harmony export (immutable) */ __webpack_exports__["viewportCount"] = viewportCount;
const viewportPercentile = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["k" /* ViewportPercentile */](...args);
/* harmony export (immutable) */ __webpack_exports__["viewportPercentile"] = viewportPercentile;
const globalPercentile = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["e" /* GlobalPercentile */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalPercentile"] = globalPercentile;
const globalMax = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["c" /* GlobalMax */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalMax"] = globalMax;
const globalMin = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["d" /* GlobalMin */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalMin"] = globalMin;
const globalAvg = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["a" /* GlobalAvg */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalAvg"] = globalAvg;
const globalSum = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["f" /* GlobalSum */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalSum"] = globalSum;
const globalCount = (...args) => new __WEBPACK_IMPORTED_MODULE_26__expressions_viewportAggregation__["b" /* GlobalCount */](...args);
/* harmony export (immutable) */ __webpack_exports__["globalCount"] = globalCount;
const inverse = (...args) => new __WEBPACK_IMPORTED_MODULE_0__expressions_palettes__["a" /* Inverse */](...args);
/* harmony export (immutable) */ __webpack_exports__["inverse"] = inverse;
const floatConstant = (...args) => new __WEBPACK_IMPORTED_MODULE_6__expressions_floatConstant__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["floatConstant"] = floatConstant;
const TRUE = new __WEBPACK_IMPORTED_MODULE_6__expressions_floatConstant__["a" /* default */](1);
/* harmony export (immutable) */ __webpack_exports__["TRUE"] = TRUE;
const FALSE = new __WEBPACK_IMPORTED_MODULE_6__expressions_floatConstant__["a" /* default */](0);
/* harmony export (immutable) */ __webpack_exports__["FALSE"] = FALSE;
const and = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["a" /* And */](...args);
/* harmony export (immutable) */ __webpack_exports__["and"] = and;
const or = (...args) => new __WEBPACK_IMPORTED_MODULE_22__expressions_binary__["n" /* Or */](...args);
/* harmony export (immutable) */ __webpack_exports__["or"] = or;
const not = (...args) => new __WEBPACK_IMPORTED_MODULE_21__expressions_unary__["d" /* Not */](...args);
/* harmony export (immutable) */ __webpack_exports__["not"] = not;
const gt = greaterThan;
/* harmony export (immutable) */ __webpack_exports__["gt"] = gt;
const gte = greaterThanOrEqualTo;
/* harmony export (immutable) */ __webpack_exports__["gte"] = gte;
const lt = lessThan;
/* harmony export (immutable) */ __webpack_exports__["lt"] = lt;
const lte = lessThanOrEqualTo;
/* harmony export (immutable) */ __webpack_exports__["lte"] = lte;
const _in = (...args) => new __WEBPACK_IMPORTED_MODULE_19__expressions_belongs_js__["a" /* In */](...args);
const eq = equals;
/* harmony export (immutable) */ __webpack_exports__["eq"] = eq;
const neq = notEquals;
/* harmony export (immutable) */ __webpack_exports__["neq"] = neq;
const nin = (...args) => new __WEBPACK_IMPORTED_MODULE_19__expressions_belongs_js__["b" /* Nin */](...args);
/* harmony export (immutable) */ __webpack_exports__["nin"] = nin;
const between = (...args) => new __WEBPACK_IMPORTED_MODULE_20__expressions_between__["a" /* default */](...args);
/* harmony export (immutable) */ __webpack_exports__["between"] = between;
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__functions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__expression__ = __webpack_require__(0);
// Binary ops
const FloatMul = genBinaryOp((x, y) => x * y, (x, y) => `(${x} * ${y})`);
/* harmony export (immutable) */ __webpack_exports__["f"] = FloatMul;
const FloatDiv = genBinaryOp((x, y) => x / y, (x, y) => `(${x} / ${y})`);
/* harmony export (immutable) */ __webpack_exports__["d"] = FloatDiv;
const FloatAdd = genBinaryOp((x, y) => x + y, (x, y) => `(${x} + ${y})`);
/* harmony export (immutable) */ __webpack_exports__["c"] = FloatAdd;
const FloatSub = genBinaryOp((x, y) => x - y, (x, y) => `(${x} - ${y})`);
/* harmony export (immutable) */ __webpack_exports__["h"] = FloatSub;
const FloatMod = genBinaryOp((x, y) => x % y, (x, y) => `mod(${x}, ${y})`);
/* harmony export (immutable) */ __webpack_exports__["e"] = FloatMod;
const FloatPow = genBinaryOp((x, y) => Math.pow(x, y), (x, y) => `pow(${x}, ${y})`);
/* harmony export (immutable) */ __webpack_exports__["g"] = FloatPow;
const GreaterThan = genBinaryOp((x, y) => x > y ? 1 : 0, (x, y) => `(${x}>${y}? 1.:0.)`);
/* harmony export (immutable) */ __webpack_exports__["i"] = GreaterThan;
const GreaterThanOrEqualTo = genBinaryOp((x, y) => x >= y ? 1 : 0, (x, y) => `(${x}>=${y}? 1.:0.)`);
/* harmony export (immutable) */ __webpack_exports__["j"] = GreaterThanOrEqualTo;
const LessThan = genBinaryOp((x, y) => x < y ? 1 : 0, (x, y) => `(${x}<${y}? 1.:0.)`);
/* harmony export (immutable) */ __webpack_exports__["k"] = LessThan;
const LessThanOrEqualTo = genBinaryOp((x, y) => x <= y ? 1 : 0, (x, y) => `(${x}<=${y}? 1.:0.)`);
/* harmony export (immutable) */ __webpack_exports__["l"] = LessThanOrEqualTo;
const Equals = genBinaryOp((x, y) => x == y ? 1 : 0, (x, y) => `(${x}==${y}? 1.:0.)`);
/* harmony export (immutable) */ __webpack_exports__["b"] = Equals;
const NotEquals = genBinaryOp((x, y) => x != y ? 1 : 0, (x, y) => `(${x}!=${y}? 1.:0.)`);
/* harmony export (immutable) */ __webpack_exports__["m"] = NotEquals;
const Or = genBinaryOp((x, y) => Math.min(x + y, 1), (x, y) => `min(${x} + ${y}, 1.)`);
/* harmony export (immutable) */ __webpack_exports__["n"] = Or;
const And = genBinaryOp((x, y) => Math.min(x * y, 1), (x, y) => `min(${x} * ${y}, 1.)`);
/* harmony export (immutable) */ __webpack_exports__["a"] = And;
function genBinaryOp(jsFn, glsl) {
return class BinaryOperation extends __WEBPACK_IMPORTED_MODULE_2__expression__["a" /* default */] {
/**
* @jsapi
* @name BinaryOperation
* @hideconstructor
* @augments Expression
* @constructor
* @param {*} a
* @param {*} b
*/
constructor(a, b) {
if (Number.isFinite(a) && Number.isFinite(b)) {
return Object(__WEBPACK_IMPORTED_MODULE_0__functions__["float"])(jsFn(a, b));
}
a = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(a);
b = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(b);
if (typeof a === 'string') {
[a, b] = [b, a];
}
if (typeof b === 'string') {
super({ a: a, auxFloat: Object(__WEBPACK_IMPORTED_MODULE_0__functions__["float"])(0) });
this.b = b;
} else {
super({ a: a, b: b });
}
}
_compile(meta) {
super._compile(meta);
const [a, b] = [this.a, this.b];
this.inlineMaker = inline => glsl(inline.a, inline.b);
// TODO this logic is operation dependant
if (typeof b === 'string' && a.type == 'category' && a.name) {
const id = meta.categoryIDs[b];
this.auxFloat.expr = id;
this.type = 'float';
this.inlineMaker = inline => glsl(inline.a, inline.auxFloat);
} else if (a.type == 'float' && b.type == 'float') {
this.type = 'float';
} else if (a.type == 'color' && b.type == 'color') {
this.type = 'color';
} else if (a.type == 'color' && b.type == 'float') {
this.type = 'color';
} else if (a.type == 'category' && b.type == 'category') {
this.type = 'float';
} else {
throw new Error(`Binary operation cannot be performed between types '${a.type}' and '${b.type}'`);
}
}
};
}
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["b"] = implicitCast;
/* harmony export (immutable) */ __webpack_exports__["a"] = hexToRgb;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__functions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__expression__ = __webpack_require__(0);
// To support literals (string and numeric) out of the box we need to cast them implicitly on constructors
function implicitCast(value) {
if (Number.isFinite(value)) {
return Object(__WEBPACK_IMPORTED_MODULE_0__functions__["float"])(value);
}
if (typeof value == 'string') {
return Object(__WEBPACK_IMPORTED_MODULE_0__functions__["category"])(value);
}
if (!(value instanceof __WEBPACK_IMPORTED_MODULE_1__expression__["a" /* default */]) && value.type !== 'paletteGenerator' && value.type !== 'float') {
throw new Error('value cannot be casted');
}
return value;
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__expression__ = __webpack_require__(0);
const Log = genUnaryOp(x => Math.log(x), x => `log(${x})`);
/* harmony export (immutable) */ __webpack_exports__["c"] = Log;
const Sqrt = genUnaryOp(x => Math.sqrt(x), x => `sqrt(${x})`);
/* harmony export (immutable) */ __webpack_exports__["g"] = Sqrt;
const Sin = genUnaryOp(x => Math.sin(x), x => `sin(${x})`);
/* harmony export (immutable) */ __webpack_exports__["f"] = Sin;
const Cos = genUnaryOp(x => Math.cos(x), x => `cos(${x})`);
/* harmony export (immutable) */ __webpack_exports__["b"] = Cos;
const Tan = genUnaryOp(x => Math.tan(x), x => `tan(${x})`);
/* harmony export (immutable) */ __webpack_exports__["h"] = Tan;
const Sign = genUnaryOp(x => Math.sign(x), x => `sign(${x})`);
/* harmony export (immutable) */ __webpack_exports__["e"] = Sign;
const Abs = genUnaryOp(x => Math.abs(x), x => `abs(${x})`);
/* harmony export (immutable) */ __webpack_exports__["a"] = Abs;
const Not = genUnaryOp(x => 1 - x, x => `1.0 - ${x}`);
/* harmony export (immutable) */ __webpack_exports__["d"] = Not;
function genUnaryOp(jsFn, glsl) {
return class UnaryOperation extends __WEBPACK_IMPORTED_MODULE_1__expression__["a" /* default */] {
constructor(a) {
a = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(a);
super({ a: a });
}
_compile(meta) {
super._compile(meta);
if (this.a.type != 'float') {
throw new Error(`Binary operation cannot be performed to '${this.a.type}'`);
}
this.type = 'float';
this.inlineMaker = inlines => glsl(inlines.a);
}
};
}
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return WM_R; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return WM_2R; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return wmProjection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isUndefined; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isObject; });
/**
* Export util functions
*/
const DEG2RAD = Math.PI / 180;
const EARTH_RADIUS = 6378137;
const WM_R = EARTH_RADIUS * Math.PI; // Webmercator *radius*: half length Earth's circumference
const WM_2R = WM_R * 2; // Webmercator coordinate range (Earth's circumference)
// Webmercator projection
function wmProjection(latLng) {
let lat = latLng.lat * DEG2RAD;
let lng = latLng.lng * DEG2RAD;
let x = lng * EARTH_RADIUS;
let y = Math.log(Math.tan(lat / 2 + Math.PI / 4)) * EARTH_RADIUS;
return { x, y };
}
function isUndefined(value) {
return value === undefined;
}
function isString(value) {
return typeof value == 'string';
}
function isNumber(value) {
return typeof value == 'number';
}
function isObject(value) {
const type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__carto_error__ = __webpack_require__(77);
/**
* Utility to build a cartoError related to validation errors.
*
* @return {CartoError} A well formed object representing the error.
*/
class CartoValidationError extends __WEBPACK_IMPORTED_MODULE_0__carto_error__["a" /* CartoError */] {
constructor(type, message) {
super({
origin: 'validation',
type: type,
message: message
});
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = CartoValidationError;
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
// Aggregation ops
const Max = genAggregationOp('max');
/* harmony export (immutable) */ __webpack_exports__["b"] = Max;
const Min = genAggregationOp('min');
/* harmony export (immutable) */ __webpack_exports__["c"] = Min;
const Avg = genAggregationOp('avg');
/* harmony export (immutable) */ __webpack_exports__["a"] = Avg;
const Sum = genAggregationOp('sum');
/* harmony export (immutable) */ __webpack_exports__["e"] = Sum;
const Mode = genAggregationOp('mode');
/* harmony export (immutable) */ __webpack_exports__["d"] = Mode;
function genAggregationOp(aggName) {
return class AggregationOperation extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(property) {
super({ property: property });
}
get name() {
return this.property.name;
}
get numCategories() {
return this.property.numCategories;
}
//Override super methods, we don't want to let the property use the raw column, we must use the agg suffixed one
_compile(metadata) {
super._compile(metadata);
this.type = this.property.type;
}
_applyToShaderSource(uniformIDMaker, propertyTIDMaker) {
return {
preface: '',
inline: `p${propertyTIDMaker(`_cdb_agg_${aggName}_${this.property.name}`)}`
};
}
_postShaderCompile() { }
_getMinimumNeededSchema() {
return {
columns: [
`_cdb_agg_${aggName}_${this.property.name}`
]
};
}
};
}
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Renderer; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__shaders__ = __webpack_require__(20);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__schema__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__dataframe__ = __webpack_require__(59);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__style_functions__ = __webpack_require__(1);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_2__dataframe__["a"]; });
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_1__schema__; });
const HISTOGRAM_BUCKETS = 1000;
/**
* @typedef {object} RPoint - Point in renderer coordinates space
* @property {number} x
* @property {number} y
*/
/**
* @description The Render To Texture Width limits the maximum number of features per tile: *maxFeatureCount = RTT_WIDTH^2*
*
* Large RTT_WIDTH values are unsupported by hardware. Limits vary on each machine.
* Support starts to drop from 2048, with a drastic reduction in support for more than 4096 pixels.
*
* Large values imply a small overhead too.
*/
const RTT_WIDTH = 1024;
/**
* @description Renderer constructor. Use it to create a new renderer bound to the provided canvas.
* Initialization will be done synchronously.
* The function will fail in case that a WebGL context cannot be created this can happen because of the following reasons:
* * The provided canvas element is invalid
* * The browser or the machine doesn't support WebGL or the required WebGL extension and minimum parameter values
* @jsapi
* @memberOf renderer
* @constructor
* @param {HTMLElement} canvas - the WebGL context will be created on this element
*/
class Renderer {
constructor(canvas) {
if (canvas) {
this.gl = canvas.getContext('webgl');
if (!this.gl) {
throw new Error('WebGL 1 is unsupported');
}
this._initGL(this.gl);
}
this._center = { x: 0, y: 0 };
this._zoom = 1;
this.RTT_WIDTH = RTT_WIDTH;
console.log('R', this);
this.dataframes = [];
}
_initGL(gl) {
this.gl = gl;
const OES_texture_float = gl.getExtension('OES_texture_float');
if (!OES_texture_float) {
throw new Error('WebGL extension OES_texture_float is unsupported');
}
const supportedRTT = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE);
if (supportedRTT < RTT_WIDTH) {
throw new Error(`WebGL parameter 'gl.MAX_RENDERBUFFER_SIZE' is below the requirement: ${supportedRTT} < ${RTT_WIDTH}`);
}
this._initShaders();
this.auxFB = gl.createFramebuffer();
// Create a VBO that covers the entire screen
// Use a "big" triangle instead of a square for performance and simplicity
this.bigTriangleVBO = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.bigTriangleVBO);
var vertices = [
10.0, -10.0,
0.0, 10.0,
-10.0, -10.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Create a 1x1 RGBA texture set to [0,0,0,0]
// Needed because sometimes we don't really use some textures within the shader, but they are declared anyway.
this.zeroTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.zeroTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
new Uint8Array(4));
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.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
this._AATex = gl.createTexture();
this._AAFB = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindTexture(gl.TEXTURE_2D, this.zeroTex);
}
/**
* Get Renderer visualization center
* @return {RPoint}
*/
getCenter() {
return { x: this._center.x, y: this._center.y };
}
/**
* Set Renderer visualization center
* @param {number} x
* @param {number} y
*/
setCenter(x, y) {
this._center.x = x;
this._center.y = y;
}
/**
* Get Renderer visualization bounds
* @return {*}
*/
getBounds() {
const center = this.getCenter();
const sx = this.getZoom() * this.getAspect();
const sy = this.getZoom();
return [center.x - sx, center.y - sy, center.x + sx, center.y + sy];
}
/**
* Get Renderer visualization zoom
* @return {number}
*/
getZoom() {
return this._zoom;
}
/**
* Set Renderer visualization zoom
* @param {number} zoom
*/
setZoom(zoom) {
this._zoom = zoom;
}
/**
* Removes a dataframe for the renderer. Freeing its resources.
* @param {*} tile
*/
removeDataframe(dataframe) {
this.dataframes = this.dataframes.filter(t => t !== dataframe);
}
/**
* @description Adds a new dataframe to the renderer.
*
* Performance-intensive. The required allocation and copy of resources will happen synchronously.
* To achieve good performance, avoid multiple calls within the same event, particularly with large dataframes.
* @param {Dataframe} dataframe
* @returns {BoundDataframe}
*/
addDataframe(dataframe) {
dataframe.bind(this);
this.dataframes.push(dataframe);
}
getAspect() {
if (this.gl) {
return this.gl.canvas.clientWidth / this.gl.canvas.clientHeight;
}
return 1;
}
getStyledTiles() {
return this.dataframes.filter(tile => tile.style && tile.visible && tile.style.colorShader);
}
_computeDrawMetadata() {
const aspect = this.gl.canvas.clientWidth / this.gl.canvas.clientHeight;
const tiles = this.getStyledTiles();
let drawMetadata = {
freeTexUnit: 4,
zoom: 1. / this._zoom,
columns: []
};
let requiredColumns = tiles.map(d => {
const colorRequirements = d.style.getColor()._getDrawMetadataRequirements();
const widthRequirements = d.style.getWidth()._getDrawMetadataRequirements();
const strokeColorRequirements = d.style.getStrokeColor()._getDrawMetadataRequirements();
const strokeWidthRequirements = d.style.getStrokeWidth()._getDrawMetadataRequirements();
const filterRequirements = d.style.filter._getDrawMetadataRequirements();
return [widthRequirements, colorRequirements, strokeColorRequirements, strokeWidthRequirements, filterRequirements].
reduce(__WEBPACK_IMPORTED_MODULE_1__schema__["union"], __WEBPACK_IMPORTED_MODULE_1__schema__["IDENTITY"]);
}).reduce(__WEBPACK_IMPORTED_MODULE_1__schema__["union"], __WEBPACK_IMPORTED_MODULE_1__schema__["IDENTITY"]).columns;
requiredColumns.map(column => {
drawMetadata.columns.push(
{
name: column,
min: Number.POSITIVE_INFINITY,
max: Number.NEGATIVE_INFINITY,
avg: undefined,
count: 0,
sum: 0,
histogramBuckets: HISTOGRAM_BUCKETS,
histogram: Array.from({ length: HISTOGRAM_BUCKETS }, () => 0),
accumHistogram: Array.from({ length: HISTOGRAM_BUCKETS }, () => 0),
}
);
});
const s = 1. / this._zoom;
tiles.map(d => {
requiredColumns.map(column => {
const values = d.properties[column];
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
let sum = 0;
let count = 0;
d.vertexScale = [(s / aspect) * d.scale, s * d.scale];
d.vertexOffset = [(s / aspect) * (this._center.x - d.center.x), s * (this._center.y - d.center.y)];
const minx = (-1 + d.vertexOffset[0]) / d.vertexScale[0];
const maxx = (1 + d.vertexOffset[0]) / d.vertexScale[0];
const miny = (-1 + d.vertexOffset[1]) / d.vertexScale[1];
const maxy = (1 + d.vertexOffset[1]) / d.vertexScale[1];
for (let i = 0; i < d.numFeatures; i++) {
const x = d.geom[2 * i + 0];
const y = d.geom[2 * i + 1];
if (x > minx && x < maxx && y > miny && y < maxy) {
const v = values[i];
if (!Number.isFinite(v)) {
continue;
}
sum += v;
min = Math.min(min, v);
max = Math.max(max, v);
count++;
}
}
const metaColumn = drawMetadata.columns.find(c => c.name == column);
metaColumn.min = Math.min(min, metaColumn.min);
metaColumn.max = Math.max(max, metaColumn.max);
metaColumn.count += count;
metaColumn.sum += sum;
});
});
requiredColumns.map(column => {
const metaColumn = drawMetadata.columns.find(c => c.name == column);
metaColumn.avg = metaColumn.sum / metaColumn.count;
});
tiles.map(d => {
requiredColumns.map(column => {
const values = d.properties[column];
const metaColumn = drawMetadata.columns.find(c => c.name == column);
d.vertexScale = [(s / aspect) * d.scale, s * d.scale];
d.vertexOffset = [(s / aspect) * (this._center.x - d.center.x), s * (this._center.y - d.center.y)];
const minx = (-1 + d.vertexOffset[0]) / d.vertexScale[0];
const maxx = (1 + d.vertexOffset[0]) / d.vertexScale[0];
const miny = (-1 + d.vertexOffset[1]) / d.vertexScale[1];
const maxy = (1 + d.vertexOffset[1]) / d.vertexScale[1];
const vmin = metaColumn.min;
const vmax = metaColumn.max;
const vdiff = vmax - vmin;
for (let i = 0; i < d.numFeatures; i++) {
const x = d.geom[2 * i + 0];
const y = d.geom[2 * i + 1];
if (x > minx && x < maxx && y > miny && y < maxy) {
const v = values[i];
if (!Number.isFinite(v)) {
continue;
}
metaColumn.histogram[Math.ceil(999 * (v - vmin) / vdiff)]++;
}
}
});
});
requiredColumns.map(column => {
const metaColumn = drawMetadata.columns.find(c => c.name == column);
for (let i = 1; i < metaColumn.histogramBuckets; i++) {
metaColumn.accumHistogram[i] = metaColumn.accumHistogram[i - 1] + metaColumn.histogram[i];
}
});
return drawMetadata;
}
refresh(timestamp) {
const gl = this.gl;
// Don't re-render more than once per animation frame
if (this.lastFrame === timestamp) {
return;
}
var width = gl.canvas.clientWidth;
var height = gl.canvas.clientHeight;
if (gl.canvas.width != width ||
gl.canvas.height != height) {
gl.canvas.width = width;
gl.canvas.height = height;
}
var aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
gl.enable(gl.CULL_FACE);
gl.disable(gl.BLEND);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.STENCIL_TEST);
gl.depthMask(false);
gl.bindFramebuffer(gl.FRAMEBUFFER, this.auxFB);
const tiles = this.getStyledTiles();
const drawMetadata = this._computeDrawMetadata();
const styleTile = (tile, tileTexture, shader, styleExpr, TID) => {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tileTexture, 0);
gl.viewport(0, 0, RTT_WIDTH, tile.height);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(shader.program);
for (let i = 0; i < 16; i++) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, this.zeroTex);
gl.uniform1i(shader.textureLocations[i], 0);
}
drawMetadata.freeTexUnit = 4;
styleExpr._preDraw(drawMetadata, gl);
Object.keys(TID).forEach((name, i) => {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, tile.propertyTex[tile.propertyID[name]]);
gl.uniform1i(shader.textureLocations[i], i);
});
gl.enableVertexAttribArray(shader.vertexAttribute);
gl.bindBuffer(gl.ARRAY_BUFFER, this.bigTriangleVBO);
gl.vertexAttribPointer(shader.vertexAttribute, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.disableVertexAttribArray(shader.vertexAttribute);
};
tiles.map(tile => styleTile(tile, tile.texColor, tile.style.colorShader, tile.style.getColor(), tile.style.propertyColorTID));
tiles.map(tile => styleTile(tile, tile.texWidth, tile.style.widthShader, tile.style.getWidth(), tile.style.propertyWidthTID));
tiles.map(tile => styleTile(tile, tile.texStrokeColor, tile.style.strokeColorShader, tile.style.getStrokeColor(), tile.style.propertyStrokeColorTID));
tiles.map(tile => styleTile(tile, tile.texStrokeWidth, tile.style.strokeWidthShader, tile.style.getStrokeWidth(), tile.style.propertyStrokeWidthTID));
tiles.map(tile => styleTile(tile, tile.texFilter, tile.style.filterShader, tile.style.filter, tile.style.propertyFilterTID));
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
if (tiles.length && tiles[0].type != 'point') {
gl.bindFramebuffer(gl.FRAMEBUFFER, this._AAFB);
const [w, h] = [gl.drawingBufferWidth, gl.drawingBufferHeight];
if (w != this._width || h != this._height) {
gl.bindTexture(gl.TEXTURE_2D, this._AATex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
w * 2, h * 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
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);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._AATex, 0);
[this._width, this._height] = [w, h];
}
gl.viewport(0, 0, w * 2, h * 2);
gl.clear(gl.COLOR_BUFFER_BIT);
}
const s = 1. / this._zoom;
const { orderingMins, orderingMaxs } = getOrderingRenderBuckets(tiles);
const renderDrawPass = orderingIndex => tiles.forEach(tile => {
let renderer = null;
if (tile.type == 'point') {
renderer = this.finalRendererProgram;
} else if (tile.type == 'line') {
renderer = this.lineRendererProgram;
} else {
renderer = this.triRendererProgram;
}
gl.useProgram(renderer.program);
//Set filtering condition on "... AND feature is in current order bucket"
gl.uniform1f(renderer.orderMinWidth, orderingMins[orderingIndex]);
gl.uniform1f(renderer.orderMaxWidth, orderingMaxs[orderingIndex]);
gl.uniform2f(renderer.vertexScaleUniformLocation,
(s / aspect) * tile.scale,
s * tile.scale);
gl.uniform2f(renderer.vertexOffsetUniformLocation,
(s / aspect) * (this._center.x - tile.center.x),
s * (this._center.y - tile.center.y));
tile.vertexScale = [(s / aspect) * tile.scale, s * tile.scale];
tile.vertexOffset = [(s / aspect) * (this._center.x - tile.center.x), s * (this._center.y - tile.center.y)];
gl.enableVertexAttribArray(renderer.vertexPositionAttribute);
gl.bindBuffer(gl.ARRAY_BUFFER, tile.vertexBuffer);
gl.vertexAttribPointer(renderer.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(renderer.featureIdAttr);
gl.bindBuffer(gl.ARRAY_BUFFER, tile.featureIDBuffer);
gl.vertexAttribPointer(renderer.featureIdAttr, 2, gl.FLOAT, false, 0, 0);
if (tile.type == 'line') {
gl.enableVertexAttribArray(renderer.normalAttr);
gl.bindBuffer(gl.ARRAY_BUFFER, tile.normalBuffer);
gl.vertexAttribPointer(renderer.normalAttr, 2, gl.FLOAT, false, 0, 0);
}
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tile.texColor);
gl.uniform1i(renderer.colorTexture, 0);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, tile.texWidth);
gl.uniform1i(renderer.widthTexture, 1);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, tile.texFilter);
gl.uniform1i(renderer.filterTexture, 2);
if (tile.type == 'point') {
// Lines and polygons don't support stroke
gl.activeTexture(gl.TEXTURE3);
gl.bindTexture(gl.TEXTURE_2D, tile.texStrokeColor);
gl.uniform1i(renderer.colorStrokeTexture, 3);
gl.activeTexture(gl.TEXTURE4);
gl.bindTexture(gl.TEXTURE_2D, tile.texStrokeWidth);
gl.uniform1i(renderer.strokeWidthTexture, 4);
}
gl.drawArrays(tile.type == 'point' ? gl.POINTS : gl.TRIANGLES, 0, tile.numVertex);
gl.disableVertexAttribArray(renderer.vertexPositionAttribute);
gl.disableVertexAttribArray(renderer.featureIdAttr);
if (tile.type == 'line') {
gl.disableVertexAttribArray(renderer.normalAttr);
}
});
orderingMins.map((_, orderingIndex) => {
renderDrawPass(orderingIndex);
});
if (tiles.length && tiles[0].type != 'point') {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.useProgram(this._aaBlendShader.program);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this._AATex);
gl.uniform1i(this._aaBlendShader.readTU, 0);
gl.enableVertexAttribArray(this._aaBlendShader.vertexAttribute);
gl.bindBuffer(gl.ARRAY_BUFFER, this.bigTriangleVBO);
gl.vertexAttribPointer(this._aaBlendShader.vertexAttribute, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.disableVertexAttribArray(this._aaBlendShader.vertexAttribute);
}
gl.disable(gl.CULL_FACE);
}
/**
* Initialize static shaders
*/
_initShaders() {
this.finalRendererProgram = __WEBPACK_IMPORTED_MODULE_0__shaders__["b" /* renderer */].createPointShader(this.gl);
this.triRendererProgram = __WEBPACK_IMPORTED_MODULE_0__shaders__["b" /* renderer */].createTriShader(this.gl);
this.lineRendererProgram = __WEBPACK_IMPORTED_MODULE_0__shaders__["b" /* renderer */].createLineShader(this.gl);
this._aaBlendShader = new __WEBPACK_IMPORTED_MODULE_0__shaders__["a" /* AABlender */](this.gl);
}
}
function getOrderingRenderBuckets(tiles) {
let orderer = null;
if (tiles.length > 0) {
orderer = tiles[0].style.getOrder();
}
let orderingMins = [0];
let orderingMaxs = [1000];
if (orderer instanceof __WEBPACK_IMPORTED_MODULE_3__style_functions__["Asc"]) {
orderingMins = Array.from({ length: 16 }, (_, i) => (15 - i) * 2);
orderingMaxs = Array.from({ length: 16 }, (_, i) => i == 0 ? 1000 : (15 - i + 1) * 2);
} else if (orderer instanceof __WEBPACK_IMPORTED_MODULE_3__style_functions__["Desc"]) {
orderingMins = Array.from({ length: 16 }, (_, i) => i * 2);
orderingMaxs = Array.from({ length: 16 }, (_, i) => i == 15 ? 1000 : (i + 1) * 2);
}
return {
orderingMins,
orderingMaxs
};
}
/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
//TODO refactor to use uniformfloat class
class Animate extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @description Animate returns a number from zero to one based on the elapsed number of milliseconds since the style was instantiated.
* The animation is not cyclic. It will stick to one once the elapsed number of milliseconds reach the animation's duration.
* @param {*} duration animation duration in milliseconds
*/
constructor(duration) {
if (!Number.isFinite(duration)) {
throw new Error('Animate only supports number literals');
}
super({});
this.aTime = Date.now();
this.bTime = this.aTime + Number(duration);
}
_compile() {
this.type = 'float';
}
_applyToShaderSource(uniformIDMaker) {
this._uniformID = uniformIDMaker();
return {
preface: `uniform float anim${this._uniformID};\n`,
inline: `anim${this._uniformID}`
};
}
_postShaderCompile(program, gl) {
this._uniformLocation = gl.getUniformLocation(program, `anim${this._uniformID}`);
}
_preDraw(drawMetadata, gl) {
const time = Date.now();
this.mix = (time - this.aTime) / (this.bTime - this.aTime);
if (this.mix > 1.) {
gl.uniform1f(this._uniformLocation, 1);
} else {
gl.uniform1f(this._uniformLocation, this.mix);
}
}
isAnimated() {
return !this.mix || this.mix <= 1.;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Animate;
/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (immutable) */ __webpack_exports__["union"] = union;
/* harmony export (immutable) */ __webpack_exports__["equals"] = equals;
// The IDENTITY schema contains zero columns, and it has two interesting properties:
// union(a,IDENTITY)=union(IDENTITY, a)=a
// contains(x, IDENTITY)=true (for x = valid schema)
const IDENTITY = {
columns: []
};
/* harmony export (immutable) */ __webpack_exports__["IDENTITY"] = IDENTITY;
/*
const schema = {
columns: ['temp', 'cat']
};*/
//TODO
// Returns true if subsetSchema is a contained by supersetSchema
// A schema A is contained by the schema B when all columns of A are present in B and
// all aggregations in A are present in B, if a column is not aggregated in A, it must
// be not aggregated in B
//export function contains(supersetSchema, subsetSchema) {
//}
// Returns the union of a and b schemas
// The union of two schemas is a schema with all the properties in both schemas and with their
// aggregtions set to the union of both aggregation sets, or null if a property aggregation is null in both schemas
// The union is not defined when one schema set the aggregation of one column and the other schema left the aggregation
// to null. In this case the function will throw an exception.
function union(a, b) {
const t = a.columns.concat(b.columns);
return {
columns: t.filter((item, pos) => t.indexOf(item) == pos)
};
}
function equals(a,b){
if (!a || !b){
return false;
}
return a.columns.length==b.columns.length && a.columns.every((v,i)=> v === b.columns[i]);
}
/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
class Base {
/**
* Base data source object.
*
* The methods listed in the {@link carto.source.Base|source.Base} object are availiable in all source objects.
*
* Use a source to reference the data used in a {@link carto.layer.Base|layer}.
*
* {@link carto.source.Base} should not be used directly use {@link carto.source.Dataset}, {@link carto.source.SQL} of {@link carto.source.GeoJSON} instead.
*
*
* @constructor Base
* @abstract
* @memberof carto.source
* @api
*/
constructor() {
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Base;
/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__animate__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__expression__ = __webpack_require__(0);
class Blend extends __WEBPACK_IMPORTED_MODULE_2__expression__["a" /* default */] {
/**
* @description Interpolate from *a* to *b* based on *mix*
* @param {*} a can be a color or a number
* @param {*} b type must match a's type
* @param {*} mix interpolation parameter in the [0,1] range
*/
constructor(a, b, mix, interpolator) {
a = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(a);
b = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(b);
mix = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(mix);
const originalMix = mix;
if (interpolator) {
mix = interpolator(mix);
}
super({ a: a, b: b, mix: mix });
this.originalMix = originalMix;
}
_compile(meta) {
super._compile(meta);
if (this.mix.type != 'float') {
throw new Error(`Blending cannot be performed by '${this.mix.type}'`);
}
if (this.a.type == 'float' && this.b.type == 'float') {
this.type = 'float';
} else if (this.a.type == 'color' && this.b.type == 'color') {
this.type = 'color';
} else {
throw new Error(`Blending cannot be performed between types '${this.a.type}' and '${this.b.type}'`);
}
this.inlineMaker = inline => `mix(${inline.a}, ${inline.b}, clamp(${inline.mix}, 0., 1.))`;
}
_preDraw(...args) {
super._preDraw(...args);
if (this.originalMix instanceof __WEBPACK_IMPORTED_MODULE_1__animate__["a" /* default */] && !this.originalMix.isAnimated()) {
this.parent._replaceChild(this, this.b);
this.notify();
}
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Blend;
/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class Float extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @param {*} x
*/
constructor(x) {
if (!Number.isFinite(x)) {
throw new Error(`Invalid arguments to Float(): ${x}`);
}
super({});
this.expr = x;
this.type = 'float';
}
_applyToShaderSource(uniformIDMaker) {
this._uniformID = uniformIDMaker();
return {
preface: `uniform float float${this._uniformID};\n`,
inline: `float${this._uniformID}`
};
}
_postShaderCompile(program, gl) {
this._uniformLocation = gl.getUniformLocation(program, `float${this._uniformID}`);
}
_preDraw(drawMetadata, gl) {
gl.uniform1f(this._uniformLocation, this.expr);
}
isAnimated() {
return false;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Float;
/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class FloatConstant extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @param {*} x
*/
constructor(x) {
if (!Number.isFinite(x)) {
throw new Error(`Invalid arguments to Float(): ${x}`);
}
super({});
this.expr = x;
this.type = 'float';
this.inlineMaker = ()=> `(${x.toFixed(20)})`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = FloatConstant;
/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class Category extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @param {*} x
*/
constructor(x) {
if (typeof x !== 'string') {
throw new Error(`Invalid arguments to Category(): ${x}`);
}
super({});
this.expr = x;
}
_compile(metadata) {
this.type = 'category';
this._metadata = metadata;
}
_applyToShaderSource(uniformIDMaker) {
this._uniformID = uniformIDMaker();
return {
preface: `uniform float cat${this._uniformID};\n`,
inline: `cat${this._uniformID}`
};
}
_postShaderCompile(program, gl) {
this._uniformLocation = gl.getUniformLocation(program, `cat${this._uniformID}`);
}
_preDraw(drawMetadata, gl) {
const id = this._metadata.categoryIDs[this.expr];
gl.uniform1f(this._uniformLocation, id);
}
isAnimated() {
return false;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Category;
/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class Property extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @param {*} name Property/column name
*/
constructor(name) {
if (typeof name !== 'string' || name == '') {
throw new Error(`Invalid property name '${name}'`);
}
super({});
this.name = name;
}
_compile(meta) {
const metaColumn = meta.columns.find(c => c.name == this.name);
if (!metaColumn) {
throw new Error(`Property '${this.name}' does not exist`);
}
this.type = metaColumn.type;
if (this.type == 'category') {
this.numCategories = metaColumn.categoryNames.length;
}
super._setGenericGLSL((childInlines, uniformIDMaker, propertyTIDMaker) => `p${propertyTIDMaker(this.name)}`);
}
_getMinimumNeededSchema() {
return {
columns: [
this.name
]
};
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Property;
/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__expression__ = __webpack_require__(0);
function IN_INLINE_MAKER(categories) {
return inline => `(${categories.map((cat, index) => `(${inline.property} == ${inline[`arg${index}`]})`).join(' || ')})? 1.: 0.`;
}
function NIN_INLINE_MAKER(categories) {
return inline => `(${categories.map((cat, index) => `(${inline.property} != ${inline[`arg${index}`]})`).join(' && ')})? 1.: 0.`;
}
/**
* Check if property belongs to the acceptedCategories list of categories
* @param {*} property
* @param {*} acceptedCategories
* @memberof carto.style.expressions
* @name in
* @api
*/
const In = generateBelongsExpression(IN_INLINE_MAKER);
/* harmony export (immutable) */ __webpack_exports__["a"] = In;
/**
* Check if property does not belong to the categories list of categories
* @param {*} property
* @param {*} categories
* @memberof carto.style.expressions
* @name nin
* @api
*/
const Nin = generateBelongsExpression(NIN_INLINE_MAKER);
/* harmony export (immutable) */ __webpack_exports__["b"] = Nin;
function generateBelongsExpression(inlineMaker) {
return class BelongExpression extends __WEBPACK_IMPORTED_MODULE_1__expression__["a" /* default */] {
constructor(property, ...categories) {
categories = categories.map(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */]);
let children = {
property
};
categories.map((arg, index) => children[`arg${index}`] = arg);
super(children);
this.categories = categories;
this.inlineMaker = inlineMaker(this.categories);
}
_compile(meta) {
super._compile(meta);
if (this.property.type != 'category') {
throw new Error('In() can only be performed to categorical properties');
}
this.categories.map(cat => {
if (cat.type != 'category') {
throw new Error('In() can only be performed to categorical properties');
}
});
this.type = 'float';
}
};
}
/***/ }),
/* 18 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/**
* Check if a given value belongs to an inclusive range (including limits).
*/
class Between extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(value, lowerLimit, upperLimit) {
super({ value, lowerLimit, upperLimit });
this.type = 'float';
}
_compile(meta) {
super._compile(meta);
if (this.value.type != 'float') {
throw new Error('Between() can only be performed to float properties');
}
if (this.lowerLimit.type != 'float') {
throw new Error('Between() can only be performed to float properties');
}
if (this.upperLimit.type != 'float') {
throw new Error('Between() can only be performed to float properties');
}
this.inlineMaker = inline => `((${inline.value} >= ${inline.lowerLimit} && ${inline.value} <= ${inline.upperLimit}) ? 1. : 0.)`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Between;
/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__expression__ = __webpack_require__(0);
class ILinear extends genInterpolator(inner => inner) { }
/* harmony export (immutable) */ __webpack_exports__["b"] = ILinear;
class BounceEaseIn extends genInterpolator(inner => `BounceEaseIn(${inner})`,
`
#ifndef BOUNCE_EASE_IN
#define BOUNCE_EASE_IN
float BounceEaseIn_BounceEaseOut(float p)
{
if(p < 4./11.0)
{
return (121. * p * p)/16.0;
}
else if(p < 8./11.0)
{
return (363./40.0 * p * p) - (99./10.0 * p) + 17./5.0;
}
else if(p < 9./10.0)
{
return (4356./361.0 * p * p) - (35442./1805.0 * p) + 16061./1805.0;
}
else
{
return (54./5.0 * p * p) - (513./25.0 * p) + 268./25.0;
}
}
float BounceEaseIn(float p)
{
return 1. - BounceEaseOut(1. - p);
}
#endif
`) { }
/* unused harmony export BounceEaseIn */
class Cubic extends genInterpolator(inner => `cubicEaseInOut(${inner})`,
`
#ifndef CUBIC
#define CUBIC
float cubicEaseInOut(float p){
if (p < 0.5) {
return 4. * p * p * p;
}else {
float f = ((2. * p) - 2.);
return 0.5 * f * f * f + 1.;
}
}
#endif
`) { }
/* harmony export (immutable) */ __webpack_exports__["a"] = Cubic;
// Interpolators
function genInterpolator(inlineMaker, preface) {
const fn = class Interpolator extends __WEBPACK_IMPORTED_MODULE_1__expression__["a" /* default */] {
constructor(m) {
m = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* implicitCast */])(m);
super({ m: m });
}
_compile(meta) {
super._compile(meta);
if (this.m.type != 'float') {
throw new Error(`Blending cannot be performed by '${this.m.type}'`);
}
this.type = 'float';
this._setGenericGLSL(inline => inlineMaker(inline.m), preface);
}
};
fn.type = 'interpolator';
return fn;
}
/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return renderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return styler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AABlender; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__renderer__ = __webpack_require__(52);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__styler__ = __webpack_require__(56);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__aaBlender__ = __webpack_require__(57);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__shader_cache__ = __webpack_require__(58);
const NUM_TEXTURE_LOCATIONS = 4;
const shaderCache = new __WEBPACK_IMPORTED_MODULE_3__shader_cache__["a" /* default */]();
function compileShader(gl, sourceCode, type) {
if (shaderCache.has(gl, sourceCode)) {
return shaderCache.get(gl, sourceCode);
}
const shader = gl.createShader(type);
gl.shaderSource(shader, sourceCode);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error('An error occurred compiling the shaders: ' + log + '\nSource:\n' + sourceCode);
}
shaderCache.set(gl, sourceCode, shader);
return shader;
}
function compileProgram(gl, glslVS, glslFS) {
const VS = compileShader(gl, glslVS, gl.VERTEX_SHADER);
const FS = compileShader(gl, glslFS, gl.FRAGMENT_SHADER);
this.program = gl.createProgram();
gl.attachShader(this.program, VS);
gl.attachShader(this.program, FS);
gl.linkProgram(this.program);
gl.deleteShader(VS);
gl.deleteShader(FS);
if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
throw new Error('Unable to link the shader program: ' + gl.getProgramInfoLog(this.program));
}
}
class AABlender {
constructor(gl) {
compileProgram.call(this, gl, __WEBPACK_IMPORTED_MODULE_2__aaBlender__["b" /* VS */], __WEBPACK_IMPORTED_MODULE_2__aaBlender__["a" /* FS */]);
this.vertexAttribute = gl.getAttribLocation(this.program, 'vertex');
this.readTU = gl.getUniformLocation(this.program, 'aaTex');
}
}
class Point {
constructor(gl) {
compileProgram.call(this, gl, __WEBPACK_IMPORTED_MODULE_0__renderer__["b" /* point */].VS, __WEBPACK_IMPORTED_MODULE_0__renderer__["b" /* point */].FS);
this.vertexPositionAttribute = gl.getAttribLocation(this.program, 'vertexPosition');
this.featureIdAttr = gl.getAttribLocation(this.program, 'featureID');
this.vertexScaleUniformLocation = gl.getUniformLocation(this.program, 'vertexScale');
this.vertexOffsetUniformLocation = gl.getUniformLocation(this.program, 'vertexOffset');
this.colorTexture = gl.getUniformLocation(this.program, 'colorTex');
this.colorStrokeTexture = gl.getUniformLocation(this.program, 'colorStrokeTex');
this.strokeWidthTexture = gl.getUniformLocation(this.program, 'strokeWidthTex');
this.widthTexture = gl.getUniformLocation(this.program, 'widthTex');
this.orderMinWidth = gl.getUniformLocation(this.program, 'orderMinWidth');
this.orderMaxWidth = gl.getUniformLocation(this.program, 'orderMaxWidth');
this.filterTexture = gl.getUniformLocation(this.program, 'filterTex');
}
}
class Tri {
constructor(gl) {
compileProgram.call(this, gl, __WEBPACK_IMPORTED_MODULE_0__renderer__["c" /* tris */].VS, __WEBPACK_IMPORTED_MODULE_0__renderer__["c" /* tris */].FS);
this.vertexPositionAttribute = gl.getAttribLocation(this.program, 'vertexPosition');
this.featureIdAttr = gl.getAttribLocation(this.program, 'featureID');
this.vertexScaleUniformLocation = gl.getUniformLocation(this.program, 'vertexScale');
this.vertexOffsetUniformLocation = gl.getUniformLocation(this.program, 'vertexOffset');
this.colorTexture = gl.getUniformLocation(this.program, 'colorTex');
this.filterTexture = gl.getUniformLocation(this.program, 'filterTex');
}
}
class Line {
constructor(gl) {
compileProgram.call(this, gl, __WEBPACK_IMPORTED_MODULE_0__renderer__["a" /* line */].VS, __WEBPACK_IMPORTED_MODULE_0__renderer__["a" /* line */].FS);
this.vertexPositionAttribute = gl.getAttribLocation(this.program, 'vertexPosition');
this.featureIdAttr = gl.getAttribLocation(this.program, 'featureID');
this.normalAttr = gl.getAttribLocation(this.program, 'normal');
this.vertexScaleUniformLocation = gl.getUniformLocation(this.program, 'vertexScale');
this.vertexOffsetUniformLocation = gl.getUniformLocation(this.program, 'vertexOffset');
this.colorTexture = gl.getUniformLocation(this.program, 'colorTex');
this.widthTexture = gl.getUniformLocation(this.program, 'widthTex');
this.filterTexture = gl.getUniformLocation(this.program, 'filterTex');
}
}
class GenericStyler {
constructor(gl, glsl, preface, inline) {
const VS = glsl.VS;
let FS = glsl.FS;
FS = FS.replace('$PREFACE', preface);
FS = FS.replace('$INLINE', inline);
compileProgram.call(this, gl, VS, FS);
this.vertexAttribute = gl.getAttribLocation(this.program, 'vertex');
this.textureLocations = [];
for (let i = 0; i < NUM_TEXTURE_LOCATIONS; i++) {
this.textureLocations[i] = gl.getUniformLocation(this.program, `property${i}`);
}
}
}
class Color extends GenericStyler {
constructor(gl, preface, inline) {
super(gl, __WEBPACK_IMPORTED_MODULE_1__styler__, '/*Color*/' + preface, inline);
}
}
class Width extends GenericStyler {
constructor(gl, preface, inline) {
super(gl, __WEBPACK_IMPORTED_MODULE_1__styler__, '/*Width*/' + preface, `vec4((${inline})/64.)`);
}
}
class Filter extends GenericStyler {
constructor(gl, preface, inline) {
super(gl, __WEBPACK_IMPORTED_MODULE_1__styler__, '/*Filter*/' + preface, `vec4(${inline})`);
}
}
const renderer = {
createPointShader: function (gl) {
return new Point(gl);
},
createTriShader: function (gl) {
return new Tri(gl);
},
createLineShader: function (gl) {
return new Line(gl);
}
};
const styler = {
createColorShader: function (gl, preface, inline) {
return new Color(gl, preface, inline);
},
createWidthShader: function (gl, preface, inline) {
return new Width(gl, preface, inline);
},
createFilterShader: function (gl, preface, inline) {
return new Filter(gl, preface, inline);
}
};
/***/ }),
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return rTiles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getRsysFromTile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return wToR; });
/**
* An RSys defines a local coordinate system that maps the coordinates
* in the range -1 <= x <= +1; -1 <= y <= +1 to an arbitrary rectangle
* in an external coordinate system. (e.g. Dataframe coordinates to World coordinates)
* It is the combination of a translation and anisotropic scaling.
* @typedef {object} RSys - Renderer relative coordinate system
* @property {RPoint} center - Position of the local system in external coordinates
* @property {number} scale - Y-scale (local Y-distance / external Y-distance)
*/
/*
* Random notes
*
* We can redefine Dataframe to use a Rsys instead of center, scale
* and we can use an Rsys for the Renderer's canvas.
*
* Some interesting World coordinate systems:
*
* WM (Webmercator): represents a part of the world (excluding polar regions)
* with coordinates in the range +/-WM_R for both X and Y. (positive orientation: E,N)
*
* NWMC (Normalized Webmercator Coordinates): represents the Webmercator *square*
* with coordinates in the range +/-1. Results from dividing Webmercator coordinates
* by WM_R. (positive orientation: E,N)
*
* TC (Tile coordinates): integers in [0, 2^Z) for zoom level Z. Example: the tile 0/0/0 (zoom, x, y) is the root tile.
* (positive orientation: E,S)
*
* An RSys's rectangle (its bounds) is the area covered by the local coordinates in
* the range +/-1.
*
* When an RSys external coordinate system is WM or NWMC, we can compute:
* * Minimum zoom level for which tiles are no larger than the RSys rectangle:
* Math.ceil(Math.log2(1 / r.scale));
* * Maximum zoom level for which tiles are no smaller than the rectangle:
* Math.floor(Math.log2(1 / r.scale));
* (note that 1 / r.scale is the fraction of the World height that the local rectangle's height represents)
*
* We'll use the term World coordinates below for the *external* reference system
* of an RSys (usually NWMC).
*/
/*eslint no-unused-vars: ["off"] */
/**
* R coordinates to World
* @param {RSys} r - ref. of the passed coordinates
* @param {number} x - x coordinate in r
* @param {number} y - y coordinate in r
* @return {RPoint} World coordinates
*/
function rToW(r, x, y) {
return { x: x * r.scale + r.center.x, y: y * r.scale + r.center.y };
}
/**
* World coordinates to local RSys
* @param {number} x - x W-coordinate
* @param {number} y - y W-coordinate
* @param {RSys} r - target ref. system
* @return {RPoint} R coordinates
*/
function wToR(x, y, r) {
return { x: (x - r.center.x) / r.scale, y: (y - r.center.y) / r.scale };
}
/**
* RSys of a tile (mapping local tile coordinates in +/-1 to NWMC)
* @param {number} x - TC x coordinate
* @param {number} y - TC y coordinate
* @param {number} z - Tile zoom level
* @return {RSys}
*/
function tileRsys(x, y, z) {
let max = Math.pow(2, z);
return { scale: 1 / max, center: { x: 2 * (x + 0.5) / max - 1, y: 1 - 2 * (y + 0.5) / max } };
}
/**
* Minimum zoom level for which tiles are no larger than the RSys rectangle
* @param {RSys} rsys
* @return {number}
*/
function rZoom(zoom) {
return Math.ceil(Math.log2(1. / zoom));
}
/**
* TC tiles that intersect the local rectangle of an RSys
* (with the largest tile size no larger than the rectangle)
* @param {RSys} rsys
* @return {Array} - array of TC tiles {x, y, z}
*/
function rTiles(bounds) {
return wRectangleTiles(rZoom((bounds[3] - bounds[1]) / 2.), bounds);
}
/**
* TC tiles of a given zoom level that intersect a W rectangle
* @param {number} z
* @param {Array} - rectangle extents [minx, miny, maxx, maxy]
* @return {Array} - array of TC tiles {x, y, z}
*/
function wRectangleTiles(z, wr) {
const [w_minx, w_miny, w_maxx, w_maxy] = wr;
const n = (1 << z); // for 0 <= z <= 30 equals Math.pow(2, z)
const clamp = x => Math.min(Math.max(x, 0), n - 1);
// compute tile coordinate ranges
const t_minx = clamp(Math.floor(n * (w_minx + 1) * 0.5));
const t_maxx = clamp(Math.ceil(n * (w_maxx + 1) * 0.5) - 1);
const t_miny = clamp(Math.floor(n * (1 - w_maxy) * 0.5));
const t_maxy = clamp(Math.ceil(n * (1 - w_miny) * 0.5) - 1);
let tiles = [];
for (let x = t_minx; x <= t_maxx; ++x) {
for (let y = t_miny; y <= t_maxy; ++y) {
tiles.push({ x: x, y: y, z: z });
}
}
return tiles;
}
/**
* Get the Rsys of a tile where the Rsys's center is the tile center and the Rsys's scale is the tile extent.
* @param {*} x
* @param {*} y
* @param {*} z
* @returns {RSys}
*/
function getRsysFromTile(x, y, z) {
return {
center: {
x: ((x + 0.5) / Math.pow(2, z)) * 2. - 1,
y: (1. - (y + 0.5) / Math.pow(2, z)) * 2. - 1.
},
scale: 1 / Math.pow(2, z)
};
}
/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__client_windshaft__ = __webpack_require__(62);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__setup_auth_service__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__setup_config_service__ = __webpack_require__(27);
const DEFAULT_SERVER_URL_TEMPLATE = 'https://{user}.carto.com';
class BaseWindshaft extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] {
constructor() {
super();
this._client = new __WEBPACK_IMPORTED_MODULE_1__client_windshaft__["a" /* default */](this);
}
initialize(auth, config) {
auth = auth || Object(__WEBPACK_IMPORTED_MODULE_3__setup_auth_service__["b" /* getDefaultAuth */])();
config = config || Object(__WEBPACK_IMPORTED_MODULE_4__setup_config_service__["b" /* getDefaultConfig */])();
Object(__WEBPACK_IMPORTED_MODULE_3__setup_auth_service__["a" /* checkAuth */])(auth);
Object(__WEBPACK_IMPORTED_MODULE_4__setup_config_service__["a" /* checkConfig */])(config);
this._apiKey = auth.apiKey;
this._username = auth.username;
this._serverURL = this._generateURL(auth, config);
}
bindLayer(...args) {
this._client._bindLayer(...args);
}
requestData(viewport, style) {
return this._client.getData(viewport, style);
}
free() {
this._client.free();
}
_generateURL(auth, config) {
let url = (config && config.serverURL) || DEFAULT_SERVER_URL_TEMPLATE;
url = url.replace(/{user}/, auth.username);
this._validateServerURL(url);
return url;
}
_validateServerURL(serverURL) {
var urlregex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;
if (!serverURL.match(urlregex)) {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'nonValidServerURL');
}
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = BaseWindshaft;
/***/ }),
/* 23 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var VectorTileFeature = __webpack_require__(25);
module.exports = 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);
};
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Point = __webpack_require__(76);
module.exports = 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) {
var cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
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) {
var cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
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;
}
/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return setDefaultAuth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getDefaultAuth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return checkAuth; });
/* unused harmony export cleanDefaultAuth */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__ = __webpack_require__(6);
let defaultAuth = undefined;
/**
* Set default authentication parameters: apiKey and user.
*
* @param {object} auth
* @param {string} auth.apiKey - API key used to authenticate against CARTO
* @param {string} auth.user - Name of the user
*
* @memberof carto
* @api
*/
function setDefaultAuth(auth) {
checkAuth(auth);
defaultAuth = auth;
}
/**
* Get default authentication
* @return {object}
*/
function getDefaultAuth() {
return defaultAuth;
}
/**
* Reset the default auth object
*/
function cleanDefaultAuth() {
defaultAuth = undefined;
}
/**
* Check a valid auth parameter.
*
* @param {object} auth
*/
function checkAuth(auth) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](auth)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'authRequired');
}
if (!__WEBPACK_IMPORTED_MODULE_0__util__["d" /* isObject */](auth)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'authObjectRequired');
}
auth.username = auth.user; // API adapter
checkApiKey(auth.apiKey);
checkUsername(auth.username);
}
function checkApiKey(apiKey) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](apiKey)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'apiKeyRequired');
}
if (!__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](apiKey)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'apiKeyStringRequired');
}
if (apiKey === '') {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'nonValidApiKey');
}
}
function checkUsername(username) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](username)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'usernameRequired');
}
if (!__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](username)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'usernameStringRequired');
}
if (username === '') {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'nonValidUsername');
}
}
/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return setDefaultConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getDefaultConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return checkConfig; });
/* unused harmony export cleanDefaultConfig */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__ = __webpack_require__(6);
let defaultConfig = undefined;
/**
* Set default configuration parameters: serverURL.
*
* @param {object} options
* @param {string} [options.serverURL='https://{user}.carto.com'] - URL of the CARTO Maps API server
*
* @memberof carto
* @api
*/
function setDefaultConfig(config) {
checkConfig(config);
defaultConfig = config;
}
/**
* Get default config
* @return {object}
*/
function getDefaultConfig() {
return defaultConfig;
}
/**
* Clean default config object
*/
function cleanDefaultConfig() {
defaultConfig = undefined;
}
/**
* Check a valid config parameter.
*
* @param {object} config
*/
function checkConfig(config) {
if (config) {
if (!__WEBPACK_IMPORTED_MODULE_0__util__["d" /* isObject */](config)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'configObjectRequired');
}
_checkServerURL(config.serverURL);
}
}
function _checkServerURL(serverURL) {
if (!__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](serverURL)) {
throw new __WEBPACK_IMPORTED_MODULE_1__error_handling_carto_validation_error__["a" /* default */]('setup', 'serverURLStringRequired');
}
}
/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__core_style_functions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__core_schema__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__core_shaders__ = __webpack_require__(20);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__core_style_shader_compiler__ = __webpack_require__(81);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__core_style_parser__ = __webpack_require__(82);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__ = __webpack_require__(6);
const DEFAULT_RESOLUTION = 1;
const DEFAULT_COLOR_EXPRESSION = __WEBPACK_IMPORTED_MODULE_1__core_style_functions__["rgba"](0, 1, 0, 0.5);
const DEFAULT_WIDTH_EXPRESSION = __WEBPACK_IMPORTED_MODULE_1__core_style_functions__["float"](5);
const DEFAULT_STROKE_COLOR_EXPRESSION = __WEBPACK_IMPORTED_MODULE_1__core_style_functions__["rgba"](0, 1, 0, 0.5);
const DEFAULT_STROKE_WIDTH_EXPRESSION = __WEBPACK_IMPORTED_MODULE_1__core_style_functions__["float"](0);
const DEFAULT_ORDER_EXPRESSION = __WEBPACK_IMPORTED_MODULE_1__core_style_functions__["noOrder"]();
const DEFAULT_FILTER_EXPRESSION = __WEBPACK_IMPORTED_MODULE_1__core_style_functions__["floatConstant"](1);
const SUPPORTED_PROPERTIES = [
'resolution',
'color',
'width',
'strokeColor',
'strokeWidth',
'order',
'filter'
];
/**
* @description A Style defines how associated dataframes of a particular renderer should be renderer.
*
* Styles are only compatible with dataframes that comply with the same schema.
* The schema is the interface that a dataframe must comply with.
*/
class Style {
/**
* Create a carto.Style.
*
* @param {string|StyleSpec} definition - The definition of a style. This parameter could be a `string` or a `StyleSpec` object
*
* @example
* new carto.Style(`
* color: rgb(0,0,0)
* `);
*
* new carto.Style({
* color: carto.style.expression.rgb(0,0,0)
* });
*
* @fires CartoError
*
* @constructor Style
* @memberof carto
* @api
*/
constructor(definition) {
const styleSpec = this._getStyleDefinition(definition);
this._checkStyleSpec(styleSpec);
this._styleSpec = styleSpec;
this.updated = true;
this._changeCallback = null;
this._styleSpec.color.parent = this;
this._styleSpec.width.parent = this;
this._styleSpec.strokeColor.parent = this;
this._styleSpec.strokeWidth.parent = this;
this._styleSpec.order.parent = this;
this._styleSpec.filter.parent = this;
this._styleSpec.color.notify = this._changed.bind(this);
this._styleSpec.width.notify = this._changed.bind(this);
this._styleSpec.strokeColor.notify = this._changed.bind(this);
this._styleSpec.strokeWidth.notify = this._changed.bind(this);
this._styleSpec.order.notify = this._changed.bind(this);
this._styleSpec.filter.notify = this._changed.bind(this);
}
/**
* Return the resolution.
*
* @return {number}
*
* @memberof carto.Style
* @api
*/
getResolution() {
return this._styleSpec.resolution;
}
/**
* Return the color expression.
*
* @return {carto.style.expression}
*
* @memberof carto.Style
* @api
*/
getColor() {
return this._styleSpec.color;
}
/**
* Return the width expression.
*
* @return {carto.style.expression}
*
* @memberof carto.Style
* @api
*/
getWidth() {
return this._styleSpec.width;
}
/**
* Return the strokeColor expression.
*
* @return {carto.style.expression}
*
* @memberof carto.Style
* @api
*/
getStrokeColor() {
return this._styleSpec.strokeColor;
}
/**
* Return the strokeWidth expression.
*
* @return {carto.style.expression}
*
* @memberof carto.Style
* @api
*/
getStrokeWidth() {
return this._styleSpec.strokeWidth;
}
/**
* Return the order expression.
*
* @return {carto.style.expression}
*
* @memberof carto.Style
* @api
*/
getOrder() {
return this._styleSpec.order;
}
get filter(){
return this._styleSpec.filter;
}
isAnimated() {
return this.getColor().isAnimated() ||
this.getWidth().isAnimated() ||
this.getStrokeColor().isAnimated() ||
this.getStrokeWidth().isAnimated() ||
this.filter.isAnimated();
}
onChange(callback) {
this._changeCallback = callback;
}
_changed() {
if (this._changeCallback) {
this._changeCallback();
}
}
getMinimumNeededSchema() {
const exprs = [
this._styleSpec.color,
this._styleSpec.width,
this._styleSpec.strokeColor,
this._styleSpec.strokeWidth,
this._styleSpec.filter,
].filter(x => x && x._getMinimumNeededSchema);
return exprs.map(expr => expr._getMinimumNeededSchema()).reduce(__WEBPACK_IMPORTED_MODULE_2__core_schema__["union"], __WEBPACK_IMPORTED_MODULE_2__core_schema__["IDENTITY"]);
}
_compileColorShader(gl, metadata) {
this._styleSpec.color._bind(metadata);
const r = Object(__WEBPACK_IMPORTED_MODULE_4__core_style_shader_compiler__["a" /* compileShader */])(gl, this._styleSpec.color, __WEBPACK_IMPORTED_MODULE_3__core_shaders__["c" /* styler */].createColorShader);
this.propertyColorTID = r.tid;
this.colorShader = r.shader;
}
_compileWidthShader(gl, metadata) {
this._styleSpec.width._bind(metadata);
const r = Object(__WEBPACK_IMPORTED_MODULE_4__core_style_shader_compiler__["a" /* compileShader */])(gl, this._styleSpec.width, __WEBPACK_IMPORTED_MODULE_3__core_shaders__["c" /* styler */].createWidthShader);
this.propertyWidthTID = r.tid;
this.widthShader = r.shader;
}
_compileStrokeColorShader(gl, metadata) {
this._styleSpec.strokeColor._bind(metadata);
const r = Object(__WEBPACK_IMPORTED_MODULE_4__core_style_shader_compiler__["a" /* compileShader */])(gl, this._styleSpec.strokeColor, __WEBPACK_IMPORTED_MODULE_3__core_shaders__["c" /* styler */].createColorShader);
this.propertyStrokeColorTID = r.tid;
this.strokeColorShader = r.shader;
}
_compileStrokeWidthShader(gl, metadata) {
this._styleSpec.strokeWidth._bind(metadata);
const r = Object(__WEBPACK_IMPORTED_MODULE_4__core_style_shader_compiler__["a" /* compileShader */])(gl, this._styleSpec.strokeWidth, __WEBPACK_IMPORTED_MODULE_3__core_shaders__["c" /* styler */].createWidthShader);
this.propertyStrokeWidthTID = r.tid;
this.strokeWidthShader = r.shader;
}
_compileFilterShader(gl, metadata) {
this._styleSpec.filter._bind(metadata);
const r = Object(__WEBPACK_IMPORTED_MODULE_4__core_style_shader_compiler__["a" /* compileShader */])(gl, this._styleSpec.filter, __WEBPACK_IMPORTED_MODULE_3__core_shaders__["c" /* styler */].createFilterShader);
this.propertyFilterTID = r.tid;
this.filterShader = r.shader;
}
_replaceChild(toReplace, replacer) {
if (toReplace == this._styleSpec.color) {
this._styleSpec.color = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
} else if (toReplace == this._styleSpec.width) {
this._styleSpec.width = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
} else if (toReplace == this._styleSpec.strokeColor) {
this._styleSpec.strokeColor = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
} else if (toReplace == this._styleSpec.strokeWidth) {
this._styleSpec.strokeWidth = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
} else if (toReplace == this._styleSpec.filter) {
this._styleSpec.filter = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
} else {
throw new Error('No child found');
}
}
// ^^
/**
* This function checks the input parameter `definition` returning always an object.
* If the `definition` is an object it returns the same object.
* If the `definition` is a string it returns the parsed string as an object.
* Otherwise it throws an error.
*
* @param {string|object} definition
* @return {StyleSpec}
*/
_getStyleDefinition(definition) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](definition)) {
return this._setDefaults({});
}
if (__WEBPACK_IMPORTED_MODULE_0__util__["d" /* isObject */](definition)) {
return this._setDefaults(definition);
}
if (__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](definition)) {
return this._setDefaults(Object(__WEBPACK_IMPORTED_MODULE_5__core_style_parser__["a" /* parseStyleDefinition */])(definition));
}
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidDefinition');
}
/**
* Add default values to a styleSpec object.
*
* @param {StyleSpec} styleSpec
* @return {StyleSpec}
*/
_setDefaults(styleSpec) {
styleSpec.resolution = __WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](styleSpec.resolution) ? DEFAULT_RESOLUTION : styleSpec.resolution;
styleSpec.color = styleSpec.color || DEFAULT_COLOR_EXPRESSION;
styleSpec.width = styleSpec.width || DEFAULT_WIDTH_EXPRESSION;
styleSpec.strokeColor = styleSpec.strokeColor || DEFAULT_STROKE_COLOR_EXPRESSION;
styleSpec.strokeWidth = styleSpec.strokeWidth || DEFAULT_STROKE_WIDTH_EXPRESSION;
styleSpec.order = styleSpec.order || DEFAULT_ORDER_EXPRESSION;
styleSpec.filter = styleSpec.filter || DEFAULT_FILTER_EXPRESSION;
return styleSpec;
}
_checkStyleSpec(styleSpec) {
/**
* @typedef {object} StyleSpec
* @property {number} resolution
* @property {carto.style.expression.Base} color
* @property {carto.style.expression.Base} width
* @property {carto.style.expression.Base} strokeColor
* @property {carto.style.expression.Base} strokeWidth
* @property {carto.style.expression.Base} order
* @api
*/
// TODO: Check expression types ie: color is not a number expression!
if (!__WEBPACK_IMPORTED_MODULE_0__util__["c" /* isNumber */](styleSpec.resolution)) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'resolutionNumberRequired');
}
if (!(styleSpec.color instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidExpression[color]');
}
if (!(styleSpec.width instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidExpression[width]');
}
if (!(styleSpec.strokeColor instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidExpression[strokeColor]');
}
if (!(styleSpec.strokeWidth instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidExpression[strokeWidth]');
}
if (!(styleSpec.order instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidExpression[order]');
}
if (!(styleSpec.filter instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_expression__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_7__error_handling_carto_validation_error__["a" /* default */]('style', 'nonValidExpression[filter]');
}
for (let key in styleSpec) {
if (SUPPORTED_PROPERTIES.indexOf(key) === -1) {
console.warn(`Property '${key}' is not supported`);
}
}
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Style;
/***/ }),
/* 29 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/**
* @description A simple non-interactive map.
*/
class Map {
/**
* Create a simple carto.Map by specifying a container `id`.
*
* @param {object} options
* @param {string} options.container The element's string `id`.
*
* @constructor Map
* @memberof carto
*/
constructor(options) {
options = options || {};
if (typeof options.container === 'string') {
const container = window.document.getElementById(options.container);
if (!container) {
throw new Error(`Container '${options.container}' not found.`);
} else {
this._container = container;
}
}
this._background = options.background || '';
this._layers = [];
this._repaint = true;
this._canvas = this._createCanvas();
this._container.appendChild(this._canvas);
this._gl = this._canvas.getContext('webgl') || this._canvas.getContext('experimental-webgl');
this._resizeCanvas(this._containerDimensions());
}
addLayer(layer, beforeLayerID) {
setTimeout(() => {
layer.initCallback();
});
let index;
for (index = 0; index < this._layers.length; index++) {
if (this._layers[index].getId() === beforeLayerID) {
break;
}
}
this._layers.splice(index, 0, layer);
window.requestAnimationFrame(this.update.bind(this));
}
update() {
this._drawBackground(this._background);
let loaded = true;
let animated = false;
this._layers.forEach((layer) => {
const hasData = layer.hasDataframes();
const hasAnimation = layer.getStyle().isAnimated();
if (hasData || hasAnimation) {
layer.paintCallback();
}
loaded = loaded && hasData;
animated = animated || hasAnimation;
});
// Update until all layers are loaded or there is an animation
if (!loaded || animated) {
window.requestAnimationFrame(this.update.bind(this));
}
}
_drawBackground(color) {
switch (color) {
case 'black':
this._gl.clearColor(0, 0, 0, 1);
this._gl.clear(this._gl.COLOR_BUFFER_BIT);
break;
case 'red':
this._gl.clearColor(1, 0, 0, 1);
this._gl.clear(this._gl.COLOR_BUFFER_BIT);
break;
case 'green':
this._gl.clearColor(0, 1, 0, 1);
this._gl.clear(this._gl.COLOR_BUFFER_BIT);
break;
case 'blue':
this._gl.clearColor(0, 0, 1, 1);
this._gl.clear(this._gl.COLOR_BUFFER_BIT);
break;
default:
// white
}
}
_createCanvas() {
const canvas = window.document.createElement('canvas');
canvas.className = 'canvas';
canvas.style.position = 'absolute';
return canvas;
}
_containerDimensions() {
let width = 0;
let height = 0;
if (this._container) {
width = this._container.offsetWidth || 400;
height = this._container.offsetHeight || 300;
}
return { width, height };
}
_resizeCanvas(size) {
const pixelRatio = window.devicePixelRatio || 1;
this._canvas.width = pixelRatio * size.width;
this._canvas.height = pixelRatio * size.height;
this._canvas.style.width = `${size.width}px`;
this._canvas.style.height = `${size.height}px`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Map;
/***/ }),
/* 30 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "source", function() { return source; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "style", function() { return style; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_style_functions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__api_source_geojson__ = __webpack_require__(51);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__api_source_dataset__ = __webpack_require__(61);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__api_source_sql__ = __webpack_require__(79);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__api_layer__ = __webpack_require__(80);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__api_style__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__api_setup_auth_service__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__api_setup_config_service__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__api_map__ = __webpack_require__(29);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return __WEBPACK_IMPORTED_MODULE_4__api_layer__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "setDefaultAuth", function() { return __WEBPACK_IMPORTED_MODULE_6__api_setup_auth_service__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "setDefaultConfig", function() { return __WEBPACK_IMPORTED_MODULE_7__api_setup_config_service__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Style", function() { return __WEBPACK_IMPORTED_MODULE_5__api_style__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Map", function() { return __WEBPACK_IMPORTED_MODULE_8__api_map__["a"]; });
/**
* @api
* @namespace carto
*
* @description
* # CARTO GL
* All the library features are exposed through the `carto` namespace.
*/
// Namespaces
const style = { expressions: __WEBPACK_IMPORTED_MODULE_0__core_style_functions__ };
const source = { Dataset: __WEBPACK_IMPORTED_MODULE_2__api_source_dataset__["a" /* default */], SQL: __WEBPACK_IMPORTED_MODULE_3__api_source_sql__["a" /* default */], GeoJSON: __WEBPACK_IMPORTED_MODULE_1__api_source_geojson__["a" /* default */] };
/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return palettes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Inverse; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_cartocolor__ = __webpack_require__(32);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_cartocolor___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_cartocolor__);
class PaletteGenerator {
constructor(name, subPalettes) {
this.type = 'paletteGenerator';
this.name = name;
this.subPalettes = subPalettes;
this.tags = subPalettes.tags;
}
getLongestSubPalette() {
const s = this.subPalettes;
for (let i = 20; i >= 0; i--) {
if (s[i]) {
return s[i];
}
}
}
}
const palettes = {};
Object.keys(__WEBPACK_IMPORTED_MODULE_0_cartocolor__).map(name => {
palettes[`${name.toLowerCase()}`] = new PaletteGenerator(name, __WEBPACK_IMPORTED_MODULE_0_cartocolor__[name]);
});
class Inverse {
constructor(palette) {
this.type = 'paletteGenerator';
this._originalPalette = palette;
this.tags = palette.tags;
this.subPalettes = new Proxy(palette.subPalettes, {
get: (target, name) => {
if (Number.isFinite(Number(name)) && Array.isArray(target[name])) {
return this._reversePalette(target[name]);
}
return target[name];
}
});
}
getLongestSubPalette() {
return this._reversePalette(this._originalPalette.getLongestSubPalette());
}
_reversePalette(palette) {
if (this.tags.includes('qualitative')) {
// Last color is 'others', therefore, we shouldn't change the order of that one
const copy = [...palette];
const others = copy.pop();
return [...copy.reverse(), others];
}
return [...palette].reverse();
}
}
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(33);
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;!function() {
var cartocolor = {
"Burg": {
"2": [
"#ffc6c4",
"#672044"
],
"3": [
"#ffc6c4",
"#cc607d",
"#672044"
],
"4": [
"#ffc6c4",
"#e38191",
"#ad466c",
"#672044"
],
"5": [
"#ffc6c4",
"#ee919b",
"#cc607d",
"#9e3963",
"#672044"
],
"6": [
"#ffc6c4",
"#f29ca3",
"#da7489",
"#b95073",
"#93345d",
"#672044"
],
"7": [
"#ffc6c4",
"#f4a3a8",
"#e38191",
"#cc607d",
"#ad466c",
"#8b3058",
"#672044"
],
"tags": [
"quantitative"
]
},
"BurgYl": {
"2": [
"#fbe6c5",
"#70284a"
],
"3": [
"#fbe6c5",
"#dc7176",
"#70284a"
],
"4": [
"#fbe6c5",
"#ee8a82",
"#c8586c",
"#70284a"
],
"5": [
"#fbe6c5",
"#f2a28a",
"#dc7176",
"#b24b65",
"#70284a"
],
"6": [
"#fbe6c5",
"#f4b191",
"#e7807d",
"#d06270",
"#a44360",
"#70284a"
],
"7": [
"#fbe6c5",
"#f5ba98",
"#ee8a82",
"#dc7176",
"#c8586c",
"#9c3f5d",
"#70284a"
],
"tags": [
"quantitative"
]
},
"RedOr": {
"2": [
"#f6d2a9",
"#b13f64"
],
"3": [
"#f6d2a9",
"#ea8171",
"#b13f64"
],
"4": [
"#f6d2a9",
"#f19c7c",
"#dd686c",
"#b13f64"
],
"5": [
"#f6d2a9",
"#f3aa84",
"#ea8171",
"#d55d6a",
"#b13f64"
],
"6": [
"#f6d2a9",
"#f4b28a",
"#ef9177",
"#e3726d",
"#cf5669",
"#b13f64"
],
"7": [
"#f6d2a9",
"#f5b78e",
"#f19c7c",
"#ea8171",
"#dd686c",
"#ca5268",
"#b13f64"
],
"tags": [
"quantitative"
]
},
"OrYel": {
"2": [
"#ecda9a",
"#ee4d5a"
],
"3": [
"#ecda9a",
"#f7945d",
"#ee4d5a"
],
"4": [
"#ecda9a",
"#f3ad6a",
"#f97b57",
"#ee4d5a"
],
"5": [
"#ecda9a",
"#f1b973",
"#f7945d",
"#f86f56",
"#ee4d5a"
],
"6": [
"#ecda9a",
"#f0c079",
"#f5a363",
"#f98558",
"#f76856",
"#ee4d5a"
],
"7": [
"#ecda9a",
"#efc47e",
"#f3ad6a",
"#f7945d",
"#f97b57",
"#f66356",
"#ee4d5a"
],
"tags": [
"quantitative"
]
},
"Peach": {
"2": [
"#fde0c5",
"#eb4a40"
],
"3": [
"#fde0c5",
"#f59e72",
"#eb4a40"
],
"4": [
"#fde0c5",
"#f8b58b",
"#f2855d",
"#eb4a40"
],
"5": [
"#fde0c5",
"#f9c098",
"#f59e72",
"#f17854",
"#eb4a40"
],
"6": [
"#fde0c5",
"#fac7a1",
"#f7ac80",
"#f38f65",
"#f0704f",
"#eb4a40"
],
"7": [
"#fde0c5",
"#facba6",
"#f8b58b",
"#f59e72",
"#f2855d",
"#ef6a4c",
"#eb4a40"
],
"tags": [
"quantitative"
]
},
"PinkYl": {
"2": [
"#fef6b5",
"#e15383"
],
"3": [
"#fef6b5",
"#ffa679",
"#e15383"
],
"4": [
"#fef6b5",
"#ffc285",
"#fa8a76",
"#e15383"
],
"5": [
"#fef6b5",
"#ffd08e",
"#ffa679",
"#f67b77",
"#e15383"
],
"6": [
"#fef6b5",
"#ffd795",
"#ffb77f",
"#fd9576",
"#f37378",
"#e15383"
],
"7": [
"#fef6b5",
"#ffdd9a",
"#ffc285",
"#ffa679",
"#fa8a76",
"#f16d7a",
"#e15383"
],
"tags": [
"quantitative"
]
},
"Mint": {
"2": [
"#e4f1e1",
"#0d585f"
],
"3": [
"#e4f1e1",
"#63a6a0",
"#0d585f"
],
"4": [
"#e4f1e1",
"#89c0b6",
"#448c8a",
"#0d585f"
],
"5": [
"#E4F1E1",
"#9CCDC1",
"#63A6A0",
"#337F7F",
"#0D585F"
],
"6": [
"#e4f1e1",
"#abd4c7",
"#7ab5ad",
"#509693",
"#2c7778",
"#0d585f"
],
"7": [
"#e4f1e1",
"#b4d9cc",
"#89c0b6",
"#63a6a0",
"#448c8a",
"#287274",
"#0d585f"
],
"tags": [
"quantitative"
]
},
"BluGrn": {
"2": [
"#c4e6c3",
"#1d4f60"
],
"3": [
"#c4e6c3",
"#4da284",
"#1d4f60"
],
"4": [
"#c4e6c3",
"#6dbc90",
"#36877a",
"#1d4f60"
],
"5": [
"#c4e6c3",
"#80c799",
"#4da284",
"#2d7974",
"#1d4f60"
],
"6": [
"#c4e6c3",
"#8dce9f",
"#5fb28b",
"#3e927e",
"#297071",
"#1d4f60"
],
"7": [
"#c4e6c3",
"#96d2a4",
"#6dbc90",
"#4da284",
"#36877a",
"#266b6e",
"#1d4f60"
],
"tags": [
"quantitative"
]
},
"DarkMint": {
"2": [
"#d2fbd4",
"#123f5a"
],
"3": [
"#d2fbd4",
"#559c9e",
"#123f5a"
],
"4": [
"#d2fbd4",
"#7bbcb0",
"#3a7c89",
"#123f5a"
],
"5": [
"#d2fbd4",
"#8eccb9",
"#559c9e",
"#2b6c7f",
"#123f5a"
],
"6": [
"#d2fbd4",
"#9cd5be",
"#6cafa9",
"#458892",
"#266377",
"#123f5a"
],
"7": [
"#d2fbd4",
"#a5dbc2",
"#7bbcb0",
"#559c9e",
"#3a7c89",
"#235d72",
"#123f5a"
],
"tags": [
"quantitative"
]
},
"Emrld": {
"2": [
"#d3f2a3",
"#074050"
],
"3": [
"#d3f2a3",
"#4c9b82",
"#074050"
],
"4": [
"#d3f2a3",
"#6cc08b",
"#217a79",
"#074050"
],
"5": [
"#d3f2a3",
"#82d091",
"#4c9b82",
"#19696f",
"#074050"
],
"6": [
"#d3f2a3",
"#8fda94",
"#60b187",
"#35877d",
"#145f69",
"#074050"
],
"7": [
"#d3f2a3",
"#97e196",
"#6cc08b",
"#4c9b82",
"#217a79",
"#105965",
"#074050"
],
"tags": [
"quantitative"
]
},
"ag_GrnYl": {
"2": [
"#245668",
"#EDEF5D"
],
"3": [
"#245668",
"#39AB7E",
"#EDEF5D"
],
"4": [
"#245668",
"#0D8F81",
"#6EC574",
"#EDEF5D"
],
"5": [
"#245668",
"#04817E",
"#39AB7E",
"#8BD16D",
"#EDEF5D"
],
"6": [
"#245668",
"#09787C",
"#1D9A81",
"#58BB79",
"#9DD869",
"#EDEF5D"
],
"7": [
"#245668",
"#0F7279",
"#0D8F81",
"#39AB7E",
"#6EC574",
"#A9DC67",
"#EDEF5D"
],
"tags": [
"aggregation"
]
},
"BluYl": {
"2": [
"#f7feae",
"#045275"
],
"3": [
"#f7feae",
"#46aea0",
"#045275"
],
"4": [
"#f7feae",
"#7ccba2",
"#089099",
"#045275"
],
"5": [
"#f7feae",
"#9bd8a4",
"#46aea0",
"#058092",
"#045275"
],
"6": [
"#f7feae",
"#ace1a4",
"#68bfa1",
"#2a9c9c",
"#02778e",
"#045275"
],
"7": [
"#f7feae",
"#b7e6a5",
"#7ccba2",
"#46aea0",
"#089099",
"#00718b",
"#045275"
],
"tags": [
"quantitative"
]
},
"Teal": {
"2": [
"#d1eeea",
"#2a5674"
],
"3": [
"#d1eeea",
"#68abb8",
"#2a5674"
],
"4": [
"#d1eeea",
"#85c4c9",
"#4f90a6",
"#2a5674"
],
"5": [
"#d1eeea",
"#96d0d1",
"#68abb8",
"#45829b",
"#2a5674"
],
"6": [
"#d1eeea",
"#a1d7d6",
"#79bbc3",
"#599bae",
"#3f7994",
"#2a5674"
],
"7": [
"#d1eeea",
"#a8dbd9",
"#85c4c9",
"#68abb8",
"#4f90a6",
"#3b738f",
"#2a5674"
],
"tags": [
"quantitative"
]
},
"TealGrn": {
"2": [
"#b0f2bc",
"#257d98"
],
"3": [
"#b0f2bc",
"#4cc8a3",
"#257d98"
],
"4": [
"#b0f2bc",
"#67dba5",
"#38b2a3",
"#257d98"
],
"5": [
"#b0f2bc",
"#77e2a8",
"#4cc8a3",
"#31a6a2",
"#257d98"
],
"6": [
"#b0f2bc",
"#82e6aa",
"#5bd4a4",
"#3fbba3",
"#2e9ea1",
"#257d98"
],
"7": [
"#b0f2bc",
"#89e8ac",
"#67dba5",
"#4cc8a3",
"#38b2a3",
"#2c98a0",
"#257d98"
],
"tags": [
"quantitative"
]
},
"Purp": {
"2": [
"#f3e0f7",
"#63589f"
],
"3": [
"#f3e0f7",
"#b998dd",
"#63589f"
],
"4": [
"#f3e0f7",
"#d1afe8",
"#9f82ce",
"#63589f"
],
"5": [
"#f3e0f7",
"#dbbaed",
"#b998dd",
"#9178c4",
"#63589f"
],
"6": [
"#f3e0f7",
"#e0c2ef",
"#c8a5e4",
"#aa8bd4",
"#8871be",
"#63589f"
],
"7": [
"#f3e0f7",
"#e4c7f1",
"#d1afe8",
"#b998dd",
"#9f82ce",
"#826dba",
"#63589f"
],
"tags": [
"quantitative"
]
},
"PurpOr": {
"3": [
"#f9ddda",
"#ce78b3",
"#573b88"
],
"4": [
"#f9ddda",
"#e597b9",
"#ad5fad",
"#573b88"
],
"5": [
"#f9ddda",
"#eda8bd",
"#ce78b3",
"#9955a8",
"#573b88"
],
"6": [
"#f9ddda",
"#f0b2c1",
"#dd8ab6",
"#bb69b0",
"#8c4fa4",
"#573b88"
],
"7": [
"#f9ddda",
"#f2b9c4",
"#e597b9",
"#ce78b3",
"#ad5fad",
"#834ba0",
"#573b88"
],
"tags": [
"quantitative"
]
},
"Sunset": {
"2": [
"#f3e79b",
"#5c53a5"
],
"3": [
"#f3e79b",
"#eb7f86",
"#5c53a5"
],
"4": [
"#f3e79b",
"#f8a07e",
"#ce6693",
"#5c53a5"
],
"5": [
"#f3e79b",
"#fab27f",
"#eb7f86",
"#b95e9a",
"#5c53a5"
],
"6": [
"#f3e79b",
"#fabc82",
"#f59280",
"#dc6f8e",
"#ab5b9e",
"#5c53a5"
],
"7": [
"#f3e79b",
"#fac484",
"#f8a07e",
"#eb7f86",
"#ce6693",
"#a059a0",
"#5c53a5"
],
"tags": [
"quantitative"
]
},
"Magenta": {
"2": [
"#f3cbd3",
"#6c2167"
],
"3": [
"#f3cbd3",
"#ca699d",
"#6c2167"
],
"4": [
"#f3cbd3",
"#dd88ac",
"#b14d8e",
"#6c2167"
],
"5": [
"#f3cbd3",
"#e498b4",
"#ca699d",
"#a24186",
"#6c2167"
],
"6": [
"#f3cbd3",
"#e7a2b9",
"#d67ba5",
"#bc5894",
"#983a81",
"#6c2167"
],
"7": [
"#f3cbd3",
"#eaa9bd",
"#dd88ac",
"#ca699d",
"#b14d8e",
"#91357d",
"#6c2167"
],
"tags": [
"quantitative"
]
},
"SunsetDark": {
"2": [
"#fcde9c",
"#7c1d6f"
],
"3": [
"#fcde9c",
"#e34f6f",
"#7c1d6f"
],
"4": [
"#fcde9c",
"#f0746e",
"#dc3977",
"#7c1d6f"
],
"5": [
"#fcde9c",
"#f58670",
"#e34f6f",
"#d72d7c",
"#7c1d6f"
],
"6": [
"#fcde9c",
"#f89872",
"#ec666d",
"#df4273",
"#c5287b",
"#7c1d6f"
],
"7": [
"#fcde9c",
"#faa476",
"#f0746e",
"#e34f6f",
"#dc3977",
"#b9257a",
"#7c1d6f"
],
"tags": [
"quantitative"
]
},
"ag_Sunset": {
"2": [
"#4b2991",
"#edd9a3"
],
"3": [
"#4b2991",
"#ea4f88",
"#edd9a3"
],
"4": [
"#4b2991",
"#c0369d",
"#fa7876",
"#edd9a3"
],
"5": [
"#4b2991",
"#a52fa2",
"#ea4f88",
"#fa9074",
"#edd9a3"
],
"6": [
"#4b2991",
"#932da3",
"#d43f96",
"#f7667c",
"#f89f77",
"#edd9a3"
],
"7": [
"#4b2991",
"#872ca2",
"#c0369d",
"#ea4f88",
"#fa7876",
"#f6a97a",
"#edd9a3"
],
"tags": [
"aggregation"
]
},
"BrwnYl": {
"2": [
"#ede5cf",
"#541f3f"
],
"3": [
"#ede5cf",
"#c1766f",
"#541f3f"
],
"4": [
"#ede5cf",
"#d39c83",
"#a65461",
"#541f3f"
],
"5": [
"#ede5cf",
"#daaf91",
"#c1766f",
"#95455a",
"#541f3f"
],
"6": [
"#ede5cf",
"#ddba9b",
"#cd8c7a",
"#b26166",
"#8a3c56",
"#541f3f"
],
"7": [
"#ede5cf",
"#e0c2a2",
"#d39c83",
"#c1766f",
"#a65461",
"#813753",
"#541f3f"
],
"tags": [
"quantitative"
]
},
"ArmyRose": {
"2": [
"#929b4f",
"#db8195"
],
"3": [
"#a3ad62",
"#fdfbe4",
"#df91a3"
],
"4": [
"#929b4f",
"#d9dbaf",
"#f3d1ca",
"#db8195"
],
"5": [
"#879043",
"#c1c68c",
"#fdfbe4",
"#ebb4b8",
"#d8758b"
],
"6": [
"#7f883b",
"#b0b874",
"#e3e4be",
"#f6ddd1",
"#e4a0ac",
"#d66d85"
],
"7": [
"#798234",
"#a3ad62",
"#d0d3a2",
"#fdfbe4",
"#f0c6c3",
"#df91a3",
"#d46780"
],
"tags": [
"diverging"
]
},
"Fall": {
"2": [
"#3d5941",
"#ca562c"
],
"3": [
"#3d5941",
"#f6edbd",
"#ca562c"
],
"4": [
"#3d5941",
"#b5b991",
"#edbb8a",
"#ca562c"
],
"5": [
"#3d5941",
"#96a07c",
"#f6edbd",
"#e6a272",
"#ca562c"
],
"6": [
"#3d5941",
"#839170",
"#cecea2",
"#f1cf9e",
"#e19464",
"#ca562c"
],
"7": [
"#3d5941",
"#778868",
"#b5b991",
"#f6edbd",
"#edbb8a",
"#de8a5a",
"#ca562c"
],
"tags": [
"diverging"
]
},
"Geyser": {
"2": [
"#008080",
"#ca562c"
],
"3": [
"#008080",
"#f6edbd",
"#ca562c"
],
"4": [
"#008080",
"#b4c8a8",
"#edbb8a",
"#ca562c"
],
"5": [
"#008080",
"#92b69e",
"#f6edbd",
"#e6a272",
"#ca562c"
],
"6": [
"#008080",
"#7eab98",
"#ced7b1",
"#f1cf9e",
"#e19464",
"#ca562c"
],
"7": [
"#008080",
"#70a494",
"#b4c8a8",
"#f6edbd",
"#edbb8a",
"#de8a5a",
"#ca562c"
],
"tags": [
"diverging"
]
},
"Temps": {
"2": [
"#009392",
"#cf597e"
],
"3": [
"#009392",
"#e9e29c",
"#cf597e"
],
"4": [
"#009392",
"#9ccb86",
"#eeb479",
"#cf597e"
],
"5": [
"#009392",
"#71be83",
"#e9e29c",
"#ed9c72",
"#cf597e"
],
"6": [
"#009392",
"#52b684",
"#bcd48c",
"#edc783",
"#eb8d71",
"#cf597e"
],
"7": [
"#009392",
"#39b185",
"#9ccb86",
"#e9e29c",
"#eeb479",
"#e88471",
"#cf597e"
],
"tags": [
"diverging"
]
},
"TealRose": {
"2": [
"#009392",
"#d0587e"
],
"3": [
"#009392",
"#f1eac8",
"#d0587e"
],
"4": [
"#009392",
"#91b8aa",
"#f1eac8",
"#dfa0a0",
"#d0587e"
],
"5": [
"#009392",
"#91b8aa",
"#f1eac8",
"#dfa0a0",
"#d0587e"
],
"6": [
"#009392",
"#72aaa1",
"#b1c7b3",
"#e5b9ad",
"#d98994",
"#d0587e"
],
"7": [
"#009392",
"#72aaa1",
"#b1c7b3",
"#f1eac8",
"#e5b9ad",
"#d98994",
"#d0587e"
],
"tags": [
"diverging"
]
},
"Tropic": {
"2": [
"#009B9E",
"#C75DAB"
],
"3": [
"#009B9E",
"#F1F1F1",
"#C75DAB"
],
"4": [
"#009B9E",
"#A7D3D4",
"#E4C1D9",
"#C75DAB"
],
"5": [
"#009B9E",
"#7CC5C6",
"#F1F1F1",
"#DDA9CD",
"#C75DAB"
],
"6": [
"#009B9E",
"#5DBCBE",
"#C6DFDF",
"#E9D4E2",
"#D99BC6",
"#C75DAB"
],
"7": [
"#009B9E",
"#42B7B9",
"#A7D3D4",
"#F1F1F1",
"#E4C1D9",
"#D691C1",
"#C75DAB"
],
"tags": [
"diverging"
]
},
"Earth": {
"2": [
"#A16928",
"#2887a1"
],
"3": [
"#A16928",
"#edeac2",
"#2887a1"
],
"4": [
"#A16928",
"#d6bd8d",
"#b5c8b8",
"#2887a1"
],
"5": [
"#A16928",
"#caa873",
"#edeac2",
"#98b7b2",
"#2887a1"
],
"6": [
"#A16928",
"#c29b64",
"#e0cfa2",
"#cbd5bc",
"#85adaf",
"#2887a1"
],
"7": [
"#A16928",
"#bd925a",
"#d6bd8d",
"#edeac2",
"#b5c8b8",
"#79a7ac",
"#2887a1"
],
"tags": [
"diverging"
]
},
"Antique": {
"2": [
"#855C75",
"#D9AF6B",
"#7C7C7C"
],
"3": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#7C7C7C"
],
"4": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#7C7C7C"
],
"5": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#7C7C7C"
],
"6": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#625377",
"#7C7C7C"
],
"7": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#625377",
"#68855C",
"#7C7C7C"
],
"8": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#625377",
"#68855C",
"#9C9C5E",
"#7C7C7C"
],
"9": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#625377",
"#68855C",
"#9C9C5E",
"#A06177",
"#7C7C7C"
],
"10": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#625377",
"#68855C",
"#9C9C5E",
"#A06177",
"#8C785D",
"#7C7C7C"
],
"11": [
"#855C75",
"#D9AF6B",
"#AF6458",
"#736F4C",
"#526A83",
"#625377",
"#68855C",
"#9C9C5E",
"#A06177",
"#8C785D",
"#467378",
"#7C7C7C"
],
"tags": [
"qualitative"
]
},
"Bold": {
"2": [
"#7F3C8D",
"#11A579",
"#A5AA99"
],
"3": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#A5AA99"
],
"4": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#A5AA99"
],
"5": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#A5AA99"
],
"6": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#80BA5A",
"#A5AA99"
],
"7": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#80BA5A",
"#E68310",
"#A5AA99"
],
"8": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#80BA5A",
"#E68310",
"#008695",
"#A5AA99"
],
"9": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#80BA5A",
"#E68310",
"#008695",
"#CF1C90",
"#A5AA99"
],
"10": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#80BA5A",
"#E68310",
"#008695",
"#CF1C90",
"#f97b72",
"#A5AA99"
],
"11": [
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#E73F74",
"#80BA5A",
"#E68310",
"#008695",
"#CF1C90",
"#f97b72",
"#4b4b8f",
"#A5AA99"
],
"tags": [
"qualitative"
]
},
"Pastel": {
"2": [
"#66C5CC",
"#F6CF71",
"#B3B3B3"
],
"3": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#B3B3B3"
],
"4": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#B3B3B3"
],
"5": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#B3B3B3"
],
"6": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#9EB9F3",
"#B3B3B3"
],
"7": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#9EB9F3",
"#FE88B1",
"#B3B3B3"
],
"8": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#9EB9F3",
"#FE88B1",
"#C9DB74",
"#B3B3B3"
],
"9": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#9EB9F3",
"#FE88B1",
"#C9DB74",
"#8BE0A4",
"#B3B3B3"
],
"10": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#9EB9F3",
"#FE88B1",
"#C9DB74",
"#8BE0A4",
"#B497E7",
"#B3B3B3"
],
"11": [
"#66C5CC",
"#F6CF71",
"#F89C74",
"#DCB0F2",
"#87C55F",
"#9EB9F3",
"#FE88B1",
"#C9DB74",
"#8BE0A4",
"#B497E7",
"#D3B484",
"#B3B3B3"
],
"tags": [
"qualitative"
]
},
"Prism": {
"2": [
"#5F4690",
"#1D6996",
"#666666"
],
"3": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#666666"
],
"4": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#666666"
],
"5": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#666666"
],
"6": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#EDAD08",
"#666666"
],
"7": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#EDAD08",
"#E17C05",
"#666666"
],
"8": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#EDAD08",
"#E17C05",
"#CC503E",
"#666666"
],
"9": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#EDAD08",
"#E17C05",
"#CC503E",
"#94346E",
"#666666"
],
"10": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#EDAD08",
"#E17C05",
"#CC503E",
"#94346E",
"#6F4070",
"#666666"
],
"11": [
"#5F4690",
"#1D6996",
"#38A6A5",
"#0F8554",
"#73AF48",
"#EDAD08",
"#E17C05",
"#CC503E",
"#94346E",
"#6F4070",
"#994E95",
"#666666"
],
"tags": [
"qualitative"
]
},
"Safe": {
"2": [
"#88CCEE",
"#CC6677",
"#888888"
],
"3": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#888888"
],
"4": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#888888"
],
"5": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#888888"
],
"6": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#AA4499",
"#888888"
],
"7": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#AA4499",
"#44AA99",
"#888888"
],
"8": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#AA4499",
"#44AA99",
"#999933",
"#888888"
],
"9": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#AA4499",
"#44AA99",
"#999933",
"#882255",
"#888888"
],
"10": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#AA4499",
"#44AA99",
"#999933",
"#882255",
"#661100",
"#888888"
],
"11": [
"#88CCEE",
"#CC6677",
"#DDCC77",
"#117733",
"#332288",
"#AA4499",
"#44AA99",
"#999933",
"#882255",
"#661100",
"#6699CC",
"#888888"
],
"tags": [
"qualitative",
"colorblind"
]
},
"Vivid": {
"2": [
"#E58606",
"#5D69B1",
"#A5AA99"
],
"3": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#A5AA99"
],
"4": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#A5AA99"
],
"5": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#A5AA99"
],
"6": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#24796C",
"#A5AA99"
],
"7": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#24796C",
"#DAA51B",
"#A5AA99"
],
"8": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#24796C",
"#DAA51B",
"#2F8AC4",
"#A5AA99"
],
"9": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#24796C",
"#DAA51B",
"#2F8AC4",
"#764E9F",
"#A5AA99"
],
"10": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#24796C",
"#DAA51B",
"#2F8AC4",
"#764E9F",
"#ED645A",
"#A5AA99"
],
"11": [
"#E58606",
"#5D69B1",
"#52BCA3",
"#99C945",
"#CC61B0",
"#24796C",
"#DAA51B",
"#2F8AC4",
"#764E9F",
"#ED645A",
"#CC3A8E",
"#A5AA99"
],
"tags": [
"qualitative"
]
}
};
var colorbrewer_tags = {
"Blues": { "tags": ["quantitative"] },
"BrBG": { "tags": ["diverging"] },
"Greys": { "tags": ["quantitative"] },
"PiYG": { "tags": ["diverging"] },
"PRGn": { "tags": ["diverging"] },
"Purples": { "tags": ["quantitative"] },
"RdYlGn": { "tags": ["diverging"] },
"Spectral": { "tags": ["diverging"] },
"YlOrBr": { "tags": ["quantitative"] },
"YlGn": { "tags": ["quantitative"] },
"YlGnBu": { "tags": ["quantitative"] },
"YlOrRd": { "tags": ["quantitative"] }
}
var colorbrewer = __webpack_require__(34);
// augment colorbrewer with tags
for (var r in colorbrewer) {
var ramps = colorbrewer[r];
var augmentedRamps = {};
for (var i in ramps) {
augmentedRamps[i] = ramps[i];
}
if (r in colorbrewer_tags) {
augmentedRamps.tags = colorbrewer_tags[r].tags;
}
cartocolor['cb_' + r] = augmentedRamps;
}
if (true) {
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (cartocolor),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof module === "object" && module.exports) {
module.exports = cartocolor;
} else {
this.colorbrewer = cartocolor;
}
}();
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(35);
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/).
// JavaScript specs as packaged in the D3 library (d3js.org). Please see license at http://colorbrewer.org/export/LICENSE.txt
!function() {
var colorbrewer = {YlGn: {
3: ["#f7fcb9","#addd8e","#31a354"],
4: ["#ffffcc","#c2e699","#78c679","#238443"],
5: ["#ffffcc","#c2e699","#78c679","#31a354","#006837"],
6: ["#ffffcc","#d9f0a3","#addd8e","#78c679","#31a354","#006837"],
7: ["#ffffcc","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"],
8: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"],
9: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"]
},YlGnBu: {
3: ["#edf8b1","#7fcdbb","#2c7fb8"],
4: ["#ffffcc","#a1dab4","#41b6c4","#225ea8"],
5: ["#ffffcc","#a1dab4","#41b6c4","#2c7fb8","#253494"],
6: ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#2c7fb8","#253494"],
7: ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"],
8: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"],
9: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]
},GnBu: {
3: ["#e0f3db","#a8ddb5","#43a2ca"],
4: ["#f0f9e8","#bae4bc","#7bccc4","#2b8cbe"],
5: ["#f0f9e8","#bae4bc","#7bccc4","#43a2ca","#0868ac"],
6: ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#43a2ca","#0868ac"],
7: ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"],
8: ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"],
9: ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"]
},BuGn: {
3: ["#e5f5f9","#99d8c9","#2ca25f"],
4: ["#edf8fb","#b2e2e2","#66c2a4","#238b45"],
5: ["#edf8fb","#b2e2e2","#66c2a4","#2ca25f","#006d2c"],
6: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#2ca25f","#006d2c"],
7: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"],
8: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"],
9: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"]
},PuBuGn: {
3: ["#ece2f0","#a6bddb","#1c9099"],
4: ["#f6eff7","#bdc9e1","#67a9cf","#02818a"],
5: ["#f6eff7","#bdc9e1","#67a9cf","#1c9099","#016c59"],
6: ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#1c9099","#016c59"],
7: ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"],
8: ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"],
9: ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"]
},PuBu: {
3: ["#ece7f2","#a6bddb","#2b8cbe"],
4: ["#f1eef6","#bdc9e1","#74a9cf","#0570b0"],
5: ["#f1eef6","#bdc9e1","#74a9cf","#2b8cbe","#045a8d"],
6: ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#2b8cbe","#045a8d"],
7: ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"],
8: ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"],
9: ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"]
},BuPu: {
3: ["#e0ecf4","#9ebcda","#8856a7"],
4: ["#edf8fb","#b3cde3","#8c96c6","#88419d"],
5: ["#edf8fb","#b3cde3","#8c96c6","#8856a7","#810f7c"],
6: ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8856a7","#810f7c"],
7: ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"],
8: ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"],
9: ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"]
},RdPu: {
3: ["#fde0dd","#fa9fb5","#c51b8a"],
4: ["#feebe2","#fbb4b9","#f768a1","#ae017e"],
5: ["#feebe2","#fbb4b9","#f768a1","#c51b8a","#7a0177"],
6: ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#c51b8a","#7a0177"],
7: ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"],
8: ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"],
9: ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"]
},PuRd: {
3: ["#e7e1ef","#c994c7","#dd1c77"],
4: ["#f1eef6","#d7b5d8","#df65b0","#ce1256"],
5: ["#f1eef6","#d7b5d8","#df65b0","#dd1c77","#980043"],
6: ["#f1eef6","#d4b9da","#c994c7","#df65b0","#dd1c77","#980043"],
7: ["#f1eef6","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"],
8: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"],
9: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"]
},OrRd: {
3: ["#fee8c8","#fdbb84","#e34a33"],
4: ["#fef0d9","#fdcc8a","#fc8d59","#d7301f"],
5: ["#fef0d9","#fdcc8a","#fc8d59","#e34a33","#b30000"],
6: ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#e34a33","#b30000"],
7: ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"],
8: ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"],
9: ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"]
},YlOrRd: {
3: ["#ffeda0","#feb24c","#f03b20"],
4: ["#ffffb2","#fecc5c","#fd8d3c","#e31a1c"],
5: ["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"],
6: ["#ffffb2","#fed976","#feb24c","#fd8d3c","#f03b20","#bd0026"],
7: ["#ffffb2","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"],
8: ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"],
9: ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"]
},YlOrBr: {
3: ["#fff7bc","#fec44f","#d95f0e"],
4: ["#ffffd4","#fed98e","#fe9929","#cc4c02"],
5: ["#ffffd4","#fed98e","#fe9929","#d95f0e","#993404"],
6: ["#ffffd4","#fee391","#fec44f","#fe9929","#d95f0e","#993404"],
7: ["#ffffd4","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"],
8: ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"],
9: ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"]
},Purples: {
3: ["#efedf5","#bcbddc","#756bb1"],
4: ["#f2f0f7","#cbc9e2","#9e9ac8","#6a51a3"],
5: ["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"],
6: ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#756bb1","#54278f"],
7: ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"],
8: ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"],
9: ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]
},Blues: {
3: ["#deebf7","#9ecae1","#3182bd"],
4: ["#eff3ff","#bdd7e7","#6baed6","#2171b5"],
5: ["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"],
6: ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#3182bd","#08519c"],
7: ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"],
8: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"],
9: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]
},Greens: {
3: ["#e5f5e0","#a1d99b","#31a354"],
4: ["#edf8e9","#bae4b3","#74c476","#238b45"],
5: ["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"],
6: ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#31a354","#006d2c"],
7: ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"],
8: ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"],
9: ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"]
},Oranges: {
3: ["#fee6ce","#fdae6b","#e6550d"],
4: ["#feedde","#fdbe85","#fd8d3c","#d94701"],
5: ["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"],
6: ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#e6550d","#a63603"],
7: ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"],
8: ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"],
9: ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]
},Reds: {
3: ["#fee0d2","#fc9272","#de2d26"],
4: ["#fee5d9","#fcae91","#fb6a4a","#cb181d"],
5: ["#fee5d9","#fcae91","#fb6a4a","#de2d26","#a50f15"],
6: ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#de2d26","#a50f15"],
7: ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"],
8: ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"],
9: ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]
},Greys: {
3: ["#f0f0f0","#bdbdbd","#636363"],
4: ["#f7f7f7","#cccccc","#969696","#525252"],
5: ["#f7f7f7","#cccccc","#969696","#636363","#252525"],
6: ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#636363","#252525"],
7: ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"],
8: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"],
9: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]
},PuOr: {
3: ["#f1a340","#f7f7f7","#998ec3"],
4: ["#e66101","#fdb863","#b2abd2","#5e3c99"],
5: ["#e66101","#fdb863","#f7f7f7","#b2abd2","#5e3c99"],
6: ["#b35806","#f1a340","#fee0b6","#d8daeb","#998ec3","#542788"],
7: ["#b35806","#f1a340","#fee0b6","#f7f7f7","#d8daeb","#998ec3","#542788"],
8: ["#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788"],
9: ["#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788"],
10: ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],
11: ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"]
},BrBG: {
3: ["#d8b365","#f5f5f5","#5ab4ac"],
4: ["#a6611a","#dfc27d","#80cdc1","#018571"],
5: ["#a6611a","#dfc27d","#f5f5f5","#80cdc1","#018571"],
6: ["#8c510a","#d8b365","#f6e8c3","#c7eae5","#5ab4ac","#01665e"],
7: ["#8c510a","#d8b365","#f6e8c3","#f5f5f5","#c7eae5","#5ab4ac","#01665e"],
8: ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e"],
9: ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e"],
10: ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],
11: ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]
},PRGn: {
3: ["#af8dc3","#f7f7f7","#7fbf7b"],
4: ["#7b3294","#c2a5cf","#a6dba0","#008837"],
5: ["#7b3294","#c2a5cf","#f7f7f7","#a6dba0","#008837"],
6: ["#762a83","#af8dc3","#e7d4e8","#d9f0d3","#7fbf7b","#1b7837"],
7: ["#762a83","#af8dc3","#e7d4e8","#f7f7f7","#d9f0d3","#7fbf7b","#1b7837"],
8: ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837"],
9: ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837"],
10: ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],
11: ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]
},PiYG: {
3: ["#e9a3c9","#f7f7f7","#a1d76a"],
4: ["#d01c8b","#f1b6da","#b8e186","#4dac26"],
5: ["#d01c8b","#f1b6da","#f7f7f7","#b8e186","#4dac26"],
6: ["#c51b7d","#e9a3c9","#fde0ef","#e6f5d0","#a1d76a","#4d9221"],
7: ["#c51b7d","#e9a3c9","#fde0ef","#f7f7f7","#e6f5d0","#a1d76a","#4d9221"],
8: ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221"],
9: ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221"],
10: ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],
11: ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]
},RdBu: {
3: ["#ef8a62","#f7f7f7","#67a9cf"],
4: ["#ca0020","#f4a582","#92c5de","#0571b0"],
5: ["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"],
6: ["#b2182b","#ef8a62","#fddbc7","#d1e5f0","#67a9cf","#2166ac"],
7: ["#b2182b","#ef8a62","#fddbc7","#f7f7f7","#d1e5f0","#67a9cf","#2166ac"],
8: ["#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac"],
9: ["#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac"],
10: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],
11: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]
},RdGy: {
3: ["#ef8a62","#ffffff","#999999"],
4: ["#ca0020","#f4a582","#bababa","#404040"],
5: ["#ca0020","#f4a582","#ffffff","#bababa","#404040"],
6: ["#b2182b","#ef8a62","#fddbc7","#e0e0e0","#999999","#4d4d4d"],
7: ["#b2182b","#ef8a62","#fddbc7","#ffffff","#e0e0e0","#999999","#4d4d4d"],
8: ["#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d"],
9: ["#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d"],
10: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],
11: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"]
},RdYlBu: {
3: ["#fc8d59","#ffffbf","#91bfdb"],
4: ["#d7191c","#fdae61","#abd9e9","#2c7bb6"],
5: ["#d7191c","#fdae61","#ffffbf","#abd9e9","#2c7bb6"],
6: ["#d73027","#fc8d59","#fee090","#e0f3f8","#91bfdb","#4575b4"],
7: ["#d73027","#fc8d59","#fee090","#ffffbf","#e0f3f8","#91bfdb","#4575b4"],
8: ["#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4"],
9: ["#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4"],
10: ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],
11: ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]
},Spectral: {
3: ["#fc8d59","#ffffbf","#99d594"],
4: ["#d7191c","#fdae61","#abdda4","#2b83ba"],
5: ["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"],
6: ["#d53e4f","#fc8d59","#fee08b","#e6f598","#99d594","#3288bd"],
7: ["#d53e4f","#fc8d59","#fee08b","#ffffbf","#e6f598","#99d594","#3288bd"],
8: ["#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd"],
9: ["#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd"],
10: ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],
11: ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]
},RdYlGn: {
3: ["#fc8d59","#ffffbf","#91cf60"],
4: ["#d7191c","#fdae61","#a6d96a","#1a9641"],
5: ["#d7191c","#fdae61","#ffffbf","#a6d96a","#1a9641"],
6: ["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"],
7: ["#d73027","#fc8d59","#fee08b","#ffffbf","#d9ef8b","#91cf60","#1a9850"],
8: ["#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850"],
9: ["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"],
10: ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],
11: ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]
},Accent: {
3: ["#7fc97f","#beaed4","#fdc086"],
4: ["#7fc97f","#beaed4","#fdc086","#ffff99"],
5: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0"],
6: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f"],
7: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17"],
8: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"]
},Dark2: {
3: ["#1b9e77","#d95f02","#7570b3"],
4: ["#1b9e77","#d95f02","#7570b3","#e7298a"],
5: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e"],
6: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02"],
7: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d"],
8: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"]
},Paired: {
3: ["#a6cee3","#1f78b4","#b2df8a"],
4: ["#a6cee3","#1f78b4","#b2df8a","#33a02c"],
5: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99"],
6: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c"],
7: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f"],
8: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00"],
9: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6"],
10: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a"],
11: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99"],
12: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"]
},Pastel1: {
3: ["#fbb4ae","#b3cde3","#ccebc5"],
4: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4"],
5: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6"],
6: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc"],
7: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd"],
8: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"],
9: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]
},Pastel2: {
3: ["#b3e2cd","#fdcdac","#cbd5e8"],
4: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4"],
5: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9"],
6: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae"],
7: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc"],
8: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"]
},Set1: {
3: ["#e41a1c","#377eb8","#4daf4a"],
4: ["#e41a1c","#377eb8","#4daf4a","#984ea3"],
5: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"],
6: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33"],
7: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"],
8: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"],
9: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"]
},Set2: {
3: ["#66c2a5","#fc8d62","#8da0cb"],
4: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3"],
5: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854"],
6: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f"],
7: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494"],
8: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"]
},Set3: {
3: ["#8dd3c7","#ffffb3","#bebada"],
4: ["#8dd3c7","#ffffb3","#bebada","#fb8072"],
5: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3"],
6: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462"],
7: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69"],
8: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5"],
9: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9"],
10: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd"],
11: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5"],
12: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"]
}};
if (true) {
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (colorbrewer),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof module === "object" && module.exports) {
module.exports = colorbrewer;
} else {
this.colorbrewer = colorbrewer;
}
}();
/***/ }),
/* 36 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
let bucketUID = 0;
class Buckets extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/*
If input is numeric => args is a breakpoint list
If input is categorical => args is a list of category names to map input
*/
constructor(input, ...args) {
args = args.map(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */]);
let children = {
input
};
args.map((arg, index) => children[`arg${index}`] = arg);
super(children);
this.bucketUID = bucketUID++;
this.numCategories = args.length + 1;
this.args = args;
}
_compile(metadata) {
super._compile(metadata);
this.type = 'category';
this.othersBucket = this.input.type == 'category';
this.args.map(breakpoint => {
if (breakpoint.type != this.input.type) {
throw new Error('Buckets() argument types mismatch');
}
});
}
_applyToShaderSource(uniformIDMaker, propertyTIDMaker) {
const childSources = this.childrenNames.map(name => this[name]._applyToShaderSource(uniformIDMaker, propertyTIDMaker));
let childInlines = {};
childSources.map((source, index) => childInlines[this.childrenNames[index]] = source.inline);
const funcName = `buckets${this.bucketUID}`;
const cmp = this.input.type == 'category' ? '==' : '<';
const elif = (_, index) =>
`${index > 0 ? 'else' : ''} if (x${cmp}(${childInlines[`arg${index}`]})){
return ${index}.;
}`;
const funcBody = this.args.map(elif).join('');
const preface = `float ${funcName}(float x){
${funcBody}
return ${this.numCategories - 1}.;
}`;
return {
preface: childSources.map(s => s.preface).reduce((a, b) => a + b, '') + preface,
inline: `${funcName}(${childInlines.input})`
};
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Buckets;
/***/ }),
/* 37 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
class CIELab extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(l, a, b) {
l = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(l);
a = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(a);
b = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(b);
super({ l: l, a: a, b: b });
}
_compile(meta) {
super._compile(meta);
if (this.l.type != 'float' || this.a.type != 'float' || this.b.type != 'float') {
throw new Error('CIELab() invalid parameters');
}
this.type = 'color';
this._setGenericGLSL(inline =>
`vec4(xyztosrgb(cielabtoxyz(
vec3(
clamp(${inline.l}, 0., 100.),
clamp(${inline.a}, -128., 128.),
clamp(${inline.b}, -128., 128.)
)
)), 1)`
, `
#ifndef cielabtoxyz_fn
#define cielabtoxyz_fn
const mat3 XYZ_2_RGB = (mat3(
3.2404542,-1.5371385,-0.4985314,
-0.9692660, 1.8760108, 0.0415560,
0.0556434,-0.2040259, 1.0572252
));
const float SRGB_GAMMA = 1.0 / 2.2;
vec3 rgb_to_srgb_approx(vec3 rgb) {
return pow(rgb, vec3(SRGB_GAMMA));
}
float f1(float t){
const float sigma = 6./29.;
if (t>sigma){
return t*t*t;
}else{
return 3.*sigma*sigma*(t-4./29.);
}
}
vec3 cielabtoxyz(vec3 c) {
const float xn = 95.047/100.;
const float yn = 100./100.;
const float zn = 108.883/100.;
return vec3(xn*f1((c.x+16.)/116. + c.y/500. ),
yn*f1((c.x+16.)/116.),
zn*f1((c.x+16.)/116. - c.z/200. )
);
}
vec3 xyztorgb(vec3 c){
return c *XYZ_2_RGB;
}
vec3 xyztosrgb(vec3 c) {
return rgb_to_srgb_approx(xyztorgb(c));
}
#endif
`);
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = CIELab;
/***/ }),
/* 38 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
class HSV extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description Color constructor for Hue Saturation Value (HSV) color space
* @param {*} hue hue is the color hue, the coordinates goes from 0 to 1 and is cyclic, i.e.: 0.5=1.5=2.5=-0.5
* @param {*} saturation saturation of the color in the [0,1] range
* @param {*} value value (brightness) of the color in the [0,1] range
*/
constructor(h, s, v) {
h = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(h);
s = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(s);
v = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(v);
super({ h: h, s: s, v: v });
}
_compile(metadata) {
super._compile(metadata);
function typeCheck(v) {
return !(v.type == 'float' || v.type == 'category');
}
if (typeCheck(this.h) || typeCheck(this.s) || typeCheck(this.v)) {
throw new Error('CIELab() invalid parameters');
}
this.type = 'color';
const normalize = (v, hue = false) => {
if (v.type == 'category') {
return `/${hue ? v.numCategories + 1 : v.numCategories}.`;
}
return '';
};
super._setGenericGLSL(inline =>
`vec4(hsv2rgb(vec3(${inline.h}${normalize(this.h, true)}, clamp(${inline.s}${normalize(this.s)}, 0.,1.), clamp(${inline.v}${normalize(this.v)}, 0.,1.))), 1)`
, `
#ifndef HSV2RGB
#define HSV2RGB
vec3 hsv2rgb(vec3 c) {
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
#endif
`);
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = HSV;
/***/ }),
/* 39 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class Linear extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description get the current timestamp
*/
constructor(input, min, max) {
super({ input, min, max });
}
_compile(metadata) {
this.type = 'float';
super._compile(metadata);
this.inlineMaker = (inline) => `((${inline.input}-${inline.min})/(${inline.max}-${inline.min}))`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Linear;
/***/ }),
/* 40 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
//
class Near extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description Near returns zero for inputs that are far away from center.
* This can be useful for filtering out features by setting their size to zero.
*
* _____
* _____/ \_____
*
* @param {*} input
* @param {*} center
* @param {*} threshold size of the allowed distance between input and center that is filtered in (returning one)
* @param {*} falloff size of the distance to be used as a falloff to linearly interpolate between zero and one
*/
constructor(input, center, threshold, falloff) {
input = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(input);
center = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(center);
threshold = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(threshold);
falloff = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(falloff);
super({ input: input, center: center, threshold: threshold, falloff: falloff });
}
_compile(meta) {
super._compile(meta);
if (this.input.type != 'float' || this.center.type != 'float' || this.threshold.type != 'float' || this.falloff.type != 'float') {
throw new Error('Near(): invalid parameter type');
}
this.type = 'float';
this.inlineMaker = (inline) =>
`(1.-clamp((abs(${inline.input}-${inline.center})-${inline.threshold})/${inline.falloff},
0., 1.))`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Near;
/***/ }),
/* 41 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
const nowInit = Date.now();
class Now extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description get the current timestamp
*/
constructor() {
super({ now: Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(0) });
}
_compile(metadata) {
super._compile(metadata);
this.type = 'float';
super.inlineMaker = inline => inline.now;
}
_preDraw(...args) {
this.now.expr = (Date.now() - nowInit) / 1000.;
this.now._preDraw(...args);
}
isAnimated() {
return true;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Now;
/***/ }),
/* 42 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
class Ramp extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description Creates a color ramp based on input and within the range defined by *minKey* and *maxKey*
* @param {*} input
* @param {*} palette
*/
constructor(input, palette, ...args) {
if (args.length > 0) {
throw new Error('ramp(input, palette) only accepts two parameters');
}
input = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(input);
palette = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(palette);
super({ input: input });
this.minKey = 0;
this.maxKey = 1;
this.palette = palette;
}
_compile(meta) {
super._compile(meta);
this.type = 'color';
if (this.input.type == 'category') {
this.maxKey = this.input.numCategories - 1;
}
}
_free(gl) {
gl.deleteTexture(this.texture);
}
_applyToShaderSource(uniformIDMaker, propertyTIDMaker) {
this._UID = uniformIDMaker();
const input = this.input._applyToShaderSource(uniformIDMaker, propertyTIDMaker);
return {
preface: input.preface + `
uniform sampler2D texRamp${this._UID};
uniform float keyMin${this._UID};
uniform float keyWidth${this._UID};
`,
inline: `texture2D(texRamp${this._UID}, vec2((${input.inline}-keyMin${this._UID})/keyWidth${this._UID}, 0.5)).rgba`
};
}
_getColorsFromPalette(input, palette) {
if (palette.type == 'paletteGenerator') {
let colors;
if (input.numCategories) {
// If we are not gonna pop the others we don't need to get the extra color
const subPalette = (palette.tags.includes('qualitative') && !input.othersBucket) ? input.numCategories : input.numCategories - 1;
if (palette.subPalettes[subPalette]) {
colors = palette.subPalettes[subPalette];
} else {
// More categories than palettes, new colors will be created by linear interpolation
colors = palette.getLongestSubPalette();
}
} else {
colors = palette.getLongestSubPalette();
}
// We need to remove the 'others' color if the palette has it (it is a qualitative palette) and if the input doesn't have a 'others' bucket
if (palette.tags.includes('qualitative') && !input.othersBucket) {
colors = colors.slice(0, colors.length - 1);
}
return colors;
} else {
return palette;
}
}
_postShaderCompile(program, gl) {
if (!this.init) {
this.init = true;
this.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.texture);
const level = 0;
const internalFormat = gl.RGBA;
const width = 256;
const height = 1;
const border = 0;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const pixel = new Uint8Array(4 * width);
const colors = this._getColorsFromPalette(this.input, this.palette);
// console.log(this.input.numCategories, this.input.othersBucket, colors, this);
for (var i = 0; i < width; i++) {
const vlowRaw = colors[Math.floor(i / width * (colors.length - 1))];
const vhighRaw = colors[Math.ceil(i / width * (colors.length - 1))];
const vlow = [Object(__WEBPACK_IMPORTED_MODULE_1__utils__["a" /* hexToRgb */])(vlowRaw).r, Object(__WEBPACK_IMPORTED_MODULE_1__utils__["a" /* hexToRgb */])(vlowRaw).g, Object(__WEBPACK_IMPORTED_MODULE_1__utils__["a" /* hexToRgb */])(vlowRaw).b, 255];
const vhigh = [Object(__WEBPACK_IMPORTED_MODULE_1__utils__["a" /* hexToRgb */])(vhighRaw).r, Object(__WEBPACK_IMPORTED_MODULE_1__utils__["a" /* hexToRgb */])(vhighRaw).g, Object(__WEBPACK_IMPORTED_MODULE_1__utils__["a" /* hexToRgb */])(vhighRaw).b, 255];
const m = i / width * (colors.length - 1) - Math.floor(i / width * (colors.length - 1));
const v = vlow.map((low, index) => low * (1. - m) + vhigh[index] * m);
pixel[4 * i + 0] = v[0];
pixel[4 * i + 1] = v[1];
pixel[4 * i + 2] = v[2];
pixel[4 * i + 3] = v[3];
}
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
width, height, border, srcFormat, srcType,
pixel);
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);
}
this.input._postShaderCompile(program, gl);
this._texLoc = gl.getUniformLocation(program, `texRamp${this._UID}`);
this._keyMinLoc = gl.getUniformLocation(program, `keyMin${this._UID}`);
this._keyWidthLoc = gl.getUniformLocation(program, `keyWidth${this._UID}`);
}
_preDraw(drawMetadata, gl) {
this.input._preDraw(drawMetadata, gl);
gl.activeTexture(gl.TEXTURE0 + drawMetadata.freeTexUnit);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.uniform1i(this._texLoc, drawMetadata.freeTexUnit);
gl.uniform1f(this._keyMinLoc, (this.minKey));
gl.uniform1f(this._keyWidthLoc, (this.maxKey) - (this.minKey));
drawMetadata.freeTexUnit++;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Ramp;
/***/ }),
/* 43 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
//TODO refactor to uniformcolor, write color (plain, literal)
class RGBA extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description RGBA color constructor
* @param {*} r red component in the [0,1] range
* @param {*} g green component in the [0,1] range
* @param {*} b blue component in the [0,1] range
* @param {*} a alpha/opacity component in the [0,1] range
*/
constructor(r, g, b, a) {
var color = [r, g, b, a];
color = color.map(x => Number.isFinite(x) ? Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(x) : x);
r = color[0];
g = color[1];
b = color[2];
a = color[3];
super({ r, g, b, a });
}
_compile(meta) {
super._compile(meta);
if (this.r.type != 'float' || this.g.type != 'float' || this.b.type != 'float' || this.a.type != 'float') {
throw new Error('Invalid parameters for RGBA()');
}
this.type = 'color'; // TODO this kind of thing can be refactored into Color class and use: extends ColorExpression
this.inlineMaker = inline => `vec4(${inline.r}, ${inline.g}, ${inline.b}, ${inline.a})`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = RGBA;
/***/ }),
/* 44 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
class Opacity extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description Override the input color opacity
* @param {*} color input color
* @param {*} opacity new opacity
*/
constructor(a, b) {
if (Number.isFinite(b)) {
b = Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(b);
}
super({ a: a, b: b });
}
_compile(meta) {
super._compile(meta);
if (!(this.a.type == 'color' && this.b.type == 'float')) {
throw new Error(`Opacity cannot be performed between '${this.a.type}' and '${this.b.type}'`);
}
this.type = 'color';
this.inlineMaker = inlines => `vec4((${inlines.a}).rgb, ${inlines.b})`;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Opacity;
/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class Top extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(property, buckets) {
// TODO 'cat'
super({ property: property });
this.buckets = buckets; //TODO force fixed literal
}
_compile(metadata) {
super._compile(metadata);
if (this.property.type != 'category') {
throw new Error(`top() first argument must be of type category, but it is of type '${this.property.type}'`);
}
this.type = 'category';
this.numCategories = this.buckets + 1;
this.othersBucket = true;
this._meta = metadata;
}
_applyToShaderSource(uniformIDMaker, propertyTIDMaker) {
this._UID = uniformIDMaker();
const property = this.property._applyToShaderSource(uniformIDMaker, propertyTIDMaker);
return {
preface: property.preface + `uniform sampler2D topMap${this._UID};\n`,
inline: `(255.*texture2D(topMap${this._UID}, vec2(${property.inline}/1024., 0.5)).a)`
};
}
_postShaderCompile(program, gl) {
if (!this.init) {
if (this.buckets > this.property.numCategories) {
this.buckets = this.property.numCategories;
}
this.init = true;
this.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.texture);
const width = 1024;
let pixels = new Uint8Array(4 * width);
const metaColumn = this._meta.columns.find(c => c.name == this.property.name);
metaColumn.categoryNames.map((name, i) => {
if (i < this.buckets) {
pixels[4 * this._meta.categoryIDs[name] + 3] = (i + 1);
}
});
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
width, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
pixels);
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.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
}
this.property._postShaderCompile(program);
this._texLoc = gl.getUniformLocation(program, `topMap${this._UID}`);
}
_preDraw(drawMetadata, gl) {
this.property._preDraw(drawMetadata);
gl.activeTexture(gl.TEXTURE0 + drawMetadata.freeTexUnit);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.uniform1i(this._texLoc, drawMetadata.freeTexUnit);
drawMetadata.freeTexUnit++;
}
//TODO _free
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Top;
/***/ }),
/* 46 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils__ = __webpack_require__(3);
class XYZ extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(x, y, z) {
x = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(x);
y = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(y);
z = Object(__WEBPACK_IMPORTED_MODULE_1__utils__["b" /* implicitCast */])(z);
super({ x: x, y: y, z: z });
}
_compile(meta) {
super._compile(meta);
if (this.x.type != 'float' || this.y.type != 'float' || this.z.type != 'float') {
throw new Error('XYZ() invalid parameters');
}
this.type = 'color';
this._setGenericGLSL(inline =>
`vec4(xyztosrgb((
vec3(
clamp(${inline.x}, -100000., 10000.),
clamp(${inline.y}, -12800., 12800.),
clamp(${inline.z}, -12800., 12800.)
)
)), 1)`
, `
#ifndef cielabtoxyz_fn
#define cielabtoxyz_fn
const mat3 XYZ_2_RGB = (mat3(
3.2404542,-1.5371385,-0.4985314,
-0.9692660, 1.8760108, 0.0415560,
0.0556434,-0.2040259, 1.0572252
));
const mat3 XYZ_2_RGB_T = (mat3(
3.2404542,-0.9692660,0.0556434,
-1.5371385, 1.8760108, -0.2040259,
-0.4985314,0.0415560, 1.0572252
));
const float SRGB_GAMMA = 1.0 / 2.2;
vec3 rgb_to_srgb_approx(vec3 rgb) {
return pow(rgb, vec3(SRGB_GAMMA));
}
float f1(float t){
const float sigma = 6./29.;
if (t>sigma){
return t*t*t;
}else{
return 3.*sigma*sigma*(t-4./29.);
}
}
vec3 cielabtoxyz(vec3 c) {
const float xn = 95.047;
const float yn = 100.;
const float zn = 108.883;
return vec3(xn*f1((c.x+16.)/116. + c.y/500. ),
yn*f1((c.x+16.)/116.),
zn*f1((c.x+16.)/116. - c.z/200. )
);
}
vec3 xyztorgb(vec3 c){
return c * XYZ_2_RGB;
}
vec3 xyztosrgb(vec3 c) {
return rgb_to_srgb_approx(xyztorgb(c));
}
#endif
`);
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = XYZ;
/***/ }),
/* 47 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
class Zoom extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @description get the current zoom level
*/
constructor() {
super({ zoom: Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(0) });
}
_compile(metadata) {
super._compile(metadata);
this.type = 'float';
super.inlineMaker = inline => inline.zoom;
}
_preDraw(drawMetadata, gl) {
this.zoom.expr = drawMetadata.zoom;
this.zoom._preDraw(drawMetadata, gl);
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Zoom;
/***/ }),
/* 48 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
let quantilesUID = 0;
function genQuantiles(global) {
return class Quantiles extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(input, buckets) {
if (!Number.isFinite(buckets)) {
throw new Error('Quantiles() only accepts a fixed number of buckets');
}
let children = {
input
};
let breakpoints = [];
for (let i = 0; i < buckets - 1; i++) {
children[`arg${i}`] = Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(i * 10);
breakpoints.push(children[`arg${i}`]);
}
super(children);
this.quantilesUID = quantilesUID++;
this.numCategories = buckets;
this.buckets = buckets;
this.breakpoints = breakpoints;
}
_compile(metadata) {
super._compile(metadata);
this.type = 'category';
if (global) {
const copy = metadata.sample.map(s => s[this.input.name]);
copy.sort((x, y) => x - y);
this.breakpoints.map((breakpoint, index) => {
const p = (index + 1) / this.buckets;
breakpoint.expr = copy[Math.floor(p * copy.length)];
});
}
}
_getDrawMetadataRequirements() {
return { columns: [this.input.name] };
}
_applyToShaderSource(uniformIDMaker, propertyTIDMaker) {
const childSources = this.childrenNames.map(name => this[name]._applyToShaderSource(uniformIDMaker, propertyTIDMaker));
let childInlines = {};
childSources.map((source, index) => childInlines[this.childrenNames[index]] = source.inline);
const funcName = `quantiles${this.quantilesUID}`;
const elif = (_, index) =>
`${index > 0 ? 'else' : ''} if (x<(${childInlines[`arg${index}`]})){
return ${index + 1}.;
}`;
const funcBody = this.breakpoints.map(elif).join('');
const preface = `float ${funcName}(float x){
${funcBody}
return 0.;
}`;
return {
preface: childSources.map(s => s.preface).reduce((a, b) => a + b, '') + preface,
inline: `${funcName}(${childInlines.input})`
};
}
_preDraw(drawMetadata, gl) {
const column = drawMetadata.columns.find(c => c.name == this.input.name);
let i = 0;
const total = column.accumHistogram[column.histogramBuckets - 1];
const r = Math.random();
let brs = [];
// TODO OPT: this could be faster with binary search
if (!global) {
this.breakpoints.map((breakpoint, index) => {
for (i; i < column.histogramBuckets; i++) {
if (column.accumHistogram[i] >= (index + 1) / this.buckets * total) {
break;
}
}
const percentileValue = i / column.histogramBuckets * (column.max - column.min) + column.min;
brs.push(percentileValue);
breakpoint.expr = percentileValue;
});
}
if (r > 0.99) {
console.log(this.breakpoints.map(br => br.expr));
}
super._preDraw(drawMetadata, gl);
}
getBreakpointList() {
return this.breakpoints.map(br => br.expr);
}
};
}
const Quantiles = genQuantiles(false);
/* harmony export (immutable) */ __webpack_exports__["b"] = Quantiles;
const GlobalQuantiles = genQuantiles(true);
/* harmony export (immutable) */ __webpack_exports__["a"] = GlobalQuantiles;
/***/ }),
/* 49 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
const ViewportMax = generateAggregattion('max');
/* harmony export (immutable) */ __webpack_exports__["i"] = ViewportMax;
const ViewportMin = generateAggregattion('min');
/* harmony export (immutable) */ __webpack_exports__["j"] = ViewportMin;
const ViewportAvg = generateAggregattion('avg');
/* harmony export (immutable) */ __webpack_exports__["g"] = ViewportAvg;
const ViewportSum = generateAggregattion('sum');
/* harmony export (immutable) */ __webpack_exports__["l"] = ViewportSum;
const ViewportCount = generateAggregattion('count');
/* harmony export (immutable) */ __webpack_exports__["h"] = ViewportCount;
const GlobalMax = generateAggregattion('max', true);
/* harmony export (immutable) */ __webpack_exports__["c"] = GlobalMax;
const GlobalMin = generateAggregattion('min', true);
/* harmony export (immutable) */ __webpack_exports__["d"] = GlobalMin;
const GlobalAvg = generateAggregattion('avg', true);
/* harmony export (immutable) */ __webpack_exports__["a"] = GlobalAvg;
const GlobalSum = generateAggregattion('sum', true);
/* harmony export (immutable) */ __webpack_exports__["f"] = GlobalSum;
const GlobalCount = generateAggregattion('count', true);
/* harmony export (immutable) */ __webpack_exports__["b"] = GlobalCount;
const ViewportPercentile = generatePercentile();
/* harmony export (immutable) */ __webpack_exports__["k"] = ViewportPercentile;
const GlobalPercentile = generatePercentile(true);
/* harmony export (immutable) */ __webpack_exports__["e"] = GlobalPercentile;
function generateAggregattion(metadataPropertyName, global) {
return class Aggregattion extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @param {*} property
*/
constructor(property) {
super({ value: Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(0) });
this.property = property;
}
_compile(metadata) {
console.log(metadata);
super._compile(metadata);
this.property._compile(metadata);
this.type = 'float';
super.inlineMaker = inline => inline.value;
if (global) {
this.value.expr = metadata.columns.find(c => c.name == this.property.name)[metadataPropertyName];
}
}
_getMinimumNeededSchema() {
return this.property._getMinimumNeededSchema();
}
_getDrawMetadataRequirements() {
return { columns: [this.property.name] };
}
_preDraw(drawMetadata, gl) {
const column = drawMetadata.columns.find(c => c.name == this.property.name);
if (!global) {
this.value.expr = column[metadataPropertyName];
}
if (Math.random() > 0.999) {
console.log(metadataPropertyName, this.property.name, this.value.expr);
}
this.value._preDraw(drawMetadata, gl);
}
getValue() {
return this.value.expr;
}
};
}
function generatePercentile(global) {
return class Percentile extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
/**
* @jsapi
* @param {*} property
*/
constructor(property, percentile) {
if (!Number.isFinite(percentile)) {
throw new Error('Percentile must be a fixed literal number');
}
super({ value: Object(__WEBPACK_IMPORTED_MODULE_1__functions__["float"])(0) });
this.property = property;
this.percentile = percentile;
}
_compile(metadata) {
super._compile(metadata);
this.property._compile(metadata);
this.type = 'float';
super.inlineMaker = inline => inline.value;
if (global) {
const copy = metadata.sample.map(s => s[this.property.name]);
copy.sort((x, y) => x - y);
const p = this.percentile / 100;
this.value.expr = copy[Math.floor(p * copy.length)];
}
}
_getMinimumNeededSchema() {
return this.property._getMinimumNeededSchema();
}
_getDrawMetadataRequirements() {
return { columns: [this.property.name] };
}
_preDraw(drawMetadata, gl) {
if (!global) {
const column = drawMetadata.columns.find(c => c.name == this.property.name);
const total = column.accumHistogram[999];
// TODO OPT: this could be faster with binary search
for (var i = 0; i < column.histogramBuckets; i++) {
if (column.accumHistogram[i] >= this.percentile / 100 * total) {
break;
}
}
const br = i / column.histogramBuckets * (column.max - column.min) + column.min;
this.value.expr = br;
}
if (Math.random() > 0.99) {
console.log(`percentile${this.percentile}`, this.property.name, this.value.expr);
}
this.value._preDraw(drawMetadata, gl);
}
getValue() {
return this.value.expr;
}
};
}
/***/ }),
/* 50 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__expression__ = __webpack_require__(0);
class Width extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor() {
super({});
this.type = 'propertyReference';
}
}
/* harmony export (immutable) */ __webpack_exports__["d"] = Width;
class Asc extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(by) {
super({});
if (!(by instanceof Width)) {
throw new Error('Asc() only accepts \'width()\' for now');
}
this.type = 'orderer';
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Asc;
class Desc extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor(by) {
super({});
if (!(by instanceof Width)) {
throw new Error('Desc() only accepts \'width()\' for now');
}
this.type = 'orderer';
}
}
/* harmony export (immutable) */ __webpack_exports__["b"] = Desc;
class NoOrder extends __WEBPACK_IMPORTED_MODULE_0__expression__["a" /* default */] {
constructor() {
super({});
this.type = 'orderer';
}
}
/* harmony export (immutable) */ __webpack_exports__["c"] = NoOrder;
/***/ }),
/* 51 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__core_renderer__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__client_rsys__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(5);
// TODO: add docs / API
class GeoJSON extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] {
constructor(data) {
super();
data = data || {};
if (data.type === 'FeatureCollection') {
this._features = data.features || [];
} else if (data.type === 'Feature') {
this._features = [data];
}
else {
throw Error('No valid GeoJSON data');
}
this._status = 'init'; // init -> metadata -> data
this._type = ''; // Point, LineString, MultiLineString, Polygon, MultiPolygon
}
_getFeatures(data) {
switch (data.type) {
case 'FeatureCollection':
this._features = data.features || [];
break;
case 'Feature':
this._features = [data];
break;
default:
throw Error('No valid GeoJSON data');
}
}
bindLayer(addDataframe, removeDataframe) {
this._addDataframe = addDataframe;
this._removeDataframe = removeDataframe;
}
requestData() {
// TODO: split in two functions: (metadata) / (data)
//
if (this._status === 'init') {
this._status = 'metadata';
return new Promise(resolve => {
let metadata = {};
resolve(metadata);
});
} else if (this._status === 'metadata') {
this._status = 'data';
let geometry = null;
const numFeatures = this._features.length;
const properties = {};
for (let i = 0; i < numFeatures; i++) {
const feature = this._features[i];
if (feature.type === 'Feature') {
const type = feature.geometry.type;
const coordinates = feature.geometry.coordinates;
if (!this._type) {
this._type = type;
} else if (this._type !== type) {
throw Error(`Multiple types not supported: ${this._type}, ${type}`);
}
if (type === 'Point') {
if (!geometry) {
geometry = new Float32Array(numFeatures * 2);
}
const point = this._computePointGeometry(coordinates);
geometry[2 * i + 0] = point.x;
geometry[2 * i + 1] = point.y;
}
else if (type === 'LineString') {
if (!geometry) {
geometry = [];
}
const line = this._computeLineStringGeometry(coordinates);
geometry.push([line]);
}
else if (type === 'MultiLineString') {
if (!geometry) {
geometry = [];
}
const multiline = this._computeMultiLineStringGeometry(coordinates);
geometry.push(multiline);
}
else if (type === 'Polygon') {
if (!geometry) {
geometry = [];
}
const polygon = this._computePolygonGeometry(coordinates);
geometry.push([polygon]);
}
else if (type === 'MultiPolygon') {
if (!geometry) {
geometry = [];
}
const multipolygon = this._computeMultiPolygonGeometry(coordinates);
geometry.push(multipolygon);
}
}
}
const dataframe = new __WEBPACK_IMPORTED_MODULE_1__core_renderer__["a" /* Dataframe */](
{ x: 0, y: 0 },
1,
geometry,
properties,
);
dataframe.type = this._getDataframeType(this._type);
dataframe.active = true;
dataframe.size = numFeatures;
this._addDataframe(dataframe);
}
}
_getDataframeType(type) {
if (type === 'Point') return 'point';
if (type === 'LineString' || type === 'MultiLineString') return 'line';
if (type === 'Polygon' || type === 'MultiPolygon') return 'polygon';
return '';
}
_computePointGeometry(data) {
const lat = data[1];
const lng = data[0];
const wm = __WEBPACK_IMPORTED_MODULE_3__util__["g" /* wmProjection */]({ lat, lng });
return __WEBPACK_IMPORTED_MODULE_2__client_rsys__["c" /* wToR */](wm.x, wm.y, { scale: __WEBPACK_IMPORTED_MODULE_3__util__["b" /* WM_R */], center: { x: 0, y: 0 } });
}
_computeLineStringGeometry(data) {
let line = [];
for (let i = 0; i < data.length; i++) {
const point = this._computePointGeometry(data[i]);
line.push(point.x, point.y);
}
return line;
}
_computeMultiLineStringGeometry(data) {
let multiline = [];
for (let i = 0; i < data.length; i++) {
let line = this._computeLineStringGeometry(data[i]);
if (line.length > 0) {
multiline.push(line);
}
}
return multiline;
}
_computePolygonGeometry(data) {
let polygon = {
flat: [],
holes: []
};
let holeIndex = 0;
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].length; j++) {
const point = this._computePointGeometry(data[i][j]);
polygon.flat.push(point.x, point.y);
}
if (!this._isClockWise(data[i])) {
if (i > 0) {
holeIndex += data[i - 1].length;
polygon.holes.push(holeIndex);
} else {
throw new Error('First polygon ring MUST be external');
}
}
}
return polygon;
}
_computeMultiPolygonGeometry(data) {
let multipolygon = [];
for (let i = 0; i < data.length; i++) {
let polygon = this._computePolygonGeometry(data[i]);
if (polygon.flat.length > 0) {
multipolygon.push(polygon);
}
}
return multipolygon;
}
_isClockWise(vertices) {
let total = 0;
let pt1 = vertices[0], pt2;
for (let i = 0; i < vertices.length - 1; i++) {
pt2 = vertices[i + 1];
total += (pt2[1] - pt1[1]) * (pt2[0] + pt1[0]);
pt1 = pt2;
}
return total >= 0;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = GeoJSON;
/***/ }),
/* 52 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__point__ = __webpack_require__(53);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__tris__ = __webpack_require__(54);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__lines__ = __webpack_require__(55);
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_0__point__; });
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_1__tris__; });
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_2__lines__; });
/***/ }),
/* 53 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
//TODO performance optimization: direct stroke/color/widths from uniform instead of texture read when possible
/*
Antialiasing
I think that the current antialiasing method is correct.
It is certainly fast since it uses the distance to the circumference.
The results have been checked against a reference 4x4 sampling method.
The vertex shader is responsible for the oversizing of the points to "enable" conservative rasterization.
See https://developer.nvidia.com/content/dont-be-conservative-conservative-rasterization
This oversizing requires a change of the coordinate space that must be reverted in the fragment shader.
This is done with `sizeNormalizer`.
Debugging antialiasing is hard. I'm gonna leave here a few helpers:
float referenceAntialias(vec2 p){
float alpha=0.;
for (float x=-0.75; x<1.; x+=0.5){
for (float y=-0.75; y<1.; y+=0.5){
vec2 p2 = p + vec2(x,y)*dp;
if (length(p2)<1.){
alpha+=1.;
}
}
}
return alpha/16.;
}
float noAntialias(vec2 p){
if (length(p)<1.){
return 1.;
}
return 0.;
}
Use this to check that the affected antiliased pixels are ok:
if (c.a==1.||c.a==0.){
gl_FragColor = vec4(1,0,0,1);
return;
}
*/
const VS = `
precision highp float;
attribute vec2 vertexPosition;
attribute vec2 featureID;
uniform vec2 vertexScale;
uniform vec2 vertexOffset;
uniform float orderMinWidth;
uniform float orderMaxWidth;
uniform sampler2D colorTex;
uniform sampler2D widthTex;
uniform sampler2D colorStrokeTex;
uniform sampler2D strokeWidthTex;
uniform sampler2D filterTex;
//TODO order bucket texture
varying highp vec4 color;
varying highp vec4 stroke;
varying highp float dp;
varying highp float sizeNormalizer;
varying highp float fillScale;
varying highp float strokeScale;
void main(void) {
color = texture2D(colorTex, featureID);
stroke = texture2D(colorStrokeTex, featureID);
float filtering = texture2D(filterTex, featureID).a;
color.a *= filtering;
stroke.a *= filtering;
float size = 64.*texture2D(widthTex, featureID).a;
float fillSize = size;
float strokeSize = 64.*texture2D(strokeWidthTex, featureID).a;
size+=strokeSize*0.5;
fillScale=size/fillSize;
strokeScale=size/max(0.001, (fillSize-strokeSize*0.5));
if (fillScale==strokeScale){
stroke.a=0.;
}
gl_PointSize = size+2.;
dp = 1.0/(size+1.);
sizeNormalizer = (size+1.)/(size);
vec4 p = vec4(vertexScale*vertexPosition-vertexOffset, 0.5, 1.);
if (size==0. || (stroke.a==0. && color.a==0.) || size<orderMinWidth || size>orderMaxWidth){
p.x=10000.;
}
gl_Position = p;
}`;
/* harmony export (immutable) */ __webpack_exports__["VS"] = VS;
const FS = `
precision highp float;
varying lowp vec4 color;
varying lowp vec4 stroke;
varying highp float dp;
varying highp float sizeNormalizer;
varying highp float fillScale;
varying highp float strokeScale;
float distanceAntialias(vec2 p){
return 1. - smoothstep(1.-dp*1.4142, 1.+dp*1.4142, length(p));
}
void main(void) {
vec2 p = (2.*gl_PointCoord-vec2(1.))*sizeNormalizer;
vec4 c = color;
vec4 s = stroke;
c.a *= distanceAntialias(p*fillScale);
c.rgb*=c.a;
s.a *= distanceAntialias(p);
s.a *= 1.-distanceAntialias((strokeScale)*p);
s.rgb*=s.a;
c=s+(1.-s.a)*c;
gl_FragColor = c;
}`;
/* harmony export (immutable) */ __webpack_exports__["FS"] = FS;
/***/ }),
/* 54 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
const VS = `
precision highp float;
attribute vec2 vertexPosition;
attribute vec2 featureID;
uniform vec2 vertexScale;
uniform vec2 vertexOffset;
uniform sampler2D colorTex;
uniform sampler2D filterTex;
varying highp vec4 color;
void main(void) {
vec4 c = texture2D(colorTex, featureID);
float filtering = texture2D(filterTex, featureID).a;
c.a *= filtering;
vec4 p = vec4(vertexScale*vertexPosition-vertexOffset, 0.5, 1.);
if (c.a==0.){
p.x=10000.;
}
color = vec4(c.rgb*c.a, c.a);
gl_Position = p;
}`;
/* harmony export (immutable) */ __webpack_exports__["VS"] = VS;
const FS = `
precision highp float;
varying highp vec4 color;
void main(void) {
gl_FragColor = color;
}`;
/* harmony export (immutable) */ __webpack_exports__["FS"] = FS;
/***/ }),
/* 55 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
const VS = `
precision highp float;
attribute vec2 vertexPosition;
attribute vec2 featureID;
attribute vec2 normal;
uniform vec2 vertexScale;
uniform vec2 vertexOffset;
uniform sampler2D colorTex;
uniform sampler2D widthTex;
uniform sampler2D filterTex;
varying lowp vec4 color;
void main(void) {
color = texture2D(colorTex, featureID);
float filtering = texture2D(filterTex, featureID).a;
color.a *= filtering;
color.rgb *= color.a;
float size = 64.*texture2D(widthTex, featureID).a;
vec4 p = vec4(vertexScale*(vertexPosition)+normal*0.001*size-vertexOffset, 0.5, 1.);
if (size==0. || color.a==0.){
p.x=10000.;
}
gl_Position = p;
}`;
/* harmony export (immutable) */ __webpack_exports__["VS"] = VS;
const FS = `
precision highp float;
varying lowp vec4 color;
void main(void) {
gl_FragColor = color;
}`;
/* harmony export (immutable) */ __webpack_exports__["FS"] = FS;
/***/ }),
/* 56 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
//TODO Discuss size scaling constant, maybe we need to remap using an exponential map
const VS = `
precision highp float;
attribute vec2 vertex;
varying vec2 uv;
void main(void) {
uv = vertex*0.5+vec2(0.5);
gl_Position = vec4(vertex, 0.5, 1.);
}
`;
/* harmony export (immutable) */ __webpack_exports__["VS"] = VS;
const FS = `
precision highp float;
varying vec2 uv;
$PREFACE
uniform sampler2D property0;
uniform sampler2D property1;
uniform sampler2D property2;
uniform sampler2D property3;
void main(void) {
// TODO texture reads should be dynamic to improve Texture Unit utilization
float p0=texture2D(property0, uv).a;
float p1=texture2D(property1, uv).a;
float p2=texture2D(property2, uv).a;
float p3=texture2D(property3, uv).a;
gl_FragColor = $INLINE;
}
`;
/* harmony export (immutable) */ __webpack_exports__["FS"] = FS;
/***/ }),
/* 57 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
const VS = `
precision highp float;
attribute vec2 vertex;
varying vec2 uv;
void main(void) {
uv = vertex*0.5+vec2(0.5);
gl_Position = vec4(vertex, 0.5, 1.);
}
`;
/* harmony export (immutable) */ __webpack_exports__["b"] = VS;
const FS = `
precision highp float;
varying vec2 uv;
uniform sampler2D aaTex;
void main(void) {
vec4 aa = texture2D(aaTex, uv);
gl_FragColor = aa;
}
`;
/* harmony export (immutable) */ __webpack_exports__["a"] = FS;
/***/ }),
/* 58 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/**
* To avoid recompiling the shaders we keep a shader cache.
* We need a different shader per webgl context so we use a 2 level cache where at the first level
* the webgl context is the key and at the second level the shader code is the cache key.
*/
class ShaderCache {
constructor() {
this.caches = new WeakMap();
}
get(gl, shadercode) {
if (this.caches.has(gl)) {
let cache = this.caches.get(gl);
if (cache[shadercode]) {
return cache[shadercode];
}
}
}
set(gl, shadercode, shader) {
if (this.caches.has(gl)) {
let cache = this.caches.get(gl);
cache[shadercode] = shader;
} else {
let cache = new WeakMap;
cache[shadercode] = shader;
this.caches.set(gl, cache);
}
}
has(gl, shadercode) {
return this.get(gl, shadercode) !== undefined;
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = ShaderCache;
/***/ }),
/* 59 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_earcut__ = __webpack_require__(60);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_earcut___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_earcut__);
/**
* @typedef {object} Dataframe - Point in renderer coordinates space
* @property {RPoint} center
* @property {number} scale
* @property {geom} geometry
* @property {Properties} properties
*/
class Dataframe {
constructor(center, scale, geom, properties) {
this.center = center;
this.scale = scale;
this.geom = geom;
this.properties = properties;
}
bind(renderer) {
const gl = renderer.gl;
this.renderer = renderer;
this.propertyTex = [];
const decodedGeom = decodeGeom(this.type, this.geom);
var points = decodedGeom.geometry;
this.numVertex = points.length / 2;
this.breakpointList = decodedGeom.breakpointList;
this.numFeatures = this.breakpointList.length || this.numVertex;
this._genDataframePropertyTextures(gl);
const width = this.renderer.RTT_WIDTH;
const height = Math.ceil(this.numFeatures / width);
this.setStyle = (style) => {
this.style = style;
};
this.style = null;
this.vertexBuffer = gl.createBuffer();
this.featureIDBuffer = gl.createBuffer();
this.texColor = this._createStyleTileTexture(this.numFeatures);
this.texWidth = this._createStyleTileTexture(this.numFeatures);
this.texStrokeColor = this._createStyleTileTexture(this.numFeatures);
this.texStrokeWidth = this._createStyleTileTexture(this.numFeatures);
this.texFilter = this._createStyleTileTexture(this.numFeatures);
var ids = new Float32Array(points.length);
let index = 0;
for (var i = 0; i < points.length; i += 2) {
if ((!this.breakpointList.length && i > 0) || i == this.breakpointList[index]) {
index++;
}
ids[i + 0] = ((index) % width) / (width - 1);
ids[i + 1] = height > 1 ? Math.floor((index) / width) / (height - 1) : 0.5;
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);
if (decodedGeom.normals) {
this.normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);
gl.bufferData(gl.ARRAY_BUFFER, decodedGeom.normals, gl.STATIC_DRAW);
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.featureIDBuffer);
gl.bufferData(gl.ARRAY_BUFFER, ids, gl.STATIC_DRAW);
}
_genDataframePropertyTextures() {
const gl = this.renderer.gl;
const width = this.renderer.RTT_WIDTH;
const height = Math.ceil(this.numFeatures / width);
this.height = height;
this.propertyID = {}; //Name => PID
this.propertyCount = 0;
for (var k in this.properties) {
if (this.properties.hasOwnProperty(k) && this.properties[k].length > 0) {
var propertyID = this.propertyID[k];
if (propertyID === undefined) {
propertyID = this.propertyCount;
this.propertyCount++;
this.propertyID[k] = propertyID;
}
this.propertyTex[propertyID] = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.propertyTex[propertyID]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA,
width, height, 0, gl.ALPHA, gl.FLOAT,
this.properties[k]);
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.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
}
}
}
_createStyleTileTexture(numFeatures) {
// TODO we are wasting 75% of the memory for the scalar attributes (width, strokeWidth),
// since RGB components are discarded
const gl = this.renderer.gl;
const width = this.renderer.RTT_WIDTH;
const height = Math.ceil(numFeatures / width);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE,
null);
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.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
return texture;
}
free() {
if (this.propertyTex) {
const gl = this.renderer.gl;
this.propertyTex.map(tex => gl.deleteTexture(tex));
gl.deleteTexture(this.texColor);
gl.deleteTexture(this.texStrokeColor);
gl.deleteTexture(this.texWidth);
gl.deleteTexture(this.texStrokeWidth);
gl.deleteTexture(this.texFilter);
gl.deleteBuffer(this.vertexBuffer);
gl.deleteBuffer(this.featureIDBuffer);
this.texColor = 'freed';
this.texWidth = 'freed';
this.texStrokeColor = 'freed';
this.texStrokeWidth = 'freed';
this.texFilter = 'freed';
this.vertexBuffer = 'freed';
this.featureIDBuffer = 'freed';
this.propertyTex = null;
}
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Dataframe;
function getLineNormal(a, b) {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
return normalize([-dy, dx]);
}
function normalize(v) {
const s = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
return [v[0] / s, v[1] / s];
}
// Decode a tile geometry
// If the geometry type is 'point' it will pass trough the geom (the vertex array)
// If the geometry type is 'polygon' it will triangulate the polygon list (geom)
// geom will be a list of polygons in which each polygon will have a flat array of vertices and a list of holes indices
// Example:
/* let geom = [
{
flat: [
0.,0., 1.,0., 1.,1., 0.,1., 0.,0, //A square
0.25,0.25, 0.75,0.25, 0.75,0.75, 0.25,0.75, 0.25,0.25//A small square
]
holes: [5]
}
]
*/
// If the geometry type is 'line' it will generate the appropriate zero-sized, vertex-shader expanded triangle list with mitter joints.
// The geom will be an array of coordinates in this case
function decodeGeom(geomType, geom) {
if (geomType == 'point') {
return {
geometry: geom,
breakpointList: []
};
} else if (geomType == 'polygon') {
let vertexArray = []; //Array of triangle vertices
let breakpointList = []; // Array of indices (to vertexArray) that separate each feature
geom.map(feature => {
feature.map(polygon => {
const triangles = __WEBPACK_IMPORTED_MODULE_0_earcut__(polygon.flat, polygon.holes);
triangles.map(index => {
vertexArray.push(polygon.flat[2 * index]);
vertexArray.push(polygon.flat[2 * index + 1]);
});
});
breakpointList.push(vertexArray.length);
});
return {
geometry: new Float32Array(vertexArray),
breakpointList
};
} else if (geomType == 'line') {
let geometry = [];
let normals = [];
let breakpointList = []; // Array of indices (to vertexArray) that separate each feature
geom.map(feature => {
feature.map(line => {
// Create triangulation
for (let i = 0; i < line.length - 2; i += 2) {
const a = [line[i + 0], line[i + 1]];
const b = [line[i + 2], line[i + 3]];
if (i > 0) {
var prev = [line[i + -2], line[i + -1]];
var nprev = getLineNormal(a, prev);
}
if (i < line.length - 4) {
var next = [line[i + 4], line[i + 5]];
var nnext = getLineNormal(next, b);
}
let normal = getLineNormal(b, a);
let na = normal;
let nb = normal;
//TODO bug, cartesian interpolation is not correct, should use polar coordinates for the interpolation
if (prev) {
na = normalize([
normal[0] * 0.5 + nprev[0] * 0.5,
normal[1] * 0.5 + nprev[1] * 0.5,
]);
}
if (next) {
nb = normalize([
normal[0] * 0.5 + nnext[0] * 0.5,
normal[1] * 0.5 + nnext[1] * 0.5,
]);
}
normals.push(-na[0], -na[1]);
normals.push(na[0], na[1]);
normals.push(-nb[0], -nb[1]);
normals.push(na[0], na[1]);
normals.push(nb[0], nb[1]);
normals.push(-nb[0], -nb[1]);
normal = [0, 0];
//First triangle
geometry.push(a[0] - 0.01 * normal[0]);
geometry.push(a[1] - 0.01 * normal[1]);
geometry.push(a[0] + 0.01 * normal[0]);
geometry.push(a[1] + 0.01 * normal[1]);
geometry.push(b[0] - 0.01 * normal[0]);
geometry.push(b[1] - 0.01 * normal[1]);
//Second triangle
geometry.push(a[0] + 0.01 * normal[0]);
geometry.push(a[1] + 0.01 * normal[1]);
geometry.push(b[0] + 0.01 * normal[0]);
geometry.push(b[1] + 0.01 * normal[1]);
geometry.push(b[0] - 0.01 * normal[0]);
geometry.push(b[1] - 0.01 * normal[1]);
}
});
breakpointList.push(geometry.length);
});
return {
geometry: new Float32Array(geometry),
breakpointList,
normals: new Float32Array(normals)
};
} else {
throw new Error(`Unimplemented geometry type: '${geomType}'`);
}
}
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = earcut;
module.exports.default = earcut;
function earcut(data, holeIndices, dim) {
dim = dim || 2;
var hasHoles = holeIndices && holeIndices.length,
outerLen = hasHoles ? holeIndices[0] * dim : data.length,
outerNode = linkedList(data, 0, outerLen, dim, true),
triangles = [];
if (!outerNode) return triangles;
var minX, minY, maxX, maxY, x, y, invSize;
if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if (data.length > 80 * dim) {
minX = maxX = data[0];
minY = maxY = data[1];
for (var i = dim; i < outerLen; i += dim) {
x = data[i];
y = data[i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
// minX, minY and invSize are later used to transform coords into integers for z-order calculation
invSize = Math.max(maxX - minX, maxY - minY);
invSize = invSize !== 0 ? 1 / invSize : 0;
}
earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
return triangles;
}
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
var i, last;
if (clockwise === (signedArea(data, start, end, dim) > 0)) {
for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
} else {
for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
}
if (last && equals(last, last.next)) {
removeNode(last);
last = last.next;
}
return last;
}
// eliminate colinear or duplicate points
function filterPoints(start, end) {
if (!start) return start;
if (!end) end = start;
var p = start,
again;
do {
again = false;
if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
removeNode(p);
p = end = p.prev;
if (p === p.next) break;
again = true;
} else {
p = p.next;
}
} while (again || p !== end);
return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
if (!ear) return;
// interlink polygon nodes in z-order
if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
var stop = ear,
prev, next;
// iterate through ears, slicing them one by one
while (ear.prev !== ear.next) {
prev = ear.prev;
next = ear.next;
if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
// cut off the triangle
triangles.push(prev.i / dim);
triangles.push(ear.i / dim);
triangles.push(next.i / dim);
removeNode(ear);
// skipping the next vertice 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(ear, triangles, dim);
earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
// as a last resort, try splitting the remaining polygon into two
} else if (pass === 2) {
splitEarcut(ear, triangles, dim, minX, minY, invSize);
}
break;
}
}
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
var p = ear.next.next;
while (p !== ear.prev) {
if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.next;
}
return true;
}
function isEarHashed(ear, minX, minY, invSize) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
// z-order range for the current triangle bbox;
var minZ = zOrder(minTX, minTY, minX, minY, invSize),
maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
var p = ear.prevZ,
n = ear.nextZ;
// look for points inside the triangle in both directions
while (p && p.z >= minZ && n && n.z <= maxZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.prevZ;
if (n !== ear.prev && n !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, 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 !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, 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 !== ear.prev && n !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
area(n.prev, n, n.next) >= 0) return false;
n = n.nextZ;
}
return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
var p = start;
do {
var a = p.prev,
b = p.next.next;
if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
triangles.push(a.i / dim);
triangles.push(p.i / dim);
triangles.push(b.i / dim);
// remove two nodes involved
removeNode(p);
removeNode(p.next);
p = start = b;
}
p = p.next;
} while (p !== start);
return p;
}
// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
// look for a valid diagonal that divides the polygon into two
var a = start;
do {
var b = a.next.next;
while (b !== a.prev) {
if (a.i !== b.i && isValidDiagonal(a, b)) {
// split the polygon in two by the diagonal
var c = splitPolygon(a, b);
// filter colinear points around the cuts
a = filterPoints(a, a.next);
c = filterPoints(c, c.next);
// run earcut on each half
earcutLinked(a, triangles, dim, minX, minY, invSize);
earcutLinked(c, triangles, dim, minX, minY, invSize);
return;
}
b = b.next;
}
a = a.next;
} while (a !== start);
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
var queue = [],
i, len, start, end, list;
for (i = 0, len = holeIndices.length; i < len; i++) {
start = holeIndices[i] * dim;
end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
list = linkedList(data, start, end, dim, false);
if (list === list.next) list.steiner = true;
queue.push(getLeftmost(list));
}
queue.sort(compareX);
// process holes from left to right
for (i = 0; i < queue.length; i++) {
eliminateHole(queue[i], outerNode);
outerNode = filterPoints(outerNode, outerNode.next);
}
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) {
outerNode = findHoleBridge(hole, outerNode);
if (outerNode) {
var b = splitPolygon(outerNode, hole);
filterPoints(b, b.next);
}
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
var p = outerNode,
hx = hole.x,
hy = hole.y,
qx = -Infinity,
m;
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do {
if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
if (x <= hx && x > qx) {
qx = x;
if (x === hx) {
if (hy === p.y) return p;
if (hy === p.next.y) return p.next;
}
m = p.x < p.next.x ? p : p.next;
}
}
p = p.next;
} while (p !== outerNode);
if (!m) return null;
if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
var stop = m,
mx = m.x,
my = m.y,
tanMin = Infinity,
tan;
p = m.next;
while (p !== stop) {
if (hx >= p.x && p.x >= mx && hx !== p.x &&
pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
m = p;
tanMin = tan;
}
}
p = p.next;
}
return m;
}
// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, invSize) {
var p = start;
do {
if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next;
} while (p !== start);
p.prevZ.nextZ = null;
p.prevZ = null;
sortLinked(p);
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
var i, p, q, e, tail, numMerges, pSize, qSize,
inSize = 1;
do {
p = list;
list = null;
tail = null;
numMerges = 0;
while (p) {
numMerges++;
q = p;
pSize = 0;
for (i = 0; i < inSize; i++) {
pSize++;
q = q.nextZ;
if (!q) break;
}
qSize = inSize;
while (pSize > 0 || (qSize > 0 && q)) {
if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
e = p;
p = p.nextZ;
pSize--;
} else {
e = q;
q = q.nextZ;
qSize--;
}
if (tail) tail.nextZ = e;
else list = e;
e.prevZ = tail;
tail = e;
}
p = q;
}
tail.nextZ = null;
inSize *= 2;
} while (numMerges > 1);
return list;
}
// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder(x, y, minX, minY, invSize) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * (x - minX) * invSize;
y = 32767 * (y - minY) * invSize;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
// find the leftmost node of a polygon ring
function getLeftmost(start) {
var p = start,
leftmost = start;
do {
if (p.x < leftmost.x) 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) >= 0 &&
(ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
(bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
// 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);
}
// 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) {
if ((equals(p1, q1) && equals(p2, q2)) ||
(equals(p1, q2) && equals(p2, q1))) return true;
return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
var p = a;
do {
if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
intersects(p, p.next, a, b)) return true;
p = p.next;
} while (p !== a);
return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
return area(a.prev, a, a.next) < 0 ?
area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
var p = a,
inside = false,
px = (a.x + b.x) / 2,
py = (a.y + b.y) / 2;
do {
if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
(px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
inside = !inside;
p = p.next;
} while (p !== a);
return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
var a2 = new Node(a.i, a.x, a.y),
b2 = new Node(b.i, b.x, b.y),
an = a.next,
bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
var p = new Node(i, x, y);
if (!last) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next.prev = p;
last.next = p;
}
return p;
}
function removeNode(p) {
p.next.prev = p.prev;
p.prev.next = p.next;
if (p.prevZ) p.prevZ.nextZ = p.nextZ;
if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}
function Node(i, x, y) {
// vertice index in coordinates array
this.i = i;
// vertex coordinates
this.x = x;
this.y = y;
// previous and next vertice nodes in a polygon ring
this.prev = null;
this.next = null;
// z-order curve value
this.z = null;
// previous and next nodes in z-order
this.prevZ = null;
this.nextZ = null;
// indicates whether this is a steiner point
this.steiner = false;
}
// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
var hasHoles = holeIndices && holeIndices.length;
var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
if (hasHoles) {
for (var i = 0, len = holeIndices.length; i < len; i++) {
var start = holeIndices[i] * dim;
var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
polygonArea -= Math.abs(signedArea(data, start, end, dim));
}
}
var trianglesArea = 0;
for (i = 0; i < triangles.length; i += 3) {
var a = triangles[i] * dim;
var b = triangles[i + 1] * dim;
var c = triangles[i + 2] * dim;
trianglesArea += Math.abs(
(data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
(data[a] - data[b]) * (data[c + 1] - data[a + 1]));
}
return polygonArea === 0 && trianglesArea === 0 ? 0 :
Math.abs((trianglesArea - polygonArea) / polygonArea);
};
function signedArea(data, start, end, dim) {
var sum = 0;
for (var i = start, j = end - dim; i < end; i += dim) {
sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
j = i;
}
return sum;
}
// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
var dim = data[0][0].length,
result = {vertices: [], holes: [], dimensions: dim},
holeIndex = 0;
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
}
if (i > 0) {
holeIndex += data[i - 1].length;
result.holes.push(holeIndex);
}
}
return result;
};
/***/ }),
/* 61 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__base_windshaft__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__ = __webpack_require__(6);
class Dataset extends __WEBPACK_IMPORTED_MODULE_1__base_windshaft__["a" /* default */] {
/**
* Create a carto.source.Dataset.
*
* @param {string} tableName - The name of an existing table
* @param {object} auth
* @param {string} auth.apiKey - API key used to authenticate against CARTO
* @param {string} auth.user - Name of the user
* @param {object} config
* @param {string} [config.serverURL='https://{user}.carto.com'] - URL of the CARTO Maps API server
*
* @example
* new carto.source.Dataset('european_cities', {
* apiKey: 'YOUR_API_KEY_HERE',
* user: 'YOUR_USERNAME_HERE'
* });
*
* @fires CartoError
*
* @constructor Dataset
* @extends carto.source.Base
* @memberof carto.source
* @api
*/
constructor(tableName, auth, config) {
super();
this._checkTableName(tableName);
this._tableName = tableName;
this.initialize(auth, config);
}
_checkTableName(tableName) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](tableName)) {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'tableNameRequired');
}
if (!__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](tableName)) {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'tableNameStringRequired');
}
if (tableName === '') {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'nonValidTableName');
}
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Dataset;
/***/ }),
/* 62 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_renderer__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__rsys__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_pbf__ = __webpack_require__(63);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_pbf___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_pbf__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_lru_cache__ = __webpack_require__(65);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_lru_cache___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_lru_cache__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__windshaft_filtering__ = __webpack_require__(73);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__mapbox_vector_tile__ = __webpack_require__(74);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__mapbox_vector_tile___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__mapbox_vector_tile__);
const SAMPLE_ROWS = 1000;
const MIN_FILTERING = 500000;
// Get dataframes <- MVT <- Windshaft
// Get metadata
// Instantiate map Windshaft
// Requrest SQL API (temp)
// Cache dataframe
class Windshaft {
constructor(source) {
this._source = source;
this._requestGroupID = 0;
this._oldDataframes = [];
this._MNS = null;
this._promiseMNS = null;
this._categoryStringToIDMap = {};
this._numCategories = 0;
const lruOptions = {
max: 1000
// TODO improve cache length heuristic
, length: function () { return 1; }
, dispose: (key, promise) => {
promise.then(dataframe => {
if (!dataframe.empty) {
dataframe.free();
this._removeDataframe(dataframe);
}
});
}
, maxAge: 1000 * 60 * 60
};
this.cache = __WEBPACK_IMPORTED_MODULE_3_lru_cache__(lruOptions);
this.inProgressInstantiations = {};
this._subdomainCounter = 0;
}
_bindLayer(addDataframe, removeDataframe, dataLoadedCallback) {
this._addDataframe = addDataframe;
this._removeDataframe = removeDataframe;
this._dataLoadedCallback = dataLoadedCallback;
}
_getInstantiationID(MNS, resolution, filtering) {
return JSON.stringify({
MNS,
resolution,
filtering: this.metadata && this.metadata.featureCount > MIN_FILTERING ? filtering : null
});
}
/**
* Should be called whenever the viewport or the style changes
* Returns falseable if the metadata didn't changed, or a promise to a Metadata if it did change
* @param {*} viewport
* @param {*} MNS
* @param {*} addDataframe
* @param {*} styleDataframe
*/
async getData(viewport, style) {
const MNS = style.getMinimumNeededSchema();
const resolution = style.getResolution();
const filtering = __WEBPACK_IMPORTED_MODULE_4__windshaft_filtering__["a" /* getFiltering */](style);
const tiles = __WEBPACK_IMPORTED_MODULE_1__rsys__["b" /* rTiles */](viewport);
if (this._needToInstantiate(MNS, resolution, filtering)) {
await this._instantiate(MNS, resolution, filtering);
}
this._getTiles(tiles);
return this.metadata;
}
_getTiles(tiles) {
this._requestGroupID++;
var completedTiles = [];
var needToComplete = tiles.length;
const requestGroupID = this._requestGroupID;
tiles.forEach(t => {
const { x, y, z } = t;
this.getDataframe(x, y, z).then(dataframe => {
if (dataframe.empty) {
needToComplete--;
} else {
completedTiles.push(dataframe);
}
if (completedTiles.length == needToComplete && requestGroupID == this._requestGroupID) {
this._oldDataframes.map(d => d.active = false);
completedTiles.map(d => d.active = true);
this._oldDataframes = completedTiles;
this._dataLoadedCallback();
}
});
});
}
/**
* Check if the map needs to be reinstantiated
* This happens:
* - When the minimun required schema changed.
* - When the resolution changed.
* - When the filter conditions changed and the dataset should be server-filtered.
*/
_needToInstantiate(MNS, resolution, filtering) {
return !__WEBPACK_IMPORTED_MODULE_0__core_renderer__["c" /* schema */].equals(this._MNS, MNS) || resolution != this.resolution || (JSON.stringify(filtering) != JSON.stringify(this.filtering) && this.metadata.featureCount > MIN_FILTERING);
}
_getCategoryIDFromString(category) {
if (this._categoryStringToIDMap[category] !== undefined) {
return this._categoryStringToIDMap[category];
}
this._categoryStringToIDMap[category] = this._numCategories;
this._numCategories++;
return this._categoryStringToIDMap[category];
}
async _instantiateUncached(MNS, resolution, filters){
const conf = this._getConfig();
const agg = await this._generateAggregation(MNS, resolution);
const select = this._buildSelectClause(MNS);
let aggSQL = this._buildQuery(select);
const query = `(${aggSQL}) AS tmp`;
const metadata = await this.getMetadata(query, MNS, conf);
// If the number of features is higher than the minimun, enable server filtering.
if (metadata.featureCount > MIN_FILTERING) {
aggSQL = `SELECT ${select.filter((item, pos) => select.indexOf(item) == pos).join()} FROM ${this._source._query ? `(${this._source._query}) as _cdb_query_wrapper` : this._source._tableName} ${__WEBPACK_IMPORTED_MODULE_4__windshaft_filtering__["b" /* getSQLWhere */](filters)}`;
}
const urlTemplate = await this._getUrlPromise(query, conf, agg, aggSQL);
this._oldDataframes = [];
this.cache.reset();
this.urlTemplate = urlTemplate;
this.metadata = metadata;
this._MNS = MNS;
this.filtering = filters;
this.resolution = resolution;
// Store instantiation
return metadata;
}
async _instantiate(MNS, resolution, filters) {
if (this.inProgressInstantiations[this._getInstantiationID(MNS, resolution, filters)]) {
return this.inProgressInstantiations[this._getInstantiationID(MNS, resolution, filters)];
}
console.log(this._getInstantiationID(MNS, resolution, filters));
const promise = this._instantiateUncached(MNS, resolution, filters);
this.inProgressInstantiations[this._getInstantiationID(MNS, resolution, filters)] = promise;
return promise;
}
_generateAggregation(MRS, resolution) {
let aggregation = {
columns: {},
dimensions: {},
placement: 'centroid',
resolution: resolution,
threshold: 1,
};
MRS.columns
.forEach(name => {
if (name.startsWith('_cdb_agg_')) {
aggregation.columns[name] = {
aggregate_function: getAggFN(name),
aggregated_column: getBase(name)
};
} else {
aggregation.dimensions[name] = name;
}
});
return aggregation;
}
_buildSelectClause(MRS) {
return MRS.columns.map(name => name.startsWith('_cdb_agg_') ? getBase(name) : name).concat(['the_geom', 'the_geom_webmercator']);
}
_buildQuery(select) {
return `SELECT ${select.filter((item, pos) => select.indexOf(item) == pos).join()} FROM ${this._source._query ? `(${this._source._query}) as _cdb_query_wrapper` : this._source._tableName}`;
}
_getConfig() {
return {
apiKey: this._source._apiKey,
username: this._source._username,
serverURL: this._source._serverURL
};
}
free() {
this.cache.reset();
}
_generateDataFrame(rs, geometry, properties, size, type) {
// TODO: Should the dataframe constructor have type and size parameters?
const dataframe = new __WEBPACK_IMPORTED_MODULE_0__core_renderer__["a" /* Dataframe */](
rs.center,
rs.scale,
geometry,
properties,
);
dataframe.type = type;
dataframe.size = size;
return dataframe;
}
async _getUrlPromise(query, conf, agg, aggSQL) {
const LAYER_INDEX = 0;
this.geomType = await this.getGeometryType(query, conf);
if (this.geomType != 'point') {
agg = false;
}
const mapConfigAgg = {
buffersize: {
'mvt': 0
},
layers: [
{
type: 'mapnik',
options: {
sql: aggSQL,
aggregation: agg
}
}
]
};
const response = await fetch(endpoint(conf), this._getRequestConfig(mapConfigAgg));
const layergroup = await response.json();
this._subdomains = layergroup.cdn_url.templates.https.subdomains;
return getLayerUrl(layergroup, LAYER_INDEX, conf);
}
_getRequestConfig(mapConfigAgg) {
return {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(mapConfigAgg),
};
}
getDataframe(x, y, z) {
const id = `${x},${y},${z}`;
const c = this.cache.get(id);
if (c) {
return c;
}
const promise = this.requestDataframe(x, y, z);
this.cache.set(id, promise);
return promise;
}
requestDataframe(x, y, z) {
const mvt_extent = 4096;
return fetch(this._getTileUrl(x, y, z))
.then(rawData => rawData.arrayBuffer())
.then(response => {
if (response.byteLength == 0 || response == 'null') {
return { empty: true };
}
var tile = new __WEBPACK_IMPORTED_MODULE_5__mapbox_vector_tile__["VectorTile"](new __WEBPACK_IMPORTED_MODULE_2_pbf__(response));
const mvtLayer = tile.layers[Object.keys(tile.layers)[0]];
var fieldMap = {};
const numFields = [];
const catFields = [];
const catFieldsReal = [];
const numFieldsReal = [];
this._MNS.columns.map(name => {
const basename = name.startsWith('_cdb_agg_') ? getBase(name) : name;
if (this.metadata.columns.find(c => c.name == basename).type == 'category') {
catFields.push(name);
catFieldsReal.push(name);
} else {
numFields.push(name);
numFieldsReal.push(name);
}
});
catFieldsReal.map((name, i) => fieldMap[name] = i);
numFieldsReal.map((name, i) => fieldMap[name] = i + catFields.length);
const { points, featureGeometries, properties } = this._decodeMVTLayer(mvtLayer, this.metadata, mvt_extent, catFields, catFieldsReal, numFields);
var rs = __WEBPACK_IMPORTED_MODULE_1__rsys__["a" /* getRsysFromTile */](x, y, z);
let dataframeProperties = {};
Object.keys(fieldMap).map((name, pid) => {
dataframeProperties[name] = properties[pid];
});
let dataFrameGeometry = this.geomType == 'point' ? points : featureGeometries;
const dataframe = this._generateDataFrame(rs, dataFrameGeometry, dataframeProperties, mvtLayer.length, this.geomType);
this._addDataframe(dataframe);
return dataframe;
});
}
_getTileUrl(x, y, z) {
const s = this._subdomains[this._subdomainCounter++ % this._subdomains.length];
return this.urlTemplate.replace('{x}', x).replace('{y}', y).replace('{z}', z).replace('{s}', s);
}
_decodePolygons(geom, featureGeometries, mvt_extent) {
let polygon = null;
let geometry = [];
/*
All this clockwise non-sense is needed because the MVT decoder dont decode the MVT fully.
It doesn't distinguish between internal polygon rings (which defines holes) or external ones, which defines more polygons (mulipolygons)
See:
https://github.com/mapbox/vector-tile-spec/tree/master/2.1
https://en.wikipedia.org/wiki/Shoelace_formula
*/
for (let j = 0; j < geom.length; j++) {
//if exterior
// push current polygon & set new empty
//else=> add index to holes
if (isClockWise(geom[j])) {
if (polygon) {
geometry.push(polygon);
}
polygon = {
flat: [],
holes: []
};
} else {
if (j == 0) {
throw new Error('Invalid MVT tile: first polygon ring MUST be external');
}
polygon.holes.push(polygon.flat.length / 2);
}
for (let k = 0; k < geom[j].length; k++) {
polygon.flat.push(2 * geom[j][k].x / mvt_extent - 1.);
polygon.flat.push(2 * (1. - geom[j][k].y / mvt_extent) - 1.);
}
}
//if current polygon is not empty=> push it
if (polygon && polygon.flat.length > 0) {
geometry.push(polygon);
}
featureGeometries.push(geometry);
}
_decodeLines(geom, featureGeometries, mvt_extent) {
let geometry = [];
geom.map(l => {
let line = [];
l.map(point => {
line.push(2 * point.x / mvt_extent - 1, 2 * (1 - point.y / mvt_extent) - 1);
});
geometry.push(line);
});
featureGeometries.push(geometry);
}
_decodeMVTLayer(mvtLayer, metadata, mvt_extent, catFields, catFieldsReal, numFields) {
var properties = [new Float32Array(mvtLayer.length + 1024), new Float32Array(mvtLayer.length + 1024), new Float32Array(mvtLayer.length + 1024), new Float32Array(mvtLayer.length + 1024)];
if (this.geomType == 'point') {
var points = new Float32Array(mvtLayer.length * 2);
}
let featureGeometries = [];
for (var i = 0; i < mvtLayer.length; i++) {
const f = mvtLayer.feature(i);
const geom = f.loadGeometry();
if (this.geomType == 'point') {
points[2 * i + 0] = 2 * (geom[0][0].x) / mvt_extent - 1.;
points[2 * i + 1] = 2 * (1. - (geom[0][0].y) / mvt_extent) - 1.;
} else if (this.geomType == 'polygon') {
this._decodePolygons(geom, featureGeometries, mvt_extent);
} else if (this.geomType == 'line') {
this._decodeLines(geom, featureGeometries, mvt_extent);
} else {
throw new Error(`Unimplemented geometry type: '${this.geomType}'`);
}
catFields.map((name, index) => {
properties[index][i] = this._getCategoryIDFromString(f.properties[name]);
});
numFields.map((name, index) => {
properties[index + catFields.length][i] = Number(f.properties[name]);
});
}
return { properties, points, featureGeometries };
}
async getMetadata(query, proto, conf) {
//Get column names and types with a limit 0
//Get min,max,sum and count of numerics
//for each category type
//Get category names and counts by grouping by
//Assign ids
const metadata = {
columns: [],
};
const fields = await this.getColumnTypes(query, conf);
let numerics = [];
let categories = [];
Object.keys(fields).map(name => {
const type = fields[name].type;
if (type == 'number') {
numerics.push(name);
} else if (type == 'string') {
categories.push(name);
}
});
metadata.featureCount = await this.getFeatureCount(query, conf);
const numericsTypes = await this.getNumericTypes(numerics, query, conf);
const categoriesTypes = await this.getCategoryTypes(categories, query, conf);
const sampling = Math.min(SAMPLE_ROWS / metadata.featureCount, 1);
const sample = await this.getSample(conf, sampling);
numerics.map((name, index) => {
const t = numericsTypes[index];
metadata.columns.push(t);
});
metadata.categoryIDs = {};
metadata.sample = sample;
categories.map((name, index) => {
const t = categoriesTypes[index];
t.categoryNames.map(name => metadata.categoryIDs[name] = this._getCategoryIDFromString(name));
metadata.columns.push(t);
});
return metadata;
}
async getSample(conf, sampling) {
let q;
if (this._source._tableName) {
q = `SELECT * FROM ${this._source._tableName} TABLESAMPLE BERNOULLI (${100 * sampling}) REPEATABLE (0);`;
} else {
// Fallback to random() since 'TABLESAMPLE BERNOULLI' is not supported on queries
q = `WITH _rndseed as (SELECT setseed(0.5))
SELECT * FROM (${this._source._query}) as _cdb_query_wrapper WHERE random() < ${sampling};`;
}
const response = await fetch(`${conf.serverURL}/api/v2/sql?q=` + encodeURIComponent(q));
const json = await response.json();
console.log(json);
return json.rows;
}
async getFeatureCount(query, conf) {
const q = `SELECT COUNT(*) FROM ${query};`;
const response = await fetch(`${conf.serverURL}/api/v2/sql?q=` + encodeURIComponent(q));
const json = await response.json();
return json.rows[0].count;
}
async getColumnTypes(query, conf) {
const columnListQuery = `select * from ${query} limit 0;`;
const response = await fetch(`${conf.serverURL}/api/v2/sql?q=` + encodeURIComponent(columnListQuery));
const json = await response.json();
return json.fields;
}
async getGeometryType(query, conf) {
const columnListQuery = `SELECT ST_GeometryType(the_geom) AS type FROM ${query} WHERE the_geom IS NOT NULL LIMIT 1;`;
const response = await fetch(`${conf.serverURL}/api/v2/sql?q=` + encodeURIComponent(columnListQuery));
const json = await response.json();
const type = json.rows[0].type;
switch (type) {
case 'ST_MultiPolygon':
return 'polygon';
case 'ST_Point':
return 'point';
case 'ST_MultiLineString':
return 'line';
default:
throw new Error(`Unimplemented geometry type ''${type}'`);
}
}
async getNumericTypes(names, query, conf) {
const aggFns = ['min', 'max', 'sum', 'avg'];
const numericsSelect = names.map(name =>
aggFns.map(fn => `${fn}(${name}) AS ${name}_${fn}`)
).concat(['COUNT(*)']).join();
const numericsQuery = `SELECT ${numericsSelect} FROM ${query};`;
const response = await fetch(`${conf.serverURL}/api/v2/sql?q=` + encodeURIComponent(numericsQuery));
const json = await response.json();
return names.map(name => {
return {
name,
type: 'float',
min: json.rows[0][`${name}_min`],
max: json.rows[0][`${name}_max`],
avg: json.rows[0][`${name}_avg`],
sum: json.rows[0][`${name}_sum`],
};
}
);
}
async getCategoryTypes(names, query, conf) {
return Promise.all(names.map(async name => {
const catQuery = `SELECT COUNT(*), ${name} AS name FROM ${query} GROUP BY ${name} ORDER BY COUNT(*) DESC;`;
const response = await fetch(`${conf.serverURL}/api/v2/sql?q=` + encodeURIComponent(catQuery));
const json = await response.json();
let counts = [];
let names = [];
json.rows.map(row => {
counts.push(row.count);
names.push(row.name);
});
return {
name,
type: 'category',
categoryNames: names,
categoryCounts: counts
};
}));
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Windshaft;
function isClockWise(vertices) {
let a = 0;
for (let i = 0; i < vertices.length; i++) {
let j = (i + 1) % vertices.length;
a += vertices[i].x * vertices[j].y;
a -= vertices[j].x * vertices[i].y;
}
return a > 0;
}
function getBase(name) {
return name.replace(/_cdb_agg_[a-zA-Z0-9]+_/g, '');
}
function getAggFN(name) {
let s = name.substr('_cdb_agg_'.length);
return s.substr(0, s.indexOf('_'));
}
const endpoint = (conf) => {
return `${conf.serverURL}/api/v1/map?api_key=${conf.apiKey}`;
};
function getLayerUrl(layergroup, layerIndex, conf) {
if (layergroup.cdn_url && layergroup.cdn_url.templates) {
const urlTemplates = layergroup.cdn_url.templates.https;
return `${urlTemplates.url}/${conf.username}/api/v1/map/${layergroup.layergroupid}/${layerIndex}/{z}/{x}/{y}.mvt?api_key=${conf.apiKey}`;
}
return `${endpoint(conf)}/${layergroup.layergroupid}/${layerIndex}/{z}/{x}/{y}.mvt`;
}
/**
* Responsabilities: get tiles, decode tiles, return dataframe promises, optionally: cache, coalesce all layer with a source engine, return bound dataframes
*/
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = Pbf;
var ieee754 = __webpack_require__(64);
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;
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 & 0x7;
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 & 0x7f; if (b < 0x80) return val;
b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
b = buf[this.pos]; val |= (b & 0x0f) << 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,
str = readUtf8(this.buf, this.pos, end);
this.pos = end;
return str;
},
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) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readVarint(isSigned));
return arr;
},
readPackedSVarint: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readSVarint());
return arr;
},
readPackedBoolean: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readBoolean());
return arr;
},
readPackedFloat: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readFloat());
return arr;
},
readPackedDouble: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readDouble());
return arr;
},
readPackedFixed32: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readFixed32());
return arr;
},
readPackedSFixed32: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readSFixed32());
return arr;
},
readPackedFixed64: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readFixed64());
return arr;
},
readPackedSFixed64: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readSFixed64());
return arr;
},
skip: function(val) {
var type = val & 0x7;
if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
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 > 0xfffffff || val < 0) {
writeBigVarint(val, this);
return;
}
this.realloc(4);
this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
this.buf[this.pos++] = (val >>> 7) & 0x7f;
},
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 >= 0x80) 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 >= 0x80) 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) { this.writeMessage(tag, writePackedVarint, arr); },
writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
writePackedSFixed64: function(tag, arr) { 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 & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) 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 * 0x100000000 + (low >>> 0);
}
return ((high >>> 0) * 0x100000000) + (low >>> 0);
}
function writeBigVarint(val, pbf) {
var low, high;
if (val >= 0) {
low = (val % 0x100000000) | 0;
high = (val / 0x100000000) | 0;
} else {
low = ~(-val % 0x100000000);
high = ~(-val / 0x100000000);
if (low ^ 0xffffffff) {
low = (low + 1) | 0;
} else {
low = 0;
high = (high + 1) | 0;
}
}
if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
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 & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos] = low & 0x7f;
}
function writeBigVarintHigh(high, pbf) {
var lsb = (high & 0x07) << 4;
pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f;
}
function makeRoomForExtraLength(startPos, len, pbf) {
var extraLen =
len <= 0x3fff ? 1 :
len <= 0x1fffff ? 2 :
len <= 0xfffffff ? 3 : Math.ceil(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] * 0x1000000);
}
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 > 0xEF ? 4 :
b0 > 0xDF ? 3 :
b0 > 0xBF ? 2 : 1;
if (i + bytesPerSequence > end) break;
var b1, b2, b3;
if (bytesPerSequence === 1) {
if (b0 < 0x80) {
c = b0;
}
} else if (bytesPerSequence === 2) {
b1 = buf[i + 1];
if ((b1 & 0xC0) === 0x80) {
c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
if (c <= 0x7F) {
c = null;
}
}
} else if (bytesPerSequence === 3) {
b1 = buf[i + 1];
b2 = buf[i + 2];
if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
c = null;
}
}
} else if (bytesPerSequence === 4) {
b1 = buf[i + 1];
b2 = buf[i + 2];
b3 = buf[i + 3];
if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
if (c <= 0xFFFF || c >= 0x110000) {
c = null;
}
}
}
if (c === null) {
c = 0xFFFD;
bytesPerSequence = 1;
} else if (c > 0xFFFF) {
c -= 0x10000;
str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
c = 0xDC00 | c & 0x3FF;
}
str += String.fromCharCode(c);
i += bytesPerSequence;
}
return str;
}
function writeUtf8(buf, str, pos) {
for (var i = 0, c, lead; i < str.length; i++) {
c = str.charCodeAt(i); // code point
if (c > 0xD7FF && c < 0xE000) {
if (lead) {
if (c < 0xDC00) {
buf[pos++] = 0xEF;
buf[pos++] = 0xBF;
buf[pos++] = 0xBD;
lead = c;
continue;
} else {
c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
lead = null;
}
} else {
if (c > 0xDBFF || (i + 1 === str.length)) {
buf[pos++] = 0xEF;
buf[pos++] = 0xBF;
buf[pos++] = 0xBD;
} else {
lead = c;
}
continue;
}
} else if (lead) {
buf[pos++] = 0xEF;
buf[pos++] = 0xBF;
buf[pos++] = 0xBD;
lead = null;
}
if (c < 0x80) {
buf[pos++] = c;
} else {
if (c < 0x800) {
buf[pos++] = c >> 0x6 | 0xC0;
} else {
if (c < 0x10000) {
buf[pos++] = c >> 0xC | 0xE0;
} else {
buf[pos++] = c >> 0x12 | 0xF0;
buf[pos++] = c >> 0xC & 0x3F | 0x80;
}
buf[pos++] = c >> 0x6 & 0x3F | 0x80;
}
buf[pos++] = c & 0x3F | 0x80;
}
}
return pos;
}
/***/ }),
/* 64 */
/***/ (function(module, exports) {
exports.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)
}
exports.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 & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = LRUCache
// This will be a proper iterable 'Map' in engines that support it,
// or a fakey-fake PseudoMap in older versions.
var Map = __webpack_require__(66)
var util = __webpack_require__(68)
// A linked list to keep track of recently-used-ness
var Yallist = __webpack_require__(72)
// use symbols if possible, otherwise just _props
var hasSymbol = typeof Symbol === 'function'
var makeSymbol
if (hasSymbol) {
makeSymbol = function (key) {
return Symbol.for(key)
}
} else {
makeSymbol = function (key) {
return '_' + key
}
}
var MAX = makeSymbol('max')
var LENGTH = makeSymbol('length')
var LENGTH_CALCULATOR = makeSymbol('lengthCalculator')
var ALLOW_STALE = makeSymbol('allowStale')
var MAX_AGE = makeSymbol('maxAge')
var DISPOSE = makeSymbol('dispose')
var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet')
var LRU_LIST = makeSymbol('lruList')
var CACHE = makeSymbol('cache')
function naiveLength () { return 1 }
// lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
function LRUCache (options) {
if (!(this instanceof LRUCache)) {
return new LRUCache(options)
}
if (typeof options === 'number') {
options = { max: options }
}
if (!options) {
options = {}
}
var max = this[MAX] = options.max
// Kind of weird to have a default max of Infinity, but oh well.
if (!max ||
!(typeof max === 'number') ||
max <= 0) {
this[MAX] = Infinity
}
var lc = options.length || naiveLength
if (typeof lc !== 'function') {
lc = naiveLength
}
this[LENGTH_CALCULATOR] = lc
this[ALLOW_STALE] = options.stale || false
this[MAX_AGE] = options.maxAge || 0
this[DISPOSE] = options.dispose
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
this.reset()
}
// resize the cache when the max changes.
Object.defineProperty(LRUCache.prototype, 'max', {
set: function (mL) {
if (!mL || !(typeof mL === 'number') || mL <= 0) {
mL = Infinity
}
this[MAX] = mL
trim(this)
},
get: function () {
return this[MAX]
},
enumerable: true
})
Object.defineProperty(LRUCache.prototype, 'allowStale', {
set: function (allowStale) {
this[ALLOW_STALE] = !!allowStale
},
get: function () {
return this[ALLOW_STALE]
},
enumerable: true
})
Object.defineProperty(LRUCache.prototype, 'maxAge', {
set: function (mA) {
if (!mA || !(typeof mA === 'number') || mA < 0) {
mA = 0
}
this[MAX_AGE] = mA
trim(this)
},
get: function () {
return this[MAX_AGE]
},
enumerable: true
})
// resize the cache when the lengthCalculator changes.
Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
set: function (lC) {
if (typeof lC !== 'function') {
lC = naiveLength
}
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC
this[LENGTH] = 0
this[LRU_LIST].forEach(function (hit) {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
this[LENGTH] += hit.length
}, this)
}
trim(this)
},
get: function () { return this[LENGTH_CALCULATOR] },
enumerable: true
})
Object.defineProperty(LRUCache.prototype, 'length', {
get: function () { return this[LENGTH] },
enumerable: true
})
Object.defineProperty(LRUCache.prototype, 'itemCount', {
get: function () { return this[LRU_LIST].length },
enumerable: true
})
LRUCache.prototype.rforEach = function (fn, thisp) {
thisp = thisp || this
for (var walker = this[LRU_LIST].tail; walker !== null;) {
var prev = walker.prev
forEachStep(this, fn, walker, thisp)
walker = prev
}
}
function forEachStep (self, fn, node, thisp) {
var hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE]) {
hit = undefined
}
}
if (hit) {
fn.call(thisp, hit.value, hit.key, self)
}
}
LRUCache.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
for (var walker = this[LRU_LIST].head; walker !== null;) {
var next = walker.next
forEachStep(this, fn, walker, thisp)
walker = next
}
}
LRUCache.prototype.keys = function () {
return this[LRU_LIST].toArray().map(function (k) {
return k.key
}, this)
}
LRUCache.prototype.values = function () {
return this[LRU_LIST].toArray().map(function (k) {
return k.value
}, this)
}
LRUCache.prototype.reset = function () {
if (this[DISPOSE] &&
this[LRU_LIST] &&
this[LRU_LIST].length) {
this[LRU_LIST].forEach(function (hit) {
this[DISPOSE](hit.key, hit.value)
}, this)
}
this[CACHE] = new Map() // hash of items by key
this[LRU_LIST] = new Yallist() // list of items in order of use recency
this[LENGTH] = 0 // length of items in the list
}
LRUCache.prototype.dump = function () {
return this[LRU_LIST].map(function (hit) {
if (!isStale(this, hit)) {
return {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}
}
}, this).toArray().filter(function (h) {
return h
})
}
LRUCache.prototype.dumpLru = function () {
return this[LRU_LIST]
}
LRUCache.prototype.inspect = function (n, opts) {
var str = 'LRUCache {'
var extras = false
var as = this[ALLOW_STALE]
if (as) {
str += '\n allowStale: true'
extras = true
}
var max = this[MAX]
if (max && max !== Infinity) {
if (extras) {
str += ','
}
str += '\n max: ' + util.inspect(max, opts)
extras = true
}
var maxAge = this[MAX_AGE]
if (maxAge) {
if (extras) {
str += ','
}
str += '\n maxAge: ' + util.inspect(maxAge, opts)
extras = true
}
var lc = this[LENGTH_CALCULATOR]
if (lc && lc !== naiveLength) {
if (extras) {
str += ','
}
str += '\n length: ' + util.inspect(this[LENGTH], opts)
extras = true
}
var didFirst = false
this[LRU_LIST].forEach(function (item) {
if (didFirst) {
str += ',\n '
} else {
if (extras) {
str += ',\n'
}
didFirst = true
str += '\n '
}
var key = util.inspect(item.key).split('\n').join('\n ')
var val = { value: item.value }
if (item.maxAge !== maxAge) {
val.maxAge = item.maxAge
}
if (lc !== naiveLength) {
val.length = item.length
}
if (isStale(this, item)) {
val.stale = true
}
val = util.inspect(val, opts).split('\n').join('\n ')
str += key + ' => ' + val
})
if (didFirst || extras) {
str += '\n'
}
str += '}'
return str
}
LRUCache.prototype.set = function (key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE]
var now = maxAge ? Date.now() : 0
var len = this[LENGTH_CALCULATOR](value, key)
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key))
return false
}
var node = this[CACHE].get(key)
var item = node.value
// dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET]) {
this[DISPOSE](key, item.value)
}
}
item.now = now
item.maxAge = maxAge
item.value = value
this[LENGTH] += len - item.length
item.length = len
this.get(key)
trim(this)
return true
}
var hit = new Entry(key, value, len, now, maxAge)
// oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE]) {
this[DISPOSE](key, value)
}
return false
}
this[LENGTH] += hit.length
this[LRU_LIST].unshift(hit)
this[CACHE].set(key, this[LRU_LIST].head)
trim(this)
return true
}
LRUCache.prototype.has = function (key) {
if (!this[CACHE].has(key)) return false
var hit = this[CACHE].get(key).value
if (isStale(this, hit)) {
return false
}
return true
}
LRUCache.prototype.get = function (key) {
return get(this, key, true)
}
LRUCache.prototype.peek = function (key) {
return get(this, key, false)
}
LRUCache.prototype.pop = function () {
var node = this[LRU_LIST].tail
if (!node) return null
del(this, node)
return node.value
}
LRUCache.prototype.del = function (key) {
del(this, this[CACHE].get(key))
}
LRUCache.prototype.load = function (arr) {
// reset the cache
this.reset()
var now = Date.now()
// A previous serialized cache has the most recent items first
for (var l = arr.length - 1; l >= 0; l--) {
var hit = arr[l]
var expiresAt = hit.e || 0
if (expiresAt === 0) {
// the item was created without expiration in a non aged cache
this.set(hit.k, hit.v)
} else {
var maxAge = expiresAt - now
// dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge)
}
}
}
}
LRUCache.prototype.prune = function () {
var self = this
this[CACHE].forEach(function (value, key) {
get(self, key, false)
})
}
function get (self, key, doUse) {
var node = self[CACHE].get(key)
if (node) {
var hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE]) hit = undefined
} else {
if (doUse) {
self[LRU_LIST].unshiftNode(node)
}
}
if (hit) hit = hit.value
}
return hit
}
function isStale (self, hit) {
if (!hit || (!hit.maxAge && !self[MAX_AGE])) {
return false
}
var stale = false
var diff = Date.now() - hit.now
if (hit.maxAge) {
stale = diff > hit.maxAge
} else {
stale = self[MAX_AGE] && (diff > self[MAX_AGE])
}
return stale
}
function trim (self) {
if (self[LENGTH] > self[MAX]) {
for (var walker = self[LRU_LIST].tail;
self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
var prev = walker.prev
del(self, walker)
walker = prev
}
}
}
function del (self, node) {
if (node) {
var hit = node.value
if (self[DISPOSE]) {
self[DISPOSE](hit.key, hit.value)
}
self[LENGTH] -= hit.length
self[CACHE].delete(hit.key)
self[LRU_LIST].removeNode(node)
}
}
// classy, since V8 prefers predictable objects.
function Entry (key, value, length, now, maxAge) {
this.key = key
this.value = value
this.length = length
this.now = now
this.maxAge = maxAge || 0
}
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {if (process.env.npm_package_name === 'pseudomap' &&
process.env.npm_lifecycle_script === 'test')
process.env.TEST_PSEUDOMAP = 'true'
if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
module.exports = Map
} else {
module.exports = __webpack_require__(67)
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(23)))
/***/ }),
/* 67 */
/***/ (function(module, exports) {
var hasOwnProperty = Object.prototype.hasOwnProperty
module.exports = PseudoMap
function PseudoMap (set) {
if (!(this instanceof PseudoMap)) // whyyyyyyy
throw new TypeError("Constructor PseudoMap requires 'new'")
this.clear()
if (set) {
if ((set instanceof PseudoMap) ||
(typeof Map === 'function' && set instanceof Map))
set.forEach(function (value, key) {
this.set(key, value)
}, this)
else if (Array.isArray(set))
set.forEach(function (kv) {
this.set(kv[0], kv[1])
}, this)
else
throw new TypeError('invalid argument')
}
}
PseudoMap.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
Object.keys(this._data).forEach(function (k) {
if (k !== 'size')
fn.call(thisp, this._data[k].value, this._data[k].key)
}, this)
}
PseudoMap.prototype.has = function (k) {
return !!find(this._data, k)
}
PseudoMap.prototype.get = function (k) {
var res = find(this._data, k)
return res && res.value
}
PseudoMap.prototype.set = function (k, v) {
set(this._data, k, v)
}
PseudoMap.prototype.delete = function (k) {
var res = find(this._data, k)
if (res) {
delete this._data[res._index]
this._data.size--
}
}
PseudoMap.prototype.clear = function () {
var data = Object.create(null)
data.size = 0
Object.defineProperty(this, '_data', {
value: data,
enumerable: false,
configurable: true,
writable: false
})
}
Object.defineProperty(PseudoMap.prototype, 'size', {
get: function () {
return this._data.size
},
set: function (n) {},
enumerable: true,
configurable: true
})
PseudoMap.prototype.values =
PseudoMap.prototype.keys =
PseudoMap.prototype.entries = function () {
throw new Error('iterators are not implemented in this version')
}
// Either identical, or both NaN
function same (a, b) {
return a === b || a !== a && b !== b
}
function Entry (k, v, i) {
this.key = k
this.value = v
this._index = i
}
function find (data, k) {
for (var i = 0, s = '_' + k, key = s;
hasOwnProperty.call(data, key);
key = s + i++) {
if (same(data[key].key, k))
return data[key]
}
}
function set (data, k, v) {
for (var i = 0, s = '_' + k, key = s;
hasOwnProperty.call(data, key);
key = s + i++) {
if (same(data[key].key, k)) {
data[key].value = v
return
}
}
data.size++
data[key] = new Entry(k, v, key)
}
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(70);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(71);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(69), __webpack_require__(23)))
/***/ }),
/* 69 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 70 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 71 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 72 */
/***/ (function(module, exports) {
module.exports = Yallist
Yallist.Node = Node
Yallist.create = Yallist
function Yallist (list) {
var self = this
if (!(self instanceof Yallist)) {
self = new Yallist()
}
self.tail = null
self.head = null
self.length = 0
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item)
})
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i])
}
}
return self
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list')
}
var next = node.next
var prev = node.prev
if (next) {
next.prev = prev
}
if (prev) {
prev.next = next
}
if (node === this.head) {
this.head = next
}
if (node === this.tail) {
this.tail = prev
}
node.list.length--
node.next = null
node.prev = null
node.list = null
}
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var head = this.head
node.list = this
node.next = head
if (head) {
head.prev = node
}
this.head = node
if (!this.tail) {
this.tail = node
}
this.length++
}
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var tail = this.tail
node.list = this
node.prev = tail
if (tail) {
tail.next = node
}
this.tail = node
if (!this.head) {
this.head = node
}
this.length++
}
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i])
}
return this.length
}
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i])
}
return this.length
}
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined
}
var res = this.tail.value
this.tail = this.tail.prev
if (this.tail) {
this.tail.next = null
} else {
this.head = null
}
this.length--
return res
}
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined
}
var res = this.head.value
this.head = this.head.next
if (this.head) {
this.head.prev = null
} else {
this.tail = null
}
this.length--
return res
}
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this)
walker = walker.next
}
}
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this)
walker = walker.prev
}
}
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.next
}
return res
}
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.prev
}
return res
}
Yallist.prototype.reduce = function (fn, initial) {
var acc
var walker = this.head
if (arguments.length > 1) {
acc = initial
} else if (this.head) {
walker = this.head.next
acc = this.head.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i)
walker = walker.next
}
return acc
}
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc
var walker = this.tail
if (arguments.length > 1) {
acc = initial
} else if (this.tail) {
walker = this.tail.prev
acc = this.tail.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i)
walker = walker.prev
}
return acc
}
Yallist.prototype.toArray = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value
walker = walker.next
}
return arr
}
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value
walker = walker.prev
}
return arr
}
Yallist.prototype.slice = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.reverse = function () {
var head = this.head
var tail = this.tail
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev
walker.prev = walker.next
walker.next = p
}
this.head = tail
this.tail = head
return this
}
function push (self, item) {
self.tail = new Node(item, self.tail, null, self)
if (!self.head) {
self.head = self.tail
}
self.length++
}
function unshift (self, item) {
self.head = new Node(item, null, self.head, self)
if (!self.tail) {
self.tail = self.head
}
self.length++
}
function Node (value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list)
}
this.list = list
this.value = value
if (prev) {
prev.next = this
this.prev = prev
} else {
this.prev = null
}
if (next) {
next.prev = this
this.next = next
} else {
this.next = null
}
}
/***/ }),
/* 73 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getFiltering;
/* harmony export (immutable) */ __webpack_exports__["b"] = getSQLWhere;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_style_expressions_binary__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__core_style_expressions_belongs__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__core_style_expressions_between__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__core_style_expressions_category__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__core_style_expressions_float__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__core_style_expressions_property__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_blend__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__core_style_expressions_animate__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__core_style_expressions_floatConstant__ = __webpack_require__(14);
/**
* Returns supported windshaft filters for the style
* @param {*} style
* @returns {Filtering}
*/
function getFiltering(style) {
return getFilter(style.filter);
}
/**
*
* @param {Filtering} filtering
*/
function getSQLWhere(filtering) {
if (!filtering) {
return '';
}
return 'WHERE ' + filtering.map(filter => getSQL(filter)).join(' AND ');
}
function getSQL(f) {
return getBetweenSQL(f) || getInSQL(f) || getNinSQL(f) || '';
}
function getBetweenSQL(f) {
if (f.type == 'between') {
return `(${f.property} BETWEEN ${f.lowerLimit} AND ${f.upperLimit})`;
}
}
function getInSQL(f) {
if (f.type == 'in') {
return `(${f.property} IN (${f.whitelist.map(cat => `'${cat}'`).join()}))`;
}
}
function getNinSQL(f) {
if (f.type == 'nin') {
return `(${f.property} NOT IN (${f.blacklist.map(cat => `'${cat}'`).join()}))`;
}
}
function getFilter(f) {
return getAndFilter(f) || getInFilter(f) || getNinFilter(f) || getBetweenFilter(f) || getBlendFilter(f) || null;
}
function getAndFilter(f) {
if (f instanceof __WEBPACK_IMPORTED_MODULE_0__core_style_expressions_binary__["a" /* And */]) {
return [getFilter(f.a), getFilter(f.b)].filter(Boolean).reduce((x, y) => x.concat(y));
}
}
function getBlendFilter(f) {
if (f instanceof __WEBPACK_IMPORTED_MODULE_6__core_style_expressions_blend__["a" /* default */] && f.originalMix instanceof __WEBPACK_IMPORTED_MODULE_7__core_style_expressions_animate__["a" /* default */]) {
return getFilter(f.b);
}
}
function getInFilter(f) {
if (f instanceof __WEBPACK_IMPORTED_MODULE_1__core_style_expressions_belongs__["a" /* In */] && f.property instanceof __WEBPACK_IMPORTED_MODULE_5__core_style_expressions_property__["a" /* default */] && f.categories.every(cat => cat instanceof __WEBPACK_IMPORTED_MODULE_3__core_style_expressions_category__["a" /* default */])) {
return [{
type: 'in',
property: f.property.name,
whitelist: f.categories.map(cat => cat.expr)
}];
}
}
function getNinFilter(f) {
if (f instanceof __WEBPACK_IMPORTED_MODULE_1__core_style_expressions_belongs__["b" /* Nin */] && f.property instanceof __WEBPACK_IMPORTED_MODULE_5__core_style_expressions_property__["a" /* default */] && f.categories.every(cat => cat instanceof __WEBPACK_IMPORTED_MODULE_3__core_style_expressions_category__["a" /* default */])) {
return [{
type: 'nin',
property: f.property.name,
blacklist: f.categories.map(cat => cat.expr)
}];
}
}
function getBetweenFilter(f) {
if (isBetweenFilter(f)) {
return [{
type: 'between',
property: f.value.name,
lowerLimit: f.lowerLimit.expr,
upperLimit: f.upperLimit.expr,
}];
}
}
function isBetweenFilter(f) {
return f instanceof __WEBPACK_IMPORTED_MODULE_2__core_style_expressions_between__["a" /* default */]
&& f.value instanceof __WEBPACK_IMPORTED_MODULE_5__core_style_expressions_property__["a" /* default */]
&& (f.lowerLimit instanceof __WEBPACK_IMPORTED_MODULE_4__core_style_expressions_float__["a" /* default */] || f.lowerLimit instanceof __WEBPACK_IMPORTED_MODULE_8__core_style_expressions_floatConstant__["a" /* default */])
&& (f.upperLimit instanceof __WEBPACK_IMPORTED_MODULE_4__core_style_expressions_float__["a" /* default */] || f.upperLimit instanceof __WEBPACK_IMPORTED_MODULE_8__core_style_expressions_floatConstant__["a" /* default */]);
}
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
module.exports.VectorTile = __webpack_require__(75);
module.exports.VectorTileFeature = __webpack_require__(25);
module.exports.VectorTileLayer = __webpack_require__(24);
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var VectorTileLayer = __webpack_require__(24);
module.exports = 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;
}
}
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = 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;
};
/***/ }),
/* 77 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CartoError; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__error_list__ = __webpack_require__(78);
const UNEXPECTED_ERROR = 'unexpected error';
const GENERIC_ORIGIN = 'generic';
/**
* Represents an error in the carto library.
*
* @typedef {object} CartoError
* @property {string} message - A short error description
* @property {string} name - The name of the error "CartoError"
* @property {string} origin - Where the error was originated: 'validation'
* @property {object} originalError - An object containing the internal/original error
* @property {object} stack - Error stack trace
* @property {string} type - Error type
* @api
*/
class CartoError extends Error {
/**
* Build a cartoError from a generic error.
* @constructor
*
* @return {CartoError} A well formed object representing the error.
*/
constructor(error) {
super((error && error.message) || UNEXPECTED_ERROR);
this.name = 'CartoError';
this.originalError = error;
// this.stack = (new Error()).stack;
this.type = (error && error.type) || '';
this.origin = (error && error.origin) || GENERIC_ORIGIN;
// Add extra fields
var extraFields = this._getExtraFields();
this.message = extraFields.friendlyMessage;
}
_getExtraFields() {
const errorList = this._getErrorList();
for (let key in errorList) {
const error = errorList[key];
if (!(error.messageRegex instanceof RegExp)) {
throw new Error(`MessageRegex on ${key} is not a RegExp.`);
}
if (error.messageRegex.test(this.message)) {
return {
friendlyMessage: this._replaceRegex(error)
};
}
}
// When cartoError not found return generic values
return {
friendlyMessage: this.message || ''
};
}
_getErrorList() {
return __WEBPACK_IMPORTED_MODULE_0__error_list__[this.origin] && __WEBPACK_IMPORTED_MODULE_0__error_list__[this.origin][this.type];
}
/**
* Replace $0 with the proper paramter in the listedError regex to build a friendly message.
*/
_replaceRegex (error) {
if (!error.friendlyMessage) {
return this.message;
}
var match = this.message && this.message.match(error.messageRegex);
if (match && match.length > 1) {
return error.friendlyMessage.replace('$0', match[1]);
}
return error.friendlyMessage;
}
}
/***/ }),
/* 78 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validation", function() { return validation; });
const validation = {
layer: {
'id-required': {
messageRegex: /idRequired/,
friendlyMessage: '`id` property required.'
},
'id-string-required': {
messageRegex: /idStringRequired/,
friendlyMessage: '`id` property must be a string.'
},
'non-valid-id': {
messageRegex: /nonValidId/,
friendlyMessage: '`id` property must be not empty.'
},
'source-required': {
messageRegex: /sourceRequired/,
friendlyMessage: '`source` property required.'
},
'non-valid-source': {
messageRegex: /nonValidSource/,
friendlyMessage: 'The given object is not a valid source. See "carto.source.Base".'
},
'style-required': {
messageRegex: /styleRequired/,
friendlyMessage: '`style` property required.'
},
'non-valid-style': {
messageRegex: /nonValidStyle/,
friendlyMessage: 'The given object is not a valid style. See "carto.Style".'
}
},
setup: {
'auth-required': {
messageRegex: /authRequired/,
friendlyMessage: '`auth` property is required.'
},
'auth-object-required': {
messageRegex: /authObjectRequired/,
friendlyMessage: '`auth` property must be an object.'
},
'api-key-required': {
messageRegex: /apiKeyRequired/,
friendlyMessage: '`apiKey` property is required.'
},
'api-key-string-required': {
messageRegex: /apiKeyStringRequired/,
friendlyMessage: '`apiKey` property must be a string.'
},
'non-valid-api-key': {
messageRegex: /nonValidApiKey/,
friendlyMessage: '`apiKey` property must be not empty.'
},
'username-required': {
messageRegex: /usernameRequired/,
friendlyMessage: '`username` property is required.'
},
'username-string-required': {
messageRegex: /usernameStringRequired/,
friendlyMessage: '`username` property must be a string.'
},
'non-valid-username': {
messageRegex: /nonValidUsername/,
friendlyMessage: '`username` property must be not empty.'
},
'config-object-required': {
messageRegex: /configObjectRequired/,
friendlyMessage: '`config` property must be an object.'
},
'server-url-string-required': {
messageRegex: /serverURLStringRequired/,
friendlyMessage: '`serverURL` property must be a string.'
}
},
source: {
'non-valid-server-url': {
messageRegex: /nonValidServerURL/,
friendlyMessage: '`serverURL` property is not a valid URL.'
},
'table-name-required': {
messageRegex: /tableNameRequired/,
friendlyMessage: '`tableName` property is required.'
},
'table-name-string-required': {
messageRegex: /tableNameStringRequired$/,
friendlyMessage: '`tableName` property must be a string.'
},
'non-valid-table-name': {
messageRegex: /nonValidTableName$/,
friendlyMessage: '`tableName` property must be not empty.'
},
'query-required': {
messageRegex: /queryRequired/,
friendlyMessage: '`query` property is required.'
},
'query-string-required': {
messageRegex: /queryStringRequired$/,
friendlyMessage: '`query` property must be a string.'
},
'non-valid-query': {
messageRegex: /nonValidQuery$/,
friendlyMessage: '`query` property must be not empty.'
},
'non-valid-sql-query': {
messageRegex: /nonValidSQLQuery$/,
friendlyMessage: '`query` property must be a SQL query.'
}
},
style: {
'non-valid-definition': {
messageRegex: /nonValidDefinition$/,
friendlyMessage: 'style definition should be a styleSpec object or a valid style string.'
},
'non-valid-expression': {
messageRegex: /nonValidExpression\[(.+)\]$/,
friendlyMessage: '`$0` parameter is not a valid style Expresion.'
},
'resolution-number-required': {
messageRegex: /resolutionNumberRequired$/,
friendlyMessage: '`resolution` must be a number.'
}
}
};
/***/ }),
/* 79 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__base_windshaft__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__ = __webpack_require__(6);
class SQL extends __WEBPACK_IMPORTED_MODULE_1__base_windshaft__["a" /* default */] {
/**
* Create a carto.source.Dataset.
*
* @param {string} query - A SQL query containing a SELECT statement
* @param {object} auth
* @param {string} auth.apiKey - API key used to authenticate against CARTO
* @param {string} auth.user - Name of the user
* @param {object} config
* @param {string} [config.serverURL='https://{user}.carto.com'] - URL of the CARTO Maps API server
*
* @example
* new carto.source.SQL('SELECT * FROM european_cities', {
* apiKey: 'YOUR_API_KEY_HERE',
* user: 'YOUR_USERNAME_HERE'
* });
*
* @fires CartoError
*
* @constructor SQL
* @extends carto.source.Base
* @memberof carto.source
* @api
*/
constructor(query, auth, config) {
super();
this._checkQuery(query);
this._query = query;
this.initialize(auth, config);
}
_checkQuery(query) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](query)) {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'queryRequired');
}
if (!__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](query)) {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'queryStringRequired');
}
if (query === '') {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'nonValidQuery');
}
var sqlRegex = /(SELECT|select)\s+.*\s+(FROM|from)\s+.*/;
if (!query.match(sqlRegex)) {
throw new __WEBPACK_IMPORTED_MODULE_2__error_handling_carto_validation_error__["a" /* default */]('source', 'nonValidSQLQuery');
}
}
}
/* harmony export (immutable) */ __webpack_exports__["a"] = SQL;
/***/ }),
/* 80 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__source_base__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__style__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__map__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__integrator_carto__ = __webpack_require__(84);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__integrator_mapbox_gl__ = __webpack_require__(85);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__core_style_functions__ = __webpack_require__(1);
/**
* Responsabilities: rely style changes into MNS source notifications, notify renderer about style changes, notify source about viewport changes,
* rely dataframes to renderer, configure visibility for all source dataframes, set up MGL integration (opionally)
*/
class Layer {
/**
* Create a carto.Layer.
*
*
* @param {string} id
* @param {carto.source.Base} source
* @param {carto.Style} style
*
* @example
* new carto.Layer('layer0', source, style);
*
* @fires CartoError
*
* @constructor Layer
* @memberof carto
* @api
*/
constructor(id, source, style) {
this._checkId(id);
this._checkSource(source);
this._checkStyle(style);
this._lastViewport = null;
this._lastMNS = null;
this._integrator = null;
this._dataframes = [];
this._id = id;
this.metadata = null;
this.setSource(source);
this.setStyle(style);
this._listeners = {};
this.state = 'init';
console.log('L', this);
this.paintCallback = () => {
this._dataframes.map(
dataframe => {
dataframe.setStyle(this._style);
dataframe.visible = dataframe.active;
});
this._integrator.renderer.refresh(Number.NaN);
this._dataframes.map(
dataframe => {
dataframe.visible = false;
});
if (this.state == 'dataLoaded') {
this.state = 'dataPainted';
this._fire('loaded');
}
};
}
_fire(eventType, eventData) {
if (!this._listeners[eventType]) {
return;
}
this._listeners[eventType].map(listener => listener(eventData));
}
on(eventType, callback) {
if (!this._listeners[eventType]) {
this._listeners[eventType] = [callback];
} else {
this._listeners[eventType].push(callback);
}
}
off(eventType, callback) {
const index = this._listeners[eventType].indexOf(callback);
this._listeners[eventType].splice(index, 1);
}
/**
* Set a new source for this layer.
*
* @param {carto.source.Base} source - New source
*
* @memberof carto.Layer
* @api
*/
setSource(source) {
this._checkSource(source);
source.bindLayer(this._onDataframeAdded.bind(this), this._onDataFrameRemoved.bind(this), this._onDataLoaded.bind(this));
if (this._source && this._source !== source) {
this._source.free();
}
this._source = source;
}
/**
* Callback executed when the client adds a new dataframe
* @param {Dataframe} dataframe
*/
_onDataframeAdded(dataframe) {
this._dataframes.push(dataframe);
this._integrator.renderer.addDataframe(dataframe);
this._integrator.invalidateWebGLState();
}
/**
* Callback executed when the client removes dataframe
* @param {Dataframe} dataframe
*/
_onDataFrameRemoved(dataframe) {
this._dataframes = this._dataframes.filter(d => d !== dataframe);
this._integrator.renderer.removeDataframe(dataframe);
this._integrator.invalidateWebGLState();
}
/**
* Callback executed when the client finishes loading data
*/
_onDataLoaded() {
this.state = 'dataLoaded';
}
/**
* Set a new style for this layer.
*
* @param {carto.Style} style - New style
*
* @memberof carto.Layer
* @api
*/
setStyle(style) {
this._checkStyle(style);
return this._styleChanged(style).then(r => {
if (this._style) {
this._style.onChange(null);
}
this._style = style;
this._style.onChange(() => {
this._styleChanged(style);
});
return r;
});
}
/**
* Blend the current style with another style
*
* @param {carto.Style} style - style to blend to
*
* @memberof carto.Layer
* @api
*/
blendToStyle(style, ms = 400, interpolator = __WEBPACK_IMPORTED_MODULE_7__core_style_functions__["cubic"]) {
this._checkStyle(style);
if (this._style) {
style.getColor().blendFrom(this._style.getColor(), ms, interpolator);
style.getStrokeColor().blendFrom(this._style.getStrokeColor(), ms, interpolator);
style.getWidth().blendFrom(this._style.getWidth(), ms, interpolator);
style.getStrokeWidth().blendFrom(this._style.getStrokeWidth(), ms, interpolator);
style.filter.blendFrom(this._style.filter, ms, interpolator);
}
return this._styleChanged(style).then(r => {
if (this._style) {
this._style.onChange(null);
}
this._style = style;
this._style.onChange(() => {
this._styleChanged(style);
});
return r;
});
}
/**
* Add this layer to a map.
*
* @param {mapboxgl.Map} map
* @param {string} beforeLayerID
*
* @memberof carto.Layer
* @api
*/
addTo(map, beforeLayerID) {
if (this._isCartoMap(map)) {
this._addToCartoMap(map, beforeLayerID);
} else if (this._isMGLMap(map)) {
this._addToMGLMap(map, beforeLayerID);
} else {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'nonValidMap');
}
}
hasDataframes() {
return this._dataframes.length > 0;
}
getId() {
return this._id;
}
getSource() {
return this._source;
}
getStyle() {
return this._style;
}
_isCartoMap(map) {
return map instanceof __WEBPACK_IMPORTED_MODULE_3__map__["a" /* default */];
}
_isMGLMap() {
// TODO: implement this
return true;
}
_addToCartoMap(map, beforeLayerID) {
this._integrator = Object(__WEBPACK_IMPORTED_MODULE_4__integrator_carto__["a" /* default */])(map);
this._integrator.addLayer(this, beforeLayerID);
}
initCallback() {
this._styleChanged(this._style);
this.requestData();
}
_addToMGLMap(map, beforeLayerID) {
if (map.isStyleLoaded()) {
this._onMapLoaded(map, beforeLayerID);
} else {
map.on('load', () => {
this._onMapLoaded(map, beforeLayerID);
});
}
}
_onMapLoaded(map, beforeLayerID) {
this._integrator = Object(__WEBPACK_IMPORTED_MODULE_5__integrator_mapbox_gl__["a" /* default */])(map);
this._integrator.addLayer(this, beforeLayerID);
}
_styleChanged(style) {
const recompile = (metadata) => {
style._compileColorShader(this._integrator.renderer.gl, metadata);
style._compileWidthShader(this._integrator.renderer.gl, metadata);
style._compileStrokeColorShader(this._integrator.renderer.gl, metadata);
style._compileStrokeWidthShader(this._integrator.renderer.gl, metadata);
style._compileFilterShader(this._integrator.renderer.gl, metadata);
};
if (!(this._integrator && this._integrator.invalidateWebGLState)) {
return Promise.resolve();
}
const originalPromise = this.requestData(style);
if (!originalPromise) {
// The previous stored metadata is still valid
recompile(this.metadata);
return Promise.resolve();
}
// this.metadata needs to be updated, try to get new metadata and update this.metadata and proceed if everything works well
return originalPromise.then(metadata => {
this.metadata = metadata;
recompile(metadata);
});
}
_checkId(id) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](id)) {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'idRequired');
}
if (!__WEBPACK_IMPORTED_MODULE_0__util__["e" /* isString */](id)) {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'idStringRequired');
}
if (id === '') {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'nonValidId');
}
}
_checkSource(source) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](source)) {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'sourceRequired');
}
if (!(source instanceof __WEBPACK_IMPORTED_MODULE_1__source_base__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'nonValidSource');
}
}
_checkStyle(style) {
if (__WEBPACK_IMPORTED_MODULE_0__util__["f" /* isUndefined */](style)) {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'styleRequired');
}
if (!(style instanceof __WEBPACK_IMPORTED_MODULE_2__style__["a" /* default */])) {
throw new __WEBPACK_IMPORTED_MODULE_6__error_handling_carto_validation_error__["a" /* default */]('layer', 'nonValidStyle');
}
}
_getViewport() {
if (this._integrator) {
return this._integrator.renderer.getBounds();
}
throw new Error('?');
}
requestData(style) {
style = style || this._style;
if (!this._integrator.invalidateWebGLState) {
return;
}
return this._source.requestData(this._getViewport(), style);
}
getNumFeatures() {
return this._dataframes.filter(d => d.active).map(d => d.numFeatures).reduce((x, y) => x + y, 0);
}
//TODO free layer resources
}
/* harmony export (immutable) */ __webpack_exports__["a"] = Layer;
/***/ }),
/* 81 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = compileShader;
function compileShader(gl, styleRootExpr, shaderCreator) {
let uniformIDcounter = 0;
let tid = {};
const colorModifier = styleRootExpr._applyToShaderSource(() => uniformIDcounter++, name => {
if (tid[name] !== undefined) {
return tid[name];
}
tid[name] = Object.keys(tid).length;
return tid[name];
});
const shader = shaderCreator(gl, colorModifier.preface, colorModifier.inline);
styleRootExpr._postShaderCompile(shader.program, gl);
return {
tid: tid,
shader: shader
};
}
/***/ }),
/* 82 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export parseStyleExpression */
/* harmony export (immutable) */ __webpack_exports__["a"] = parseStyleDefinition;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jsep__ = __webpack_require__(83);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jsep___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jsep__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__functions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__expressions_utils__ = __webpack_require__(3);
// TODO use Schema classes
const aggFns = [];
var lowerCaseFunctions = {};
Object.keys(__WEBPACK_IMPORTED_MODULE_1__functions__)
.filter(name => name[0] == name[0].toLowerCase()) // Only get functions starting with lowercase
.map(name => { lowerCaseFunctions[name.toLocaleLowerCase()] = __WEBPACK_IMPORTED_MODULE_1__functions__[name]; });
lowerCaseFunctions.true = __WEBPACK_IMPORTED_MODULE_1__functions__["TRUE"];
lowerCaseFunctions.false = __WEBPACK_IMPORTED_MODULE_1__functions__["FALSE"];
/**
* @jsapi
* @param {*} str
* @param {*} schema
*/
function parseStyleExpression(str, schema) {
// jsep addBinaryOp pollutes its module scope, we need to remove the custom operators afterwards
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addBinaryOp('^', 10);
const r = parseNode(__WEBPACK_IMPORTED_MODULE_0_jsep___default()(str), schema);
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeBinaryOp('^');
return r;
}
function parseStyleNamedExpr(styleSpec, node) {
if (node.operator != ':') {
throw new Error('Invalid syntax');
}
const name = node.left.name;
if (!name) {
throw new Error('Invalid syntax');
}
const value = parseNode(node.right);
// Don't cast resolution properties implicitly since they must be of type Number
styleSpec[name] = name == 'resolution' ? value : Object(__WEBPACK_IMPORTED_MODULE_2__expressions_utils__["b" /* implicitCast */])(value);
}
function parseStyleDefinition(str) {
// jsep addBinaryOp pollutes its module scope, we need to remove the custom operators afterwards
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addBinaryOp(':', 0);
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addBinaryOp('^', 11);
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addBinaryOp('or', 1);
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addBinaryOp('and', 2);
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeLiteral('true');
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeLiteral('false');
const ast = __WEBPACK_IMPORTED_MODULE_0_jsep___default()(str);
let styleSpec = {};
if (ast.type == 'Compound') {
ast.body.map(node => parseStyleNamedExpr(styleSpec, node));
} else {
parseStyleNamedExpr(styleSpec, ast);
}
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeBinaryOp('and');
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeBinaryOp('or');
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeBinaryOp('^');
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.removeBinaryOp(':');
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addLiteral('true');
__WEBPACK_IMPORTED_MODULE_0_jsep___default.a.addLiteral('false');
return styleSpec;
}
function parseFunctionCall(node) {
const name = node.callee.name.toLowerCase();
if (aggFns.includes(name)) {
//node.arguments[0].name += '_' + name;
const args = node.arguments.map(arg => parseNode(arg));
return args[0];
}
const args = node.arguments.map(arg => parseNode(arg));
if (lowerCaseFunctions[name]) {
return lowerCaseFunctions[name](...args);
}
throw new Error(`Invalid function name '${node.callee.name}'`);
}
function parseBinaryOperation(node) {
const left = parseNode(node.left);
const right = parseNode(node.right);
switch (node.operator) {
case '*':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatMul"](left, right);
case '/':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatDiv"](left, right);
case '+':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatAdd"](left, right);
case '-':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatSub"](left, right);
case '%':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatMod"](left, right);
case '^':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatPow"](left, right);
case '>':
return __WEBPACK_IMPORTED_MODULE_1__functions__["greaterThan"](left, right);
case '>=':
return __WEBPACK_IMPORTED_MODULE_1__functions__["greaterThanOrEqualTo"](left, right);
case '<':
return __WEBPACK_IMPORTED_MODULE_1__functions__["lessThan"](left, right);
case '<=':
return __WEBPACK_IMPORTED_MODULE_1__functions__["lessThanOrEqualTo"](left, right);
case '==':
return __WEBPACK_IMPORTED_MODULE_1__functions__["equals"](left, right);
case 'and':
return __WEBPACK_IMPORTED_MODULE_1__functions__["and"](left, right);
case 'or':
return __WEBPACK_IMPORTED_MODULE_1__functions__["or"](left, right);
default:
throw new Error(`Invalid binary operator '${node.operator}'`);
}
}
function parseUnaryOperation(node) {
switch (node.operator) {
case '-':
return __WEBPACK_IMPORTED_MODULE_1__functions__["floatMul"](-1, parseNode(node.argument));
case '+':
return parseNode(node.argument);
default:
throw new Error(`Invalid unary operator '${node.operator}'`);
}
}
function parseIdentifier(node) {
if (node.name[0] == '$') {
return __WEBPACK_IMPORTED_MODULE_1__functions__["property"](node.name.substring(1));
} else if (__WEBPACK_IMPORTED_MODULE_1__functions__["palettes"][node.name.toLowerCase()]) {
return __WEBPACK_IMPORTED_MODULE_1__functions__["palettes"][node.name.toLowerCase()];
} else if (lowerCaseFunctions[node.name.toLowerCase()]) {
return lowerCaseFunctions[node.name.toLowerCase()];
}
}
function parseNode(node) {
if (node.type == 'CallExpression') {
return parseFunctionCall(node);
} else if (node.type == 'Literal') {
return node.value;
} else if (node.type == 'ArrayExpression') {
return node.elements.map(e => parseNode(e));
} else if (node.type == 'BinaryExpression') {
return parseBinaryOperation(node);
} else if (node.type == 'UnaryExpression') {
return parseUnaryOperation(node);
} else if (node.type == 'Identifier') {
return parseIdentifier(node);
}
throw new Error(`Invalid expression '${JSON.stringify(node)}'`);
}
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
// JavaScript Expression Parser (JSEP) 0.3.3
// JSEP may be freely distributed under the MIT License
// http://jsep.from.so/
/*global module: true, exports: true, console: true */
(function (root) {
'use strict';
// Node Types
// ----------
// This is the full set of types that any JSEP node can be.
// Store them here to save space when minified
var COMPOUND = 'Compound',
IDENTIFIER = 'Identifier',
MEMBER_EXP = 'MemberExpression',
LITERAL = 'Literal',
THIS_EXP = 'ThisExpression',
CALL_EXP = 'CallExpression',
UNARY_EXP = 'UnaryExpression',
BINARY_EXP = 'BinaryExpression',
LOGICAL_EXP = 'LogicalExpression',
CONDITIONAL_EXP = 'ConditionalExpression',
ARRAY_EXP = 'ArrayExpression',
PERIOD_CODE = 46, // '.'
COMMA_CODE = 44, // ','
SQUOTE_CODE = 39, // single quote
DQUOTE_CODE = 34, // double quotes
OPAREN_CODE = 40, // (
CPAREN_CODE = 41, // )
OBRACK_CODE = 91, // [
CBRACK_CODE = 93, // ]
QUMARK_CODE = 63, // ?
SEMCOL_CODE = 59, // ;
COLON_CODE = 58, // :
throwError = function(message, index) {
var error = new Error(message + ' at character ' + index);
error.index = index;
error.description = message;
throw error;
},
// Operations
// ----------
// Set `t` to `true` to save space (when minified, not gzipped)
t = true,
// Use a quickly-accessible map to store all of the unary operators
// Values are set to `true` (it really doesn't matter)
unary_ops = {'-': t, '!': t, '~': t, '+': t},
// Also use a map for the binary operations but set their values to their
// binary precedence for quick reference:
// see [Order of operations](http://en.wikipedia.org/wiki/Order_of_operations#Programming_language)
binary_ops = {
'||': 1, '&&': 2, '|': 3, '^': 4, '&': 5,
'==': 6, '!=': 6, '===': 6, '!==': 6,
'<': 7, '>': 7, '<=': 7, '>=': 7,
'<<':8, '>>': 8, '>>>': 8,
'+': 9, '-': 9,
'*': 10, '/': 10, '%': 10
},
// Get return the longest key length of any object
getMaxKeyLen = function(obj) {
var max_len = 0, len;
for(var key in obj) {
if((len = key.length) > max_len && obj.hasOwnProperty(key)) {
max_len = len;
}
}
return max_len;
},
max_unop_len = getMaxKeyLen(unary_ops),
max_binop_len = getMaxKeyLen(binary_ops),
// Literals
// ----------
// Store the values to return for the various literals we may encounter
literals = {
'true': true,
'false': false,
'null': null
},
// Except for `this`, which is special. This could be changed to something like `'self'` as well
this_str = 'this',
// Returns the precedence of a binary operator or `0` if it isn't a binary operator
binaryPrecedence = function(op_val) {
return binary_ops[op_val] || 0;
},
// Utility function (gets called from multiple places)
// Also note that `a && b` and `a || b` are *logical* expressions, not binary expressions
createBinaryExpression = function (operator, left, right) {
var type = (operator === '||' || operator === '&&') ? LOGICAL_EXP : BINARY_EXP;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
// `ch` is a character code in the next three functions
isDecimalDigit = function(ch) {
return (ch >= 48 && ch <= 57); // 0...9
},
isIdentifierStart = function(ch) {
return (ch === 36) || (ch === 95) || // `$` and `_`
(ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
},
isIdentifierPart = function(ch) {
return (ch === 36) || (ch === 95) || // `$` and `_`
(ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 48 && ch <= 57) || // 0...9
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
},
// Parsing
// -------
// `expr` is a string with the passed in expression
jsep = function(expr) {
// `index` stores the character number we are currently at while `length` is a constant
// All of the gobbles below will modify `index` as we move along
var index = 0,
charAtFunc = expr.charAt,
charCodeAtFunc = expr.charCodeAt,
exprI = function(i) { return charAtFunc.call(expr, i); },
exprICode = function(i) { return charCodeAtFunc.call(expr, i); },
length = expr.length,
// Push `index` up to the next non-space character
gobbleSpaces = function() {
var ch = exprICode(index);
// space or tab
while(ch === 32 || ch === 9 || ch === 10 || ch === 13) {
ch = exprICode(++index);
}
},
// The main parsing function. Much of this code is dedicated to ternary expressions
gobbleExpression = function() {
var test = gobbleBinaryExpression(),
consequent, alternate;
gobbleSpaces();
if(exprICode(index) === QUMARK_CODE) {
// Ternary expression: test ? consequent : alternate
index++;
consequent = gobbleExpression();
if(!consequent) {
throwError('Expected expression', index);
}
gobbleSpaces();
if(exprICode(index) === COLON_CODE) {
index++;
alternate = gobbleExpression();
if(!alternate) {
throwError('Expected expression', index);
}
return {
type: CONDITIONAL_EXP,
test: test,
consequent: consequent,
alternate: alternate
};
} else {
throwError('Expected :', index);
}
} else {
return test;
}
},
// Search for the operation portion of the string (e.g. `+`, `===`)
// Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
// and move down from 3 to 2 to 1 character until a matching binary operation is found
// then, return that binary operation
gobbleBinaryOp = function() {
gobbleSpaces();
var biop, to_check = expr.substr(index, max_binop_len), tc_len = to_check.length;
while(tc_len > 0) {
if(binary_ops.hasOwnProperty(to_check)) {
index += tc_len;
return to_check;
}
to_check = to_check.substr(0, --tc_len);
}
return false;
},
// This function is responsible for gobbling an individual expression,
// e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
gobbleBinaryExpression = function() {
var ch_i, node, biop, prec, stack, biop_info, left, right, i;
// First, try to get the leftmost thing
// Then, check to see if there's a binary operator operating on that leftmost thing
left = gobbleToken();
biop = gobbleBinaryOp();
// If there wasn't a binary operator, just return the leftmost node
if(!biop) {
return left;
}
// Otherwise, we need to start a stack to properly place the binary operations in their
// precedence structure
biop_info = { value: biop, prec: binaryPrecedence(biop)};
right = gobbleToken();
if(!right) {
throwError("Expected expression after " + biop, index);
}
stack = [left, biop_info, right];
// Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
while((biop = gobbleBinaryOp())) {
prec = binaryPrecedence(biop);
if(prec === 0) {
break;
}
biop_info = { value: biop, prec: prec };
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
biop = stack.pop().value;
left = stack.pop();
node = createBinaryExpression(biop, left, right);
stack.push(node);
}
node = gobbleToken();
if(!node) {
throwError("Expected expression after " + biop, index);
}
stack.push(biop_info, node);
}
i = stack.length - 1;
node = stack[i];
while(i > 1) {
node = createBinaryExpression(stack[i - 1].value, stack[i - 2], node);
i -= 2;
}
return node;
},
// An individual part of a binary expression:
// e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
gobbleToken = function() {
var ch, to_check, tc_len;
gobbleSpaces();
ch = exprICode(index);
if(isDecimalDigit(ch) || ch === PERIOD_CODE) {
// Char code 46 is a dot `.` which can start off a numeric literal
return gobbleNumericLiteral();
} else if(ch === SQUOTE_CODE || ch === DQUOTE_CODE) {
// Single or double quotes
return gobbleStringLiteral();
} else if (ch === OBRACK_CODE) {
return gobbleArray();
} else {
to_check = expr.substr(index, max_unop_len);
tc_len = to_check.length;
while(tc_len > 0) {
if(unary_ops.hasOwnProperty(to_check)) {
index += tc_len;
return {
type: UNARY_EXP,
operator: to_check,
argument: gobbleToken(),
prefix: true
};
}
to_check = to_check.substr(0, --tc_len);
}
if (isIdentifierStart(ch) || ch === OPAREN_CODE) { // open parenthesis
// `foo`, `bar.baz`
return gobbleVariable();
}
}
return false;
},
// Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
// keep track of everything in the numeric literal and then calling `parseFloat` on that string
gobbleNumericLiteral = function() {
var number = '', ch, chCode;
while(isDecimalDigit(exprICode(index))) {
number += exprI(index++);
}
if(exprICode(index) === PERIOD_CODE) { // can start with a decimal marker
number += exprI(index++);
while(isDecimalDigit(exprICode(index))) {
number += exprI(index++);
}
}
ch = exprI(index);
if(ch === 'e' || ch === 'E') { // exponent marker
number += exprI(index++);
ch = exprI(index);
if(ch === '+' || ch === '-') { // exponent sign
number += exprI(index++);
}
while(isDecimalDigit(exprICode(index))) { //exponent itself
number += exprI(index++);
}
if(!isDecimalDigit(exprICode(index-1)) ) {
throwError('Expected exponent (' + number + exprI(index) + ')', index);
}
}
chCode = exprICode(index);
// Check to make sure this isn't a variable name that start with a number (123abc)
if(isIdentifierStart(chCode)) {
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
} else if(chCode === PERIOD_CODE) {
throwError('Unexpected period', index);
}
return {
type: LITERAL,
value: parseFloat(number),
raw: number
};
},
// Parses a string literal, staring with single or double quotes with basic support for escape codes
// e.g. `"hello world"`, `'this is\nJSEP'`
gobbleStringLiteral = function() {
var str = '', quote = exprI(index++), closed = false, ch;
while(index < length) {
ch = exprI(index++);
if(ch === quote) {
closed = true;
break;
} else if(ch === '\\') {
// Check for all of the common escape codes
ch = exprI(index++);
switch(ch) {
case 'n': str += '\n'; break;
case 'r': str += '\r'; break;
case 't': str += '\t'; break;
case 'b': str += '\b'; break;
case 'f': str += '\f'; break;
case 'v': str += '\x0B'; break;
default : str += ch;
}
} else {
str += ch;
}
}
if(!closed) {
throwError('Unclosed quote after "'+str+'"', index);
}
return {
type: LITERAL,
value: str,
raw: quote + str + quote
};
},
// Gobbles only identifiers
// e.g.: `foo`, `_value`, `$x1`
// Also, this function checks if that identifier is a literal:
// (e.g. `true`, `false`, `null`) or `this`
gobbleIdentifier = function() {
var ch = exprICode(index), start = index, identifier;
if(isIdentifierStart(ch)) {
index++;
} else {
throwError('Unexpected ' + exprI(index), index);
}
while(index < length) {
ch = exprICode(index);
if(isIdentifierPart(ch)) {
index++;
} else {
break;
}
}
identifier = expr.slice(start, index);
if(literals.hasOwnProperty(identifier)) {
return {
type: LITERAL,
value: literals[identifier],
raw: identifier
};
} else if(identifier === this_str) {
return { type: THIS_EXP };
} else {
return {
type: IDENTIFIER,
name: identifier
};
}
},
// Gobbles a list of arguments within the context of a function call
// or array literal. This function also assumes that the opening character
// `(` or `[` has already been gobbled, and gobbles expressions and commas
// until the terminator character `)` or `]` is encountered.
// e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
gobbleArguments = function(termination) {
var ch_i, args = [], node, closed = false;
while(index < length) {
gobbleSpaces();
ch_i = exprICode(index);
if(ch_i === termination) { // done parsing
closed = true;
index++;
break;
} else if (ch_i === COMMA_CODE) { // between expressions
index++;
} else {
node = gobbleExpression();
if(!node || node.type === COMPOUND) {
throwError('Expected comma', index);
}
args.push(node);
}
}
if (!closed) {
throwError('Expected ' + String.fromCharCode(termination), index);
}
return args;
},
// Gobble a non-literal variable name. This variable name may include properties
// e.g. `foo`, `bar.baz`, `foo['bar'].baz`
// It also gobbles function calls:
// e.g. `Math.acos(obj.angle)`
gobbleVariable = function() {
var ch_i, node;
ch_i = exprICode(index);
if(ch_i === OPAREN_CODE) {
node = gobbleGroup();
} else {
node = gobbleIdentifier();
}
gobbleSpaces();
ch_i = exprICode(index);
while(ch_i === PERIOD_CODE || ch_i === OBRACK_CODE || ch_i === OPAREN_CODE) {
index++;
if(ch_i === PERIOD_CODE) {
gobbleSpaces();
node = {
type: MEMBER_EXP,
computed: false,
object: node,
property: gobbleIdentifier()
};
} else if(ch_i === OBRACK_CODE) {
node = {
type: MEMBER_EXP,
computed: true,
object: node,
property: gobbleExpression()
};
gobbleSpaces();
ch_i = exprICode(index);
if(ch_i !== CBRACK_CODE) {
throwError('Unclosed [', index);
}
index++;
} else if(ch_i === OPAREN_CODE) {
// A function call is being made; gobble all the arguments
node = {
type: CALL_EXP,
'arguments': gobbleArguments(CPAREN_CODE),
callee: node
};
}
gobbleSpaces();
ch_i = exprICode(index);
}
return node;
},
// Responsible for parsing a group of things within parentheses `()`
// This function assumes that it needs to gobble the opening parenthesis
// and then tries to gobble everything within that parenthesis, assuming
// that the next thing it should see is the close parenthesis. If not,
// then the expression probably doesn't have a `)`
gobbleGroup = function() {
index++;
var node = gobbleExpression();
gobbleSpaces();
if(exprICode(index) === CPAREN_CODE) {
index++;
return node;
} else {
throwError('Unclosed (', index);
}
},
// Responsible for parsing Array literals `[1, 2, 3]`
// This function assumes that it needs to gobble the opening bracket
// and then tries to gobble the expressions as arguments.
gobbleArray = function() {
index++;
return {
type: ARRAY_EXP,
elements: gobbleArguments(CBRACK_CODE)
};
},
nodes = [], ch_i, node;
while(index < length) {
ch_i = exprICode(index);
// Expressions can be separated by semicolons, commas, or just inferred without any
// separators
if(ch_i === SEMCOL_CODE || ch_i === COMMA_CODE) {
index++; // ignore separators
} else {
// Try to gobble each expression individually
if((node = gobbleExpression())) {
nodes.push(node);
// If we weren't able to find a binary expression and are out of room, then
// the expression passed in probably has too much
} else if(index < length) {
throwError('Unexpected "' + exprI(index) + '"', index);
}
}
}
// If there's only one expression just try returning the expression
if(nodes.length === 1) {
return nodes[0];
} else {
return {
type: COMPOUND,
body: nodes
};
}
};
// To be filled in by the template
jsep.version = '0.3.3';
jsep.toString = function() { return 'JavaScript Expression Parser (JSEP) v' + jsep.version; };
/**
* @method jsep.addUnaryOp
* @param {string} op_name The name of the unary op to add
* @return jsep
*/
jsep.addUnaryOp = function(op_name) {
max_unop_len = Math.max(op_name.length, max_unop_len);
unary_ops[op_name] = t; return this;
};
/**
* @method jsep.addBinaryOp
* @param {string} op_name The name of the binary op to add
* @param {number} precedence The precedence of the binary op (can be a float)
* @return jsep
*/
jsep.addBinaryOp = function(op_name, precedence) {
max_binop_len = Math.max(op_name.length, max_binop_len);
binary_ops[op_name] = precedence;
return this;
};
/**
* @method jsep.addLiteral
* @param {string} literal_name The name of the literal to add
* @param {*} literal_value The value of the literal
* @return jsep
*/
jsep.addLiteral = function(literal_name, literal_value) {
literals[literal_name] = literal_value;
return this;
};
/**
* @method jsep.removeUnaryOp
* @param {string} op_name The name of the unary op to remove
* @return jsep
*/
jsep.removeUnaryOp = function(op_name) {
delete unary_ops[op_name];
if(op_name.length === max_unop_len) {
max_unop_len = getMaxKeyLen(unary_ops);
}
return this;
};
/**
* @method jsep.removeAllUnaryOps
* @return jsep
*/
jsep.removeAllUnaryOps = function() {
unary_ops = {};
max_unop_len = 0;
return this;
};
/**
* @method jsep.removeBinaryOp
* @param {string} op_name The name of the binary op to remove
* @return jsep
*/
jsep.removeBinaryOp = function(op_name) {
delete binary_ops[op_name];
if(op_name.length === max_binop_len) {
max_binop_len = getMaxKeyLen(binary_ops);
}
return this;
};
/**
* @method jsep.removeAllBinaryOps
* @return jsep
*/
jsep.removeAllBinaryOps = function() {
binary_ops = {};
max_binop_len = 0;
return this;
};
/**
* @method jsep.removeLiteral
* @param {string} literal_name The name of the literal to remove
* @return jsep
*/
jsep.removeLiteral = function(literal_name) {
delete literals[literal_name];
return this;
};
/**
* @method jsep.removeAllLiterals
* @return jsep
*/
jsep.removeAllLiterals = function() {
literals = {};
return this;
};
// In desktop environments, have a way to restore the old value for `jsep`
if (false) {
var old_jsep = root.jsep;
// The star of the show! It's a function!
root.jsep = jsep;
// And a courteous function willing to move out of the way for other similarly-named objects!
jsep.noConflict = function() {
if(root.jsep === jsep) {
root.jsep = old_jsep;
}
return jsep;
};
} else {
// In Node.JS environments
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = jsep;
} else {
exports.parse = jsep;
}
}
}(this));
/***/ }),
/* 84 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getCartoMapIntegrator;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_renderer__ = __webpack_require__(8);
let integrator = null;
function getCartoMapIntegrator(map) {
if (!integrator) {
integrator = new CartoMapIntegrator(map);
}
return integrator;
}
class CartoMapIntegrator {
constructor(map) {
this.map = map;
this.renderer = new __WEBPACK_IMPORTED_MODULE_0__core_renderer__["b" /* Renderer */]();
this.renderer._initGL(this.map._gl);
this.invalidateWebGLState = () => {};
}
addLayer(layerId, layer) {
this.map.addLayer(layerId, layer);
}
}
/***/ }),
/* 85 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getMGLIntegrator;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_renderer__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(5);
let uid = 0;
// TODO This needs to be separated by each mgl map to support multi map pages
let integrator = null;
function getMGLIntegrator(map) {
if (!integrator) {
integrator = new MGLIntegrator(map);
}
return integrator;
}
/**
* Responsabilities, keep all MGL integration state and functionality that lies outside Layer
*/
class MGLIntegrator {
constructor(map) {
this.renderer = new __WEBPACK_IMPORTED_MODULE_0__core_renderer__["b" /* Renderer */]();
this.map = map;
this.invalidateWebGLState = null;
map.on('movestart', this.move.bind(this));
map.on('move', this.move.bind(this));
map.on('moveend', this.move.bind(this));
map.on('resize', this.move.bind(this));
this.moveObservers = {};
this._layers = [];
}
_registerMoveObserver(observerName, observerCallback) {
this.moveObservers[observerName] = observerCallback;
}
_unregisterMoveObserver(observerName) {
delete this.moveObservers[observerName];
}
addLayer(layer, beforeLayerID) {
const callbackID = `_cartoGL_${uid++}`;
const layerId = layer.getId();
this._registerMoveObserver(callbackID, layer.requestData.bind(layer));
this.map.repaint = true; // FIXME: add logic to manage repaint flag
this.map.setCustomWebGLDrawCallback(layerId, (gl, invalidate) => {
if (!this.invalidateWebGLState) {
this.invalidateWebGLState = invalidate;
this.notifyObservers();
this.renderer._initGL(gl);
layer.initCallback();
}
layer.paintCallback();
invalidate();
});
this.map.addLayer({
id: layerId,
type: 'custom-webgl'
}, beforeLayerID);
this._layers.push(layerId);
this.move();
}
needRefresh() {
this.map.repaint = true; // FIXME: add logic to manage repaint flag
}
move() {
var c = this.map.getCenter();
// TODO create getCenter method
this.renderer.setCenter(c.lng / 180., __WEBPACK_IMPORTED_MODULE_1__util__["g" /* wmProjection */](c).y / __WEBPACK_IMPORTED_MODULE_1__util__["b" /* WM_R */]);
this.renderer.setZoom(this.getZoom());
this.notifyObservers();
}
notifyObservers() {
Object.keys(this.moveObservers).map(id => this.moveObservers[id]());
}
getZoom() {
var b = this.map.getBounds();
var c = this.map.getCenter();
var nw = b.getNorthWest();
var sw = b.getSouthWest();
var z = (__WEBPACK_IMPORTED_MODULE_1__util__["g" /* wmProjection */](nw).y - __WEBPACK_IMPORTED_MODULE_1__util__["g" /* wmProjection */](sw).y) / __WEBPACK_IMPORTED_MODULE_1__util__["a" /* WM_2R */];
this.renderer.setCenter(c.lng / 180., __WEBPACK_IMPORTED_MODULE_1__util__["g" /* wmProjection */](c).y / __WEBPACK_IMPORTED_MODULE_1__util__["b" /* WM_R */]);
return z;
}
}
/***/ })
/******/ ]);
});
//# sourceMappingURL=carto-gl.js.map
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet">
<script src='./mapbox-gl-dev.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.2/mapbox-gl.css' rel='stylesheet' />
<script src='./carto-gl.js'></script>
<title>CARTO - Vector builder</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: 'Open Sans', sans-serif;
margin: 0;
padding: 0;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
display: flex;
}
nav {
width: 350px;
background: white;
padding: 15px;
}
input,
button {
border: 1px solid #ddd;
border-radius: 4px;
width: 100%;
height: 32px;
}
label {
font-weight: 100;
}
main {
box-shadow: inset 10px 0 10px -10px rgba(0, 0, 0, 0.3);
background: #F2F6F9;
flex: 1;
padding: 15px;
}
.map {
width: 100%;
height: 100%;
}
input,
textarea {
margin-bottom: 10px;
margin-top: 5px;
padding: 15px;
}
button {
background: #1785FB;
color: white;
margin-top: 15px;
}
textarea {
outline: none;
background: #2E3C43;
color: white;
width: 100%;
height: 150px;
resize: none;
font-family: monospace;
padding: 15px;
}
</style>
</head>
<body>
<nav>
<h3>
CARTO - Vuilder
</h3>
<form id="login">
<label for="">Username</label>
<input id="username" type="text" value="dmanzanares">
<label for="">Api key</label>
<input id="api-key" type="text" value="1234">
<label for="">Dataset</label>
<input id="dataset" type="text" value="ne_10m_populated_places_simple">
<button type="button" id="start"> START </button>
</form>
<textarea style="display: none" id="style"></textarea>
</nav>
<main>
<div id="map" class="map"></div>
</main>
<script>
const BASEMAPS = {
DarkMatter: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
Voyager: 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json',
Positron: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json',
};
var basemap = 'DarkMatter';
var map = new mapboxgl.Map({
container: 'map', // container id
style: BASEMAPS[basemap], // stylesheet location
center: [2.17, 41.38], // starting position [lng, lat]
zoom: 3, // starting zoom,
});
</script>
<script>
document.querySelector('#start').addEventListener('click', e => {
document.querySelector('#login').style.display = 'none';
const auth = {
user: document.querySelector('#username').value,
apiKey: '1234'
};
const source = new carto.source.Dataset(document.querySelector('#dataset').value, auth);
const style = new carto.Style();
const layer = new carto.Layer('carto_layer', source, style);
layer.addTo(map);
document.querySelector('#style').style.display = 'block';
document.querySelector('#style').addEventListener('input', e => {
try {
layer.blendToStyle(new carto.Style(e.target.value))
} catch (e) {
// Ignore errors
}
});
});
</script>
</body>
</html>
.mapboxgl-map {
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
overflow: hidden;
position: relative;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
.mapboxgl-map:-webkit-full-screen {
width: 100%;
height: 100%;
}
.mapboxgl-missing-css {
display: none;
}
.mapboxgl-canvas-container.mapboxgl-interactive,
.mapboxgl-ctrl-nav-compass {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.mapboxgl-canvas-container.mapboxgl-interactive:active,
.mapboxgl-ctrl-nav-compass:active {
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate {
-ms-touch-action: pan-x pan-y;
touch-action: pan-x pan-y;
}
.mapboxgl-canvas-container.mapboxgl-touch-drag-pan {
-ms-touch-action: pinch-zoom;
}
.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan {
-ms-touch-action: none;
touch-action: none;
}
.mapboxgl-ctrl-top-left,
.mapboxgl-ctrl-top-right,
.mapboxgl-ctrl-bottom-left,
.mapboxgl-ctrl-bottom-right { position:absolute; pointer-events:none; z-index:2; }
.mapboxgl-ctrl-top-left { top:0; left:0; }
.mapboxgl-ctrl-top-right { top:0; right:0; }
.mapboxgl-ctrl-bottom-left { bottom:0; left:0; }
.mapboxgl-ctrl-bottom-right { right:0; bottom:0; }
.mapboxgl-ctrl { clear:both; pointer-events:auto }
.mapboxgl-ctrl-top-left .mapboxgl-ctrl { margin:10px 0 0 10px; float:left; }
.mapboxgl-ctrl-top-right .mapboxgl-ctrl{ margin:10px 10px 0 0; float:right; }
.mapboxgl-ctrl-bottom-left .mapboxgl-ctrl { margin:0 0 10px 10px; float:left; }
.mapboxgl-ctrl-bottom-right .mapboxgl-ctrl { margin:0 10px 10px 0; float:right; }
.mapboxgl-ctrl-group {
border-radius: 4px;
-moz-box-shadow: 0px 0px 2px rgba(0,0,0,0.1);
-webkit-box-shadow: 0px 0px 2px rgba(0,0,0,0.1);
box-shadow: 0px 0px 0px 2px rgba(0,0,0,0.1);
overflow: hidden;
background: #fff;
}
.mapboxgl-ctrl-group > button {
width: 30px;
height: 30px;
display: block;
padding: 0;
outline: none;
border: none;
border-bottom: 1px solid #ddd;
box-sizing: border-box;
background-color: rgba(0,0,0,0);
cursor: pointer;
}
/* https://bugzilla.mozilla.org/show_bug.cgi?id=140562 */
.mapboxgl-ctrl > button::-moz-focus-inner {
border: 0;
padding: 0;
}
.mapboxgl-ctrl > button:last-child {
border-bottom: 0;
}
.mapboxgl-ctrl > button:hover {
background-color: rgba(0,0,0,0.05);
}
.mapboxgl-ctrl-icon,
.mapboxgl-ctrl-icon > .mapboxgl-ctrl-compass-arrow {
speak: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.mapboxgl-ctrl-icon {
padding: 5px;
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-zoom-out {
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0A%20%20%3Cpath%20style%3D%27fill%3A%23333333%3B%27%20d%3D%27m%207%2C9%20c%20-0.554%2C0%20-1%2C0.446%20-1%2C1%200%2C0.554%200.446%2C1%201%2C1%20l%206%2C0%20c%200.554%2C0%201%2C-0.446%201%2C-1%200%2C-0.554%20-0.446%2C-1%20-1%2C-1%20z%27%20%2F%3E%0A%3C%2Fsvg%3E%0A");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-zoom-in {
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0A%20%20%3Cpath%20style%3D%27fill%3A%23333333%3B%27%20d%3D%27M%2010%206%20C%209.446%206%209%206.4459904%209%207%20L%209%209%20L%207%209%20C%206.446%209%206%209.446%206%2010%20C%206%2010.554%206.446%2011%207%2011%20L%209%2011%20L%209%2013%20C%209%2013.55401%209.446%2014%2010%2014%20C%2010.554%2014%2011%2013.55401%2011%2013%20L%2011%2011%20L%2013%2011%20C%2013.554%2011%2014%2010.554%2014%2010%20C%2014%209.446%2013.554%209%2013%209%20L%2011%209%20L%2011%207%20C%2011%206.4459904%2010.554%206%2010%206%20z%27%20%2F%3E%0A%3C%2Fsvg%3E%0A");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0D%0A%20%20%3Cpath%20style%3D%27fill%3A%23333%3B%27%20d%3D%27M10%204C9%204%209%205%209%205L9%205.1A5%205%200%200%200%205.1%209L5%209C5%209%204%209%204%2010%204%2011%205%2011%205%2011L5.1%2011A5%205%200%200%200%209%2014.9L9%2015C9%2015%209%2016%2010%2016%2011%2016%2011%2015%2011%2015L11%2014.9A5%205%200%200%200%2014.9%2011L15%2011C15%2011%2016%2011%2016%2010%2016%209%2015%209%2015%209L14.9%209A5%205%200%200%200%2011%205.1L11%205C11%205%2011%204%2010%204zM10%206.5A3.5%203.5%200%200%201%2013.5%2010%203.5%203.5%200%200%201%2010%2013.5%203.5%203.5%200%200%201%206.5%2010%203.5%203.5%200%200%201%2010%206.5zM10%208.3A1.8%201.8%200%200%200%208.3%2010%201.8%201.8%200%200%200%2010%2011.8%201.8%201.8%200%200%200%2011.8%2010%201.8%201.8%200%200%200%2010%208.3z%27%20%2F%3E%0D%0A%3C%2Fsvg%3E");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate:disabled {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0D%0A%20%20%3Cpath%20style%3D%27fill%3A%23aaa%3B%27%20d%3D%27M10%204C9%204%209%205%209%205L9%205.1A5%205%200%200%200%205.1%209L5%209C5%209%204%209%204%2010%204%2011%205%2011%205%2011L5.1%2011A5%205%200%200%200%209%2014.9L9%2015C9%2015%209%2016%2010%2016%2011%2016%2011%2015%2011%2015L11%2014.9A5%205%200%200%200%2014.9%2011L15%2011C15%2011%2016%2011%2016%2010%2016%209%2015%209%2015%209L14.9%209A5%205%200%200%200%2011%205.1L11%205C11%205%2011%204%2010%204zM10%206.5A3.5%203.5%200%200%201%2013.5%2010%203.5%203.5%200%200%201%2010%2013.5%203.5%203.5%200%200%201%206.5%2010%203.5%203.5%200%200%201%2010%206.5zM10%208.3A1.8%201.8%200%200%200%208.3%2010%201.8%201.8%200%200%200%2010%2011.8%201.8%201.8%200%200%200%2011.8%2010%201.8%201.8%200%200%200%2010%208.3z%27%20%2F%3E%0D%0A%3C%2Fsvg%3E");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0D%0A%20%20%3Cpath%20style%3D%27fill%3A%2333b5e5%3B%27%20d%3D%27M10%204C9%204%209%205%209%205L9%205.1A5%205%200%200%200%205.1%209L5%209C5%209%204%209%204%2010%204%2011%205%2011%205%2011L5.1%2011A5%205%200%200%200%209%2014.9L9%2015C9%2015%209%2016%2010%2016%2011%2016%2011%2015%2011%2015L11%2014.9A5%205%200%200%200%2014.9%2011L15%2011C15%2011%2016%2011%2016%2010%2016%209%2015%209%2015%209L14.9%209A5%205%200%200%200%2011%205.1L11%205C11%205%2011%204%2010%204zM10%206.5A3.5%203.5%200%200%201%2013.5%2010%203.5%203.5%200%200%201%2010%2013.5%203.5%203.5%200%200%201%206.5%2010%203.5%203.5%200%200%201%2010%206.5zM10%208.3A1.8%201.8%200%200%200%208.3%2010%201.8%201.8%200%200%200%2010%2011.8%201.8%201.8%200%200%200%2011.8%2010%201.8%201.8%200%200%200%2010%208.3z%27%20%2F%3E%0D%0A%3C%2Fsvg%3E");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active-error {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0D%0A%20%20%3Cpath%20style%3D%27fill%3A%23e58978%3B%27%20d%3D%27M10%204C9%204%209%205%209%205L9%205.1A5%205%200%200%200%205.1%209L5%209C5%209%204%209%204%2010%204%2011%205%2011%205%2011L5.1%2011A5%205%200%200%200%209%2014.9L9%2015C9%2015%209%2016%2010%2016%2011%2016%2011%2015%2011%2015L11%2014.9A5%205%200%200%200%2014.9%2011L15%2011C15%2011%2016%2011%2016%2010%2016%209%2015%209%2015%209L14.9%209A5%205%200%200%200%2011%205.1L11%205C11%205%2011%204%2010%204zM10%206.5A3.5%203.5%200%200%201%2013.5%2010%203.5%203.5%200%200%201%2010%2013.5%203.5%203.5%200%200%201%206.5%2010%203.5%203.5%200%200%201%2010%206.5zM10%208.3A1.8%201.8%200%200%200%208.3%2010%201.8%201.8%200%200%200%2010%2011.8%201.8%201.8%200%200%200%2011.8%2010%201.8%201.8%200%200%200%2010%208.3z%27%20%2F%3E%0D%0A%3C%2Fsvg%3E");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0A%20%20%3Cpath%20style%3D%27fill%3A%2333b5e5%3B%27%20d%3D%27M%2010%2C4%20C%209%2C4%209%2C5%209%2C5%20L%209%2C5.1%20C%207.0357113%2C5.5006048%205.5006048%2C7.0357113%205.1%2C9%20L%205%2C9%20c%200%2C0%20-1%2C0%20-1%2C1%200%2C1%201%2C1%201%2C1%20l%200.1%2C0%20c%200.4006048%2C1.964289%201.9357113%2C3.499395%203.9%2C3.9%20L%209%2C15%20c%200%2C0%200%2C1%201%2C1%201%2C0%201%2C-1%201%2C-1%20l%200%2C-0.1%20c%201.964289%2C-0.400605%203.499395%2C-1.935711%203.9%2C-3.9%20l%200.1%2C0%20c%200%2C0%201%2C0%201%2C-1%20C%2016%2C9%2015%2C9%2015%2C9%20L%2014.9%2C9%20C%2014.499395%2C7.0357113%2012.964289%2C5.5006048%2011%2C5.1%20L%2011%2C5%20c%200%2C0%200%2C-1%20-1%2C-1%20z%20m%200%2C2.5%20c%201.932997%2C0%203.5%2C1.5670034%203.5%2C3.5%200%2C1.932997%20-1.567003%2C3.5%20-3.5%2C3.5%20C%208.0670034%2C13.5%206.5%2C11.932997%206.5%2C10%206.5%2C8.0670034%208.0670034%2C6.5%2010%2C6.5%20Z%27%20%2F%3E%0A%3C%2Fsvg%3E");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background-error {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0A%20%20%3Cpath%20style%3D%27fill%3A%23e54e33%3B%27%20d%3D%27M%2010%2C4%20C%209%2C4%209%2C5%209%2C5%20L%209%2C5.1%20C%207.0357113%2C5.5006048%205.5006048%2C7.0357113%205.1%2C9%20L%205%2C9%20c%200%2C0%20-1%2C0%20-1%2C1%200%2C1%201%2C1%201%2C1%20l%200.1%2C0%20c%200.4006048%2C1.964289%201.9357113%2C3.499395%203.9%2C3.9%20L%209%2C15%20c%200%2C0%200%2C1%201%2C1%201%2C0%201%2C-1%201%2C-1%20l%200%2C-0.1%20c%201.964289%2C-0.400605%203.499395%2C-1.935711%203.9%2C-3.9%20l%200.1%2C0%20c%200%2C0%201%2C0%201%2C-1%20C%2016%2C9%2015%2C9%2015%2C9%20L%2014.9%2C9%20C%2014.499395%2C7.0357113%2012.964289%2C5.5006048%2011%2C5.1%20L%2011%2C5%20c%200%2C0%200%2C-1%20-1%2C-1%20z%20m%200%2C2.5%20c%201.932997%2C0%203.5%2C1.5670034%203.5%2C3.5%200%2C1.932997%20-1.567003%2C3.5%20-3.5%2C3.5%20C%208.0670034%2C13.5%206.5%2C11.932997%206.5%2C10%206.5%2C8.0670034%208.0670034%2C6.5%2010%2C6.5%20Z%27%20%2F%3E%0A%3C%2Fsvg%3E");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-waiting {
-webkit-animation: mapboxgl-spin 2s infinite linear;
-moz-animation: mapboxgl-spin 2s infinite linear;
-o-animation: mapboxgl-spin 2s infinite linear;
-ms-animation: mapboxgl-spin 2s infinite linear;
animation: mapboxgl-spin 2s infinite linear;
}
@-webkit-keyframes mapboxgl-spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@-moz-keyframes mapboxgl-spin {
0% { -moz-transform: rotate(0deg); }
100% { -moz-transform: rotate(360deg); }
}
@-o-keyframes mapboxgl-spin {
0% { -o-transform: rotate(0deg); }
100% { -o-transform: rotate(360deg); }
}
@-ms-keyframes mapboxgl-spin {
0% { -ms-transform: rotate(0deg); }
100% { -ms-transform: rotate(360deg); }
}
@keyframes mapboxgl-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-fullscreen {
background-image: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4wLjEsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0iTGF5ZXJfMSIKICAgeD0iMHB4IgogICB5PSIwcHgiCiAgIHZpZXdCb3g9IjAgMCAyMCAyMCIKICAgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMjAgMjA7IgogICB4bWw6c3BhY2U9InByZXNlcnZlIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIKICAgc29kaXBvZGk6ZG9jbmFtZT0iZnVsbHNjcmVlbi5zdmciPjxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTQxODUiPjxyZGY6UkRGPjxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj48ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD48ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+PGRjOnRpdGxlPjwvZGM6dGl0bGU+PC9jYzpXb3JrPjwvcmRmOlJERj48L21ldGFkYXRhPjxkZWZzCiAgICAgaWQ9ImRlZnM0MTgzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZmZmZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTQ3MSIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI2OTUiCiAgICAgaWQ9Im5hbWVkdmlldzQxODEiCiAgICAgc2hvd2dyaWQ9ImZhbHNlIgogICAgIGlua3NjYXBlOnpvb209IjExLjMxMzcwOCIKICAgICBpbmtzY2FwZTpjeD0iMTQuNjk4MjgiCiAgICAgaW5rc2NhcGU6Y3k9IjEwLjUyNjY4OSIKICAgICBpbmtzY2FwZTp3aW5kb3cteD0iNjk3IgogICAgIGlua3NjYXBlOndpbmRvdy15PSIyOTgiCiAgICAgaW5rc2NhcGU6d2luZG93LW1heGltaXplZD0iMCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIgogICAgIGlua3NjYXBlOnNuYXAtYmJveD0idHJ1ZSIKICAgICBpbmtzY2FwZTpiYm94LXBhdGhzPSJ0cnVlIgogICAgIGlua3NjYXBlOm9iamVjdC1wYXRocz0idHJ1ZSIKICAgICBpbmtzY2FwZTpiYm94LW5vZGVzPSJ0cnVlIgogICAgIGlua3NjYXBlOm9iamVjdC1ub2Rlcz0idHJ1ZSI+PGlua3NjYXBlOmdyaWQKICAgICAgIHR5cGU9Inh5Z3JpZCIKICAgICAgIGlkPSJncmlkNjA3NiIgLz48L3NvZGlwb2RpOm5hbWVkdmlldz48cGF0aAogICAgIGQ9Ik0gNSA0IEMgNC41IDQgNCA0LjUgNCA1IEwgNCA2IEwgNCA5IEwgNC41IDkgTCA1Ljc3NzM0MzggNy4yOTY4NzUgQyA2Ljc3NzEzMTkgOC4wNjAyMTMxIDcuODM1NzY1IDguOTU2NTcyOCA4Ljg5MDYyNSAxMCBDIDcuODI1NzEyMSAxMS4wNjMzIDYuNzc2MTc5MSAxMS45NTE2NzUgNS43ODEyNSAxMi43MDcwMzEgTCA0LjUgMTEgTCA0IDExIEwgNCAxNSBDIDQgMTUuNSA0LjUgMTYgNSAxNiBMIDkgMTYgTCA5IDE1LjUgTCA3LjI3MzQzNzUgMTQuMjA1MDc4IEMgOC4wNDI4OTMxIDEzLjE4Nzg4NiA4LjkzOTU0NDEgMTIuMTMzNDgxIDkuOTYwOTM3NSAxMS4wNjgzNTkgQyAxMS4wNDIzNzEgMTIuMTQ2OTkgMTEuOTQyMDkzIDEzLjIxMTIgMTIuNzA3MDMxIDE0LjIxODc1IEwgMTEgMTUuNSBMIDExIDE2IEwgMTQgMTYgTCAxNSAxNiBDIDE1LjUgMTYgMTYgMTUuNSAxNiAxNSBMIDE2IDE0IEwgMTYgMTEgTCAxNS41IDExIEwgMTQuMjA1MDc4IDEyLjcyNjU2MiBDIDEzLjE3Nzk4NSAxMS45NDk2MTcgMTIuMTEyNzE4IDExLjA0MzU3NyAxMS4wMzcxMDkgMTAuMDA5NzY2IEMgMTIuMTUxODU2IDguOTgxMDYxIDEzLjIyNDM0NSA4LjA3OTg2MjQgMTQuMjI4NTE2IDcuMzA0Njg3NSBMIDE1LjUgOSBMIDE2IDkgTCAxNiA1IEMgMTYgNC41IDE1LjUgNCAxNSA0IEwgMTEgNCBMIDExIDQuNSBMIDEyLjcwMzEyNSA1Ljc3NzM0MzggQyAxMS45MzI2NDcgNi43ODY0ODM0IDExLjAyNjY5MyA3Ljg1NTQ3MTIgOS45NzA3MDMxIDguOTE5OTIxOSBDIDguOTU4NDczOSA3LjgyMDQ5NDMgOC4wNjk4NzY3IDYuNzYyNzE4OCA3LjMwNDY4NzUgNS43NzE0ODQ0IEwgOSA0LjUgTCA5IDQgTCA2IDQgTCA1IDQgeiAiCiAgICAgaWQ9InBhdGg0MTY5IiAvPjwvc3ZnPg==");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-shrink {
background-image: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4wLjEsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0iTGF5ZXJfMSIKICAgeD0iMHB4IgogICB5PSIwcHgiCiAgIHZpZXdCb3g9IjAgMCAyMCAyMCIKICAgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMjAgMjA7IgogICB4bWw6c3BhY2U9InByZXNlcnZlIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIKICAgc29kaXBvZGk6ZG9jbmFtZT0ic2hyaW5rLnN2ZyI+PG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhMTkiPjxyZGY6UkRGPjxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj48ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD48ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+PGRjOnRpdGxlPjwvZGM6dGl0bGU+PC9jYzpXb3JrPjwvcmRmOlJERj48L21ldGFkYXRhPjxkZWZzCiAgICAgaWQ9ImRlZnMxNyIgLz48c29kaXBvZGk6bmFtZWR2aWV3CiAgICAgcGFnZWNvbG9yPSIjZmZmZmZmIgogICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IgogICAgIGJvcmRlcm9wYWNpdHk9IjEiCiAgICAgb2JqZWN0dG9sZXJhbmNlPSIxMCIKICAgICBncmlkdG9sZXJhbmNlPSIxMCIKICAgICBndWlkZXRvbGVyYW5jZT0iMTAiCiAgICAgaW5rc2NhcGU6cGFnZW9wYWNpdHk9IjAiCiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIKICAgICBpbmtzY2FwZTp3aW5kb3ctd2lkdGg9IjIwMjEiCiAgICAgaW5rc2NhcGU6d2luZG93LWhlaWdodD0iOTA4IgogICAgIGlkPSJuYW1lZHZpZXcxNSIKICAgICBzaG93Z3JpZD0iZmFsc2UiCiAgICAgaW5rc2NhcGU6em9vbT0iMSIKICAgICBpbmtzY2FwZTpjeD0iNC45NTAxMDgyIgogICAgIGlua3NjYXBlOmN5PSIxMC44NTQ3NDciCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LXk9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LW1heGltaXplZD0iMCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIgogICAgIGlua3NjYXBlOnNuYXAtYmJveD0idHJ1ZSIKICAgICBpbmtzY2FwZTpiYm94LXBhdGhzPSJ0cnVlIgogICAgIGlua3NjYXBlOnNuYXAtYmJveC1lZGdlLW1pZHBvaW50cz0idHJ1ZSIKICAgICBpbmtzY2FwZTpiYm94LW5vZGVzPSJ0cnVlIgogICAgIGlua3NjYXBlOnNuYXAtYmJveC1taWRwb2ludHM9InRydWUiCiAgICAgaW5rc2NhcGU6b2JqZWN0LXBhdGhzPSJ0cnVlIgogICAgIGlua3NjYXBlOm9iamVjdC1ub2Rlcz0idHJ1ZSI+PGlua3NjYXBlOmdyaWQKICAgICAgIHR5cGU9Inh5Z3JpZCIKICAgICAgIGlkPSJncmlkNDE0NyIgLz48L3NvZGlwb2RpOm5hbWVkdmlldz48cGF0aAogICAgIHN0eWxlPSJmaWxsOiMwMDAwMDAiCiAgICAgZD0iTSA0LjI0MjE4NzUgMy40OTIxODc1IEEgMC43NTAwNzUgMC43NTAwNzUgMCAwIDAgMy43MTg3NSA0Ljc4MTI1IEwgNS45NjQ4NDM4IDcuMDI3MzQzOCBMIDQgOC41IEwgNCA5IEwgOCA5IEMgOC41MDAwMDEgOC45OTk5OTg4IDkgOC40OTk5OTkyIDkgOCBMIDkgNCBMIDguNSA0IEwgNy4wMTc1NzgxIDUuOTU1MDc4MSBMIDQuNzgxMjUgMy43MTg3NSBBIDAuNzUwMDc1IDAuNzUwMDc1IDAgMCAwIDQuMjQyMTg3NSAzLjQ5MjE4NzUgeiBNIDE1LjczNDM3NSAzLjQ5MjE4NzUgQSAwLjc1MDA3NSAwLjc1MDA3NSAwIDAgMCAxNS4yMTg3NSAzLjcxODc1IEwgMTIuOTg0Mzc1IDUuOTUzMTI1IEwgMTEuNSA0IEwgMTEgNCBMIDExIDggQyAxMSA4LjQ5OTk5OTIgMTEuNDk5OTk5IDguOTk5OTk4OCAxMiA5IEwgMTYgOSBMIDE2IDguNSBMIDE0LjAzNTE1NiA3LjAyNzM0MzggTCAxNi4yODEyNSA0Ljc4MTI1IEEgMC43NTAwNzUgMC43NTAwNzUgMCAwIDAgMTUuNzM0Mzc1IDMuNDkyMTg3NSB6IE0gNCAxMSBMIDQgMTEuNSBMIDUuOTY0ODQzOCAxMi45NzI2NTYgTCAzLjcxODc1IDE1LjIxODc1IEEgMC43NTEzMDA5NiAwLjc1MTMwMDk2IDAgMSAwIDQuNzgxMjUgMTYuMjgxMjUgTCA3LjAyNzM0MzggMTQuMDM1MTU2IEwgOC41IDE2IEwgOSAxNiBMIDkgMTIgQyA5IDExLjUwMDAwMSA4LjUwMDAwMSAxMS4wMDAwMDEgOCAxMSBMIDQgMTEgeiBNIDEyIDExIEMgMTEuNDk5OTk5IDExLjAwMDAwMSAxMSAxMS41MDAwMDEgMTEgMTIgTCAxMSAxNiBMIDExLjUgMTYgTCAxMi45NzI2NTYgMTQuMDM1MTU2IEwgMTUuMjE4NzUgMTYuMjgxMjUgQSAwLjc1MTMwMDk2IDAuNzUxMzAwOTYgMCAxIDAgMTYuMjgxMjUgMTUuMjE4NzUgTCAxNC4wMzUxNTYgMTIuOTcyNjU2IEwgMTYgMTEuNSBMIDE2IDExIEwgMTIgMTEgeiAiCiAgICAgaWQ9InBhdGg3IiAvPjwvc3ZnPg==");
}
.mapboxgl-ctrl-icon.mapboxgl-ctrl-compass > .mapboxgl-ctrl-compass-arrow {
width: 20px;
height: 20px;
margin: 5px;
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2020%2020%27%3E%0A%09%3Cpolygon%20fill%3D%27%23333333%27%20points%3D%276%2C9%2010%2C1%2014%2C9%27%2F%3E%0A%09%3Cpolygon%20fill%3D%27%23CCCCCC%27%20points%3D%276%2C11%2010%2C19%2014%2C11%20%27%2F%3E%0A%3C%2Fsvg%3E");
background-repeat: no-repeat;
display: inline-block;
}
a.mapboxgl-ctrl-logo {
width: 85px;
height: 21px;
margin: 0 0 -3px -3px;
display: block;
background-repeat: no-repeat;
cursor: pointer;
background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiAgIHZpZXdCb3g9IjAgMCA4NC40OSAyMSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgODQuNDkgMjE7IiB4bWw6c3BhY2U9InByZXNlcnZlIj48Zz4gIDxwYXRoIGNsYXNzPSJzdDAiIHN0eWxlPSJvcGFjaXR5OjAuOTsgZmlsbDogI0ZGRkZGRjsgZW5hYmxlLWJhY2tncm91bmQ6IG5ldzsiIGQ9Ik04My4yNSwxNC4yNmMwLDAuMTItMC4wOSwwLjIxLTAuMjEsMC4yMWgtMS42MWMtMC4xMywwLTAuMjQtMC4wNi0wLjMtMC4xN2wtMS40NC0yLjM5bC0xLjQ0LDIuMzkgICAgYy0wLjA2LDAuMTEtMC4xOCwwLjE3LTAuMywwLjE3aC0xLjYxYy0wLjA0LDAtMC4wOC0wLjAxLTAuMTItMC4wM2MtMC4wOS0wLjA2LTAuMTMtMC4xOS0wLjA2LTAuMjhsMCwwbDIuNDMtMy42OEw3Ni4yLDYuODQgICAgYy0wLjAyLTAuMDMtMC4wMy0wLjA3LTAuMDMtMC4xMmMwLTAuMTIsMC4wOS0wLjIxLDAuMjEtMC4yMWgxLjYxYzAuMTMsMCwwLjI0LDAuMDYsMC4zLDAuMTdsMS40MSwyLjM2bDEuNC0yLjM1ICAgIGMwLjA2LTAuMTEsMC4xOC0wLjE3LDAuMy0wLjE3SDgzYzAuMDQsMCwwLjA4LDAuMDEsMC4xMiwwLjAzYzAuMDksMC4wNiwwLjEzLDAuMTksMC4wNiwwLjI4bDAsMGwtMi4zNywzLjYzbDIuNDMsMy42NyAgICBDODMuMjQsMTQuMTgsODMuMjUsMTQuMjIsODMuMjUsMTQuMjZ6Ii8+ICA8cGF0aCBjbGFzcz0ic3QwIiBzdHlsZT0ib3BhY2l0eTowLjk7IGZpbGw6ICNGRkZGRkY7IGVuYWJsZS1iYWNrZ3JvdW5kOiBuZXc7IiBkPSJNNjYuMjQsOS41OWMtMC4zOS0xLjg4LTEuOTYtMy4yOC0zLjg0LTMuMjhjLTEuMDMsMC0yLjAzLDAuNDItMi43MywxLjE4VjMuNTFjMC0wLjEzLTAuMS0wLjIzLTAuMjMtMC4yM2gtMS40ICAgIGMtMC4xMywwLTAuMjMsMC4xMS0wLjIzLDAuMjN2MTAuNzJjMCwwLjEzLDAuMSwwLjIzLDAuMjMsMC4yM2gxLjRjMC4xMywwLDAuMjMtMC4xMSwwLjIzLTAuMjNWMTMuNWMwLjcxLDAuNzUsMS43LDEuMTgsMi43MywxLjE4ICAgIGMxLjg4LDAsMy40NS0xLjQxLDMuODQtMy4yOUM2Ni4zNywxMC43OSw2Ni4zNywxMC4xOCw2Ni4yNCw5LjU5TDY2LjI0LDkuNTl6IE02Mi4wOCwxM2MtMS4zMiwwLTIuMzktMS4xMS0yLjQxLTIuNDh2LTAuMDYgICAgYzAuMDItMS4zOCwxLjA5LTIuNDgsMi40MS0yLjQ4czIuNDIsMS4xMiwyLjQyLDIuNTFTNjMuNDEsMTMsNjIuMDgsMTN6Ii8+ICA8cGF0aCBjbGFzcz0ic3QwIiBzdHlsZT0ib3BhY2l0eTowLjk7IGZpbGw6ICNGRkZGRkY7IGVuYWJsZS1iYWNrZ3JvdW5kOiBuZXc7IiBkPSJNNzEuNjcsNi4zMmMtMS45OC0wLjAxLTMuNzIsMS4zNS00LjE2LDMuMjljLTAuMTMsMC41OS0wLjEzLDEuMTksMCwxLjc3YzAuNDQsMS45NCwyLjE3LDMuMzIsNC4xNywzLjMgICAgYzIuMzUsMCw0LjI2LTEuODcsNC4yNi00LjE5Uzc0LjA0LDYuMzIsNzEuNjcsNi4zMnogTTcxLjY1LDEzLjAxYy0xLjMzLDAtMi40Mi0xLjEyLTIuNDItMi41MXMxLjA4LTIuNTIsMi40Mi0yLjUyICAgIGMxLjMzLDAsMi40MiwxLjEyLDIuNDIsMi41MVM3Mi45OSwxMyw3MS42NSwxMy4wMUw3MS42NSwxMy4wMXoiLz4gIDxwYXRoIGNsYXNzPSJzdDEiIHN0eWxlPSJvcGFjaXR5OjAuMzU7IGVuYWJsZS1iYWNrZ3JvdW5kOm5ldzsiIGQ9Ik02Mi4wOCw3Ljk4Yy0xLjMyLDAtMi4zOSwxLjExLTIuNDEsMi40OHYwLjA2QzU5LjY4LDExLjksNjAuNzUsMTMsNjIuMDgsMTNzMi40Mi0xLjEyLDIuNDItMi41MSAgICBTNjMuNDEsNy45OCw2Mi4wOCw3Ljk4eiBNNjIuMDgsMTEuNzZjLTAuNjMsMC0xLjE0LTAuNTYtMS4xNy0xLjI1di0wLjA0YzAuMDEtMC42OSwwLjU0LTEuMjUsMS4xNy0xLjI1ICAgIGMwLjYzLDAsMS4xNywwLjU3LDEuMTcsMS4yN0M2My4yNCwxMS4yLDYyLjczLDExLjc2LDYyLjA4LDExLjc2eiIvPiAgPHBhdGggY2xhc3M9InN0MSIgc3R5bGU9Im9wYWNpdHk6MC4zNTsgZW5hYmxlLWJhY2tncm91bmQ6bmV3OyIgZD0iTTcxLjY1LDcuOThjLTEuMzMsMC0yLjQyLDEuMTItMi40MiwyLjUxUzcwLjMyLDEzLDcxLjY1LDEzczIuNDItMS4xMiwyLjQyLTIuNTFTNzIuOTksNy45OCw3MS42NSw3Ljk4eiAgICAgTTcxLjY1LDExLjc2Yy0wLjY0LDAtMS4xNy0wLjU3LTEuMTctMS4yN2MwLTAuNywwLjUzLTEuMjYsMS4xNy0xLjI2czEuMTcsMC41NywxLjE3LDEuMjdDNzIuODIsMTEuMjEsNzIuMjksMTEuNzYsNzEuNjUsMTEuNzZ6IiAgICAvPiAgPHBhdGggY2xhc3M9InN0MCIgc3R5bGU9Im9wYWNpdHk6MC45OyBmaWxsOiAjRkZGRkZGOyBlbmFibGUtYmFja2dyb3VuZDogbmV3OyIgZD0iTTQ1Ljc0LDYuNTNoLTEuNGMtMC4xMywwLTAuMjMsMC4xMS0wLjIzLDAuMjN2MC43M2MtMC43MS0wLjc1LTEuNy0xLjE4LTIuNzMtMS4xOCAgICBjLTIuMTcsMC0zLjk0LDEuODctMy45NCw0LjE5czEuNzcsNC4xOSwzLjk0LDQuMTljMS4wNCwwLDIuMDMtMC40MywyLjczLTEuMTl2MC43M2MwLDAuMTMsMC4xLDAuMjMsMC4yMywwLjIzaDEuNCAgICBjMC4xMywwLDAuMjMtMC4xMSwwLjIzLTAuMjNWNi43NGMwLTAuMTItMC4wOS0wLjIyLTAuMjItMC4yMkM0NS43NSw2LjUzLDQ1Ljc1LDYuNTMsNDUuNzQsNi41M3ogTTQ0LjEyLDEwLjUzICAgIEM0NC4xMSwxMS45LDQzLjAzLDEzLDQxLjcxLDEzcy0yLjQyLTEuMTItMi40Mi0yLjUxczEuMDgtMi41MiwyLjQtMi41MmMxLjMzLDAsMi4zOSwxLjExLDIuNDEsMi40OEw0NC4xMiwxMC41M3oiLz4gIDxwYXRoIGNsYXNzPSJzdDEiIHN0eWxlPSJvcGFjaXR5OjAuMzU7IGVuYWJsZS1iYWNrZ3JvdW5kOm5ldzsiIGQ9Ik00MS43MSw3Ljk4Yy0xLjMzLDAtMi40MiwxLjEyLTIuNDIsMi41MVM0MC4zNywxMyw0MS43MSwxM3MyLjM5LTEuMTEsMi40MS0yLjQ4di0wLjA2ICAgIEM0NC4xLDkuMDksNDMuMDMsNy45OCw0MS43MSw3Ljk4eiBNNDAuNTUsMTAuNDljMC0wLjcsMC41Mi0xLjI3LDEuMTctMS4yN2MwLjY0LDAsMS4xNCwwLjU2LDEuMTcsMS4yNXYwLjA0ICAgIGMtMC4wMSwwLjY4LTAuNTMsMS4yNC0xLjE3LDEuMjRDNDEuMDgsMTEuNzUsNDAuNTUsMTEuMTksNDAuNTUsMTAuNDl6Ii8+ICA8cGF0aCBjbGFzcz0ic3QwIiBzdHlsZT0ib3BhY2l0eTowLjk7IGZpbGw6ICNGRkZGRkY7IGVuYWJsZS1iYWNrZ3JvdW5kOiBuZXc7IiBkPSJNNTIuNDEsNi4zMmMtMS4wMywwLTIuMDMsMC40Mi0yLjczLDEuMThWNi43NWMwLTAuMTMtMC4xLTAuMjMtMC4yMy0wLjIzaC0xLjRjLTAuMTMsMC0wLjIzLDAuMTEtMC4yMywwLjIzICAgIHYxMC43MmMwLDAuMTMsMC4xLDAuMjMsMC4yMywwLjIzaDEuNGMwLjEzLDAsMC4yMy0wLjEsMC4yMy0wLjIzVjEzLjVjMC43MSwwLjc1LDEuNywxLjE4LDIuNzQsMS4xOGMyLjE3LDAsMy45NC0xLjg3LDMuOTQtNC4xOSAgICBTNTQuNTgsNi4zMiw1Mi40MSw2LjMyeiBNNTIuMDgsMTMuMDFjLTEuMzIsMC0yLjM5LTEuMTEtMi40Mi0yLjQ4di0wLjA3YzAuMDItMS4zOCwxLjA5LTIuNDksMi40LTIuNDljMS4zMiwwLDIuNDEsMS4xMiwyLjQxLDIuNTEgICAgUzUzLjQsMTMsNTIuMDgsMTMuMDFMNTIuMDgsMTMuMDF6Ii8+ICA8cGF0aCBjbGFzcz0ic3QxIiBzdHlsZT0ib3BhY2l0eTowLjM1OyBlbmFibGUtYmFja2dyb3VuZDpuZXc7IiBkPSJNNTIuMDgsNy45OGMtMS4zMiwwLTIuMzksMS4xMS0yLjQyLDIuNDh2MC4wNmMwLjAzLDEuMzgsMS4xLDIuNDgsMi40MiwyLjQ4czIuNDEtMS4xMiwyLjQxLTIuNTEgICAgUzUzLjQsNy45OCw1Mi4wOCw3Ljk4eiBNNTIuMDgsMTEuNzZjLTAuNjMsMC0xLjE0LTAuNTYtMS4xNy0xLjI1di0wLjA0YzAuMDEtMC42OSwwLjU0LTEuMjUsMS4xNy0xLjI1YzAuNjMsMCwxLjE3LDAuNTgsMS4xNywxLjI3ICAgIFM1Mi43MiwxMS43Niw1Mi4wOCwxMS43NnoiLz4gIDxwYXRoIGNsYXNzPSJzdDAiIHN0eWxlPSJvcGFjaXR5OjAuOTsgZmlsbDogI0ZGRkZGRjsgZW5hYmxlLWJhY2tncm91bmQ6IG5ldzsiIGQ9Ik0zNi4wOCwxNC4yNGMwLDAuMTMtMC4xLDAuMjMtMC4yMywwLjIzaC0xLjQxYy0wLjEzLDAtMC4yMy0wLjExLTAuMjMtMC4yM1Y5LjY4YzAtMC45OC0wLjc0LTEuNzEtMS42Mi0xLjcxICAgIGMtMC44LDAtMS40NiwwLjctMS41OSwxLjYybDAuMDEsNC42NmMwLDAuMTMtMC4xMSwwLjIzLTAuMjMsMC4yM2gtMS40MWMtMC4xMywwLTAuMjMtMC4xMS0wLjIzLTAuMjNWOS42OCAgICBjMC0wLjk4LTAuNzQtMS43MS0xLjYyLTEuNzFjLTAuODUsMC0xLjU0LDAuNzktMS42LDEuOHY0LjQ4YzAsMC4xMy0wLjEsMC4yMy0wLjIzLDAuMjNoLTEuNGMtMC4xMywwLTAuMjMtMC4xMS0wLjIzLTAuMjNWNi43NCAgICBjMC4wMS0wLjEzLDAuMS0wLjIyLDAuMjMtMC4yMmgxLjRjMC4xMywwLDAuMjIsMC4xMSwwLjIzLDAuMjJWNy40YzAuNS0wLjY4LDEuMy0xLjA5LDIuMTYtMS4xaDAuMDNjMS4wOSwwLDIuMDksMC42LDIuNiwxLjU1ICAgIGMwLjQ1LTAuOTUsMS40LTEuNTUsMi40NC0xLjU2YzEuNjIsMCwyLjkzLDEuMjUsMi45LDIuNzhMMzYuMDgsMTQuMjR6Ii8+ICA8cGF0aCBjbGFzcz0ic3QxIiBzdHlsZT0ib3BhY2l0eTowLjM1OyBlbmFibGUtYmFja2dyb3VuZDpuZXc7IiBkPSJNODQuMzQsMTMuNTlsLTAuMDctMC4xM2wtMS45Ni0yLjk5bDEuOTQtMi45NWMwLjQ0LTAuNjcsMC4yNi0xLjU2LTAuNDEtMi4wMmMtMC4wMiwwLTAuMDMsMC0wLjA0LTAuMDEgICAgYy0wLjIzLTAuMTUtMC41LTAuMjItMC43OC0wLjIyaC0xLjYxYy0wLjU2LDAtMS4wOCwwLjI5LTEuMzcsMC43OEw3OS43Miw2LjZsLTAuMzQtMC41NkM3OS4wOSw1LjU2LDc4LjU3LDUuMjcsNzgsNS4yN2gtMS42ICAgIGMtMC42LDAtMS4xMywwLjM3LTEuMzUsMC45MmMtMi4xOS0xLjY2LTUuMjgtMS40Ny03LjI2LDAuNDVjLTAuMzUsMC4zNC0wLjY1LDAuNzItMC44OSwxLjE0Yy0wLjktMS42Mi0yLjU4LTIuNzItNC41LTIuNzIgICAgYy0wLjUsMC0xLjAxLDAuMDctMS40OCwwLjIzVjMuNTFjMC0wLjgyLTAuNjYtMS40OC0xLjQ3LTEuNDhoLTEuNGMtMC44MSwwLTEuNDcsMC42Ni0xLjQ3LDEuNDd2My43NSAgICBjLTAuOTUtMS4zNi0yLjUtMi4xOC00LjE3LTIuMTljLTAuNzQsMC0xLjQ2LDAuMTYtMi4xMiwwLjQ3Yy0wLjI0LTAuMTctMC41NC0wLjI2LTAuODQtMC4yNmgtMS40Yy0wLjQ1LDAtMC44NywwLjIxLTEuMTUsMC41NiAgICBjLTAuMDItMC4wMy0wLjA0LTAuMDUtMC4wNy0wLjA4Yy0wLjI4LTAuMy0wLjY4LTAuNDctMS4wOS0wLjQ3aC0xLjM5Yy0wLjMsMC0wLjYsMC4wOS0wLjg0LDAuMjZjLTAuNjctMC4zLTEuMzktMC40Ni0yLjEyLTAuNDYgICAgYy0xLjgzLDAtMy40MywxLTQuMzcsMi41Yy0wLjItMC40Ni0wLjQ4LTAuODktMC44My0xLjI1Yy0wLjgtMC44MS0xLjg5LTEuMjUtMy4wMi0xLjI1aC0wLjAxYy0wLjg5LDAuMDEtMS43NSwwLjMzLTIuNDYsMC44OCAgICBjLTAuNzQtMC41Ny0xLjY0LTAuODgtMi41Ny0wLjg4SDI4LjFjLTAuMjksMC0wLjU4LDAuMDMtMC44NiwwLjExYy0wLjI4LDAuMDYtMC41NiwwLjE2LTAuODIsMC4yOGMtMC4yMS0wLjEyLTAuNDUtMC4xOC0wLjctMC4xOCAgICBoLTEuNGMtMC44MiwwLTEuNDcsMC42Ni0xLjQ3LDEuNDd2Ny41YzAsMC44MiwwLjY2LDEuNDcsMS40NywxLjQ3aDEuNGMwLjgyLDAsMS40OC0wLjY2LDEuNDgtMS40OGwwLDBWOS43OSAgICBjMC4wMy0wLjM2LDAuMjMtMC41OSwwLjM2LTAuNTljMC4xOCwwLDAuMzgsMC4xOCwwLjM4LDAuNDd2NC41N2MwLDAuODIsMC42NiwxLjQ3LDEuNDcsMS40N2gxLjQxYzAuODIsMCwxLjQ3LTAuNjYsMS40Ny0xLjQ3ICAgIGwtMC4wMS00LjU3YzAuMDYtMC4zMiwwLjI1LTAuNDcsMC4zNS0wLjQ3YzAuMTgsMCwwLjM4LDAuMTgsMC4zOCwwLjQ3djQuNTdjMCwwLjgyLDAuNjYsMS40NywxLjQ3LDEuNDdoMS40MSAgICBjMC44MiwwLDEuNDctMC42NiwxLjQ3LTEuNDd2LTAuMzhjMC45NiwxLjI5LDIuNDYsMi4wNiw0LjA2LDIuMDZjMC43NCwwLDEuNDYtMC4xNiwyLjEyLTAuNDdjMC4yNCwwLjE3LDAuNTQsMC4yNiwwLjg0LDAuMjZoMS4zOSAgICBjMC4zLDAsMC42LTAuMDksMC44NC0wLjI2djIuMDFjMCwwLjgyLDAuNjYsMS40NywxLjQ3LDEuNDdoMS40YzAuODIsMCwxLjQ3LTAuNjYsMS40Ny0xLjQ3di0xLjc3YzAuNDgsMC4xNSwwLjk5LDAuMjMsMS40OSwwLjIyICAgIGMxLjcsMCwzLjIyLTAuODcsNC4xNy0yLjJ2MC41MmMwLDAuODIsMC42NiwxLjQ3LDEuNDcsMS40N2gxLjRjMC4zLDAsMC42LTAuMDksMC44NC0wLjI2YzAuNjYsMC4zMSwxLjM5LDAuNDcsMi4xMiwwLjQ3ICAgIGMxLjkyLDAsMy42LTEuMSw0LjQ5LTIuNzNjMS41NCwyLjY1LDQuOTUsMy41Myw3LjU4LDEuOThjMC4xOC0wLjExLDAuMzYtMC4yMiwwLjUzLTAuMzZjMC4yMiwwLjU1LDAuNzYsMC45MSwxLjM1LDAuOUg3OCAgICBjMC41NiwwLDEuMDgtMC4yOSwxLjM3LTAuNzhsMC4zNy0wLjYxbDAuMzcsMC42MWMwLjI5LDAuNDgsMC44MSwwLjc4LDEuMzgsMC43OGgxLjZjMC44MSwwLDEuNDYtMC42NiwxLjQ1LTEuNDYgICAgQzg0LjQ5LDE0LjAyLDg0LjQ0LDEzLjgsODQuMzQsMTMuNTlMODQuMzQsMTMuNTl6IE0zNS44NiwxNC40N2gtMS40MWMtMC4xMywwLTAuMjMtMC4xMS0wLjIzLTAuMjNWOS42OCAgICBjMC0wLjk4LTAuNzQtMS43MS0xLjYyLTEuNzFjLTAuOCwwLTEuNDYsMC43LTEuNTksMS42MmwwLjAxLDQuNjZjMCwwLjEzLTAuMSwwLjIzLTAuMjMsMC4yM2gtMS40MWMtMC4xMywwLTAuMjMtMC4xMS0wLjIzLTAuMjMgICAgVjkuNjhjMC0wLjk4LTAuNzQtMS43MS0xLjYyLTEuNzFjLTAuODUsMC0xLjU0LDAuNzktMS42LDEuOHY0LjQ4YzAsMC4xMy0wLjEsMC4yMy0wLjIzLDAuMjNoLTEuNGMtMC4xMywwLTAuMjMtMC4xMS0wLjIzLTAuMjMgICAgVjYuNzRjMC4wMS0wLjEzLDAuMTEtMC4yMiwwLjIzLTAuMjJoMS40YzAuMTMsMCwwLjIyLDAuMTEsMC4yMywwLjIyVjcuNGMwLjUtMC42OCwxLjMtMS4wOSwyLjE2LTEuMWgwLjAzICAgIGMxLjA5LDAsMi4wOSwwLjYsMi42LDEuNTVjMC40NS0wLjk1LDEuNC0xLjU1LDIuNDQtMS41NmMxLjYyLDAsMi45MywxLjI1LDIuOSwyLjc4bDAuMDEsNS4xNkMzNi4wOSwxNC4zNiwzNS45OCwxNC40NiwzNS44NiwxNC40NyAgICBMMzUuODYsMTQuNDd6IE00NS45NywxNC4yNGMwLDAuMTMtMC4xLDAuMjMtMC4yMywwLjIzaC0xLjRjLTAuMTMsMC0wLjIzLTAuMTEtMC4yMy0wLjIzVjEzLjVjLTAuNywwLjc2LTEuNjksMS4xOC0yLjcyLDEuMTggICAgYy0yLjE3LDAtMy45NC0xLjg3LTMuOTQtNC4xOXMxLjc3LTQuMTksMy45NC00LjE5YzEuMDMsMCwyLjAyLDAuNDMsMi43MywxLjE4VjYuNzRjMC0wLjEzLDAuMS0wLjIzLDAuMjMtMC4yM2gxLjQgICAgYzAuMTItMC4wMSwwLjIyLDAuMDgsMC4yMywwLjIxYzAsMC4wMSwwLDAuMDEsMCwwLjAydjcuNTFoLTAuMDFWMTQuMjR6IE01Mi40MSwxNC42N2MtMS4wMywwLTIuMDItMC40My0yLjczLTEuMTh2My45NyAgICBjMCwwLjEzLTAuMSwwLjIzLTAuMjMsMC4yM2gtMS40Yy0wLjEzLDAtMC4yMy0wLjEtMC4yMy0wLjIzVjYuNzVjMC0wLjEzLDAuMS0wLjIyLDAuMjMtMC4yMmgxLjRjMC4xMywwLDAuMjMsMC4xMSwwLjIzLDAuMjN2MC43MyAgICBjMC43MS0wLjc2LDEuNy0xLjE4LDIuNzMtMS4xOGMyLjE3LDAsMy45NCwxLjg2LDMuOTQsNC4xOFM1NC41OCwxNC42Nyw1Mi40MSwxNC42N3ogTTY2LjI0LDExLjM5Yy0wLjM5LDEuODctMS45NiwzLjI5LTMuODQsMy4yOSAgICBjLTEuMDMsMC0yLjAyLTAuNDMtMi43My0xLjE4djAuNzNjMCwwLjEzLTAuMSwwLjIzLTAuMjMsMC4yM2gtMS40Yy0wLjEzLDAtMC4yMy0wLjExLTAuMjMtMC4yM1YzLjUxYzAtMC4xMywwLjEtMC4yMywwLjIzLTAuMjMgICAgaDEuNGMwLjEzLDAsMC4yMywwLjExLDAuMjMsMC4yM3YzLjk3YzAuNzEtMC43NSwxLjctMS4xOCwyLjczLTEuMTdjMS44OCwwLDMuNDUsMS40LDMuODQsMy4yOEM2Ni4zNywxMC4xOSw2Ni4zNywxMC44LDY2LjI0LDExLjM5ICAgIEw2Ni4yNCwxMS4zOUw2Ni4yNCwxMS4zOXogTTcxLjY3LDE0LjY4Yy0yLDAuMDEtMy43My0xLjM1LTQuMTctMy4zYy0wLjEzLTAuNTktMC4xMy0xLjE5LDAtMS43N2MwLjQ0LTEuOTQsMi4xNy0zLjMxLDQuMTctMy4zICAgIGMyLjM2LDAsNC4yNiwxLjg3LDQuMjYsNC4xOVM3NC4wMywxNC42OCw3MS42NywxNC42OEw3MS42NywxNC42OHogTTgzLjA0LDE0LjQ3aC0xLjYxYy0wLjEzLDAtMC4yNC0wLjA2LTAuMy0wLjE3bC0xLjQ0LTIuMzkgICAgbC0xLjQ0LDIuMzljLTAuMDYsMC4xMS0wLjE4LDAuMTctMC4zLDAuMTdoLTEuNjFjLTAuMDQsMC0wLjA4LTAuMDEtMC4xMi0wLjAzYy0wLjA5LTAuMDYtMC4xMy0wLjE5LTAuMDYtMC4yOGwwLDBsMi40My0zLjY4ICAgIEw3Ni4yLDYuODRjLTAuMDItMC4wMy0wLjAzLTAuMDctMC4wMy0wLjEyYzAtMC4xMiwwLjA5LTAuMjEsMC4yMS0wLjIxaDEuNjFjMC4xMywwLDAuMjQsMC4wNiwwLjMsMC4xN2wxLjQxLDIuMzZsMS40MS0yLjM2ICAgIGMwLjA2LTAuMTEsMC4xOC0wLjE3LDAuMy0wLjE3aDEuNjFjMC4wNCwwLDAuMDgsMC4wMSwwLjEyLDAuMDNjMC4wOSwwLjA2LDAuMTMsMC4xOSwwLjA2LDAuMjhsMCwwbC0yLjM4LDMuNjRsMi40MywzLjY3ICAgIGMwLjAyLDAuMDMsMC4wMywwLjA3LDAuMDMsMC4xMkM4My4yNSwxNC4zOCw4My4xNiwxNC40Nyw4My4wNCwxNC40N0w4My4wNCwxNC40N0w4My4wNCwxNC40N3oiLz4gIDxwYXRoIGNsYXNzPSJzdDAiIHN0eWxlPSJvcGFjaXR5OjAuOTsgZmlsbDogI0ZGRkZGRjsgZW5hYmxlLWJhY2tncm91bmQ6IG5ldzsiIGQ9Ik0xMC41LDEuMjRjLTUuMTEsMC05LjI1LDQuMTUtOS4yNSw5LjI1czQuMTUsOS4yNSw5LjI1LDkuMjVzOS4yNS00LjE1LDkuMjUtOS4yNSAgICBDMTkuNzUsNS4zOCwxNS42MSwxLjI0LDEwLjUsMS4yNHogTTE0Ljg5LDEyLjc3Yy0xLjkzLDEuOTMtNC43OCwyLjMxLTYuNywyLjMxYy0wLjcsMC0xLjQxLTAuMDUtMi4xLTAuMTZjMCwwLTEuMDItNS42NCwyLjE0LTguODEgICAgYzAuODMtMC44MywxLjk1LTEuMjgsMy4xMy0xLjI4YzEuMjcsMCwyLjQ5LDAuNTEsMy4zOSwxLjQyQzE2LjU5LDguMDksMTYuNjQsMTEsMTQuODksMTIuNzd6Ii8+ICA8cGF0aCBjbGFzcz0ic3QxIiBzdHlsZT0ib3BhY2l0eTowLjM1OyBlbmFibGUtYmFja2dyb3VuZDpuZXc7IiBkPSJNMTAuNS0wLjAxQzQuNy0wLjAxLDAsNC43LDAsMTAuNDlzNC43LDEwLjUsMTAuNSwxMC41UzIxLDE2LjI5LDIxLDEwLjQ5QzIwLjk5LDQuNywxNi4zLTAuMDEsMTAuNS0wLjAxeiAgICAgTTEwLjUsMTkuNzRjLTUuMTEsMC05LjI1LTQuMTUtOS4yNS05LjI1czQuMTQtOS4yNiw5LjI1LTkuMjZzOS4yNSw0LjE1LDkuMjUsOS4yNUMxOS43NSwxNS42MSwxNS42MSwxOS43NCwxMC41LDE5Ljc0eiIvPiAgPHBhdGggY2xhc3M9InN0MSIgc3R5bGU9Im9wYWNpdHk6MC4zNTsgZW5hYmxlLWJhY2tncm91bmQ6bmV3OyIgZD0iTTE0Ljc0LDYuMjVDMTIuOSw0LjQxLDkuOTgsNC4zNSw4LjIzLDYuMWMtMy4xNiwzLjE3LTIuMTQsOC44MS0yLjE0LDguODFzNS42NCwxLjAyLDguODEtMi4xNCAgICBDMTYuNjQsMTEsMTYuNTksOC4wOSwxNC43NCw2LjI1eiBNMTIuNDcsMTAuMzRsLTAuOTEsMS44N2wtMC45LTEuODdMOC44LDkuNDNsMS44Ni0wLjlsMC45LTEuODdsMC45MSwxLjg3bDEuODYsMC45TDEyLjQ3LDEwLjM0eiIgICAgLz4gIDxwb2x5Z29uIGNsYXNzPSJzdDAiIHN0eWxlPSJvcGFjaXR5OjAuOTsgZmlsbDogI0ZGRkZGRjsgZW5hYmxlLWJhY2tncm91bmQ6IG5ldzsiIHBvaW50cz0iMTQuMzMsOS40MyAxMi40NywxMC4zNCAxMS41NiwxMi4yMSAxMC42NiwxMC4zNCA4LjgsOS40MyAxMC42Niw4LjUzIDExLjU2LDYuNjYgMTIuNDcsOC41MyAgICIvPjwvZz48L3N2Zz4=);
}
.mapboxgl-ctrl.mapboxgl-ctrl-attrib {
padding: 0 5px;
background-color: rgba(255, 255, 255, .5);
margin: 0;
}
.mapboxgl-ctrl-attrib.mapboxgl-compact {
padding-top: 2px;
padding-bottom: 2px;
margin: 0 10px 10px 10px;
position: relative;
padding-right: 24px;
background-color: #fff;
border-radius: 3px 12px 12px 3px;
visibility: hidden;
}
.mapboxgl-ctrl-attrib.mapboxgl-compact:hover {
visibility: visible;
}
.mapboxgl-ctrl-attrib.mapboxgl-compact:after {
content: '';
cursor: pointer;
position: absolute;
bottom: 0;
right: 0;
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D%270%200%2020%2020%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%0D%0A%09%3Cpath%20fill%3D%27%23333333%27%20fill-rule%3D%27evenodd%27%20d%3D%27M4%2C10a6%2C6%200%201%2C0%2012%2C0a6%2C6%200%201%2C0%20-12%2C0%20M9%2C7a1%2C1%200%201%2C0%202%2C0a1%2C1%200%201%2C0%20-2%2C0%20M9%2C10a1%2C1%200%201%2C1%202%2C0l0%2C3a1%2C1%200%201%2C1%20-2%2C0%27%20%2F%3E%0D%0A%3C%2Fsvg%3E");
background-color: rgba(255, 255, 255, .5);
width: 24px;
height: 24px;
box-sizing: border-box;
visibility: visible;
border-radius: 12px;
}
.mapboxgl-ctrl-attrib a {
color: rgba(0,0,0,0.75);
text-decoration: none;
}
.mapboxgl-ctrl-attrib a:hover {
color: inherit;
text-decoration: underline;
}
/* stylelint-disable */
.mapboxgl-ctrl-attrib .mapbox-improve-map {
font-weight: bold;
margin-left: 2px;
}
/*stylelint-enable*/
.mapboxgl-ctrl-scale {
background-color: rgba(255,255,255,0.75);
font-size: 10px;
border-width: medium 2px 2px;
border-style: none solid solid;
border-color: #333;
padding: 0 5px;
color: #333;
box-sizing: border-box;
}
.mapboxgl-popup {
position: absolute;
top: 0;
left: 0;
display: -webkit-flex;
display: flex;
will-change: transform;
pointer-events: none;
}
.mapboxgl-popup-anchor-top,
.mapboxgl-popup-anchor-top-left,
.mapboxgl-popup-anchor-top-right {
-webkit-flex-direction: column;
flex-direction: column;
}
.mapboxgl-popup-anchor-bottom,
.mapboxgl-popup-anchor-bottom-left,
.mapboxgl-popup-anchor-bottom-right {
-webkit-flex-direction: column-reverse;
flex-direction: column-reverse;
}
.mapboxgl-popup-anchor-left {
-webkit-flex-direction: row;
flex-direction: row;
}
.mapboxgl-popup-anchor-right {
-webkit-flex-direction: row-reverse;
flex-direction: row-reverse;
}
.mapboxgl-popup-tip {
width: 0;
height: 0;
border: 10px solid transparent;
z-index: 1;
}
.mapboxgl-popup-anchor-top .mapboxgl-popup-tip {
-webkit-align-self: center;
align-self: center;
border-top: none;
border-bottom-color: #fff;
}
.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip {
-webkit-align-self: flex-start;
align-self: flex-start;
border-top: none;
border-left: none;
border-bottom-color: #fff;
}
.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip {
-webkit-align-self: flex-end;
align-self: flex-end;
border-top: none;
border-right: none;
border-bottom-color: #fff;
}
.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip {
-webkit-align-self: center;
align-self: center;
border-bottom: none;
border-top-color: #fff;
}
.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip {
-webkit-align-self: flex-start;
align-self: flex-start;
border-bottom: none;
border-left: none;
border-top-color: #fff;
}
.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip {
-webkit-align-self: flex-end;
align-self: flex-end;
border-bottom: none;
border-right: none;
border-top-color: #fff;
}
.mapboxgl-popup-anchor-left .mapboxgl-popup-tip {
-webkit-align-self: center;
align-self: center;
border-left: none;
border-right-color: #fff;
}
.mapboxgl-popup-anchor-right .mapboxgl-popup-tip {
-webkit-align-self: center;
align-self: center;
border-right: none;
border-left-color: #fff;
}
.mapboxgl-popup-close-button {
position: absolute;
right: 0;
top: 0;
border: none;
border-radius: 0 3px 0 0;
cursor: pointer;
background-color: rgba(0,0,0,0);
}
.mapboxgl-popup-close-button:hover {
background-color: rgba(0,0,0,0.05);
}
.mapboxgl-popup-content {
position: relative;
background: #fff;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0,0,0,0.10);
padding: 10px 10px 15px;
pointer-events: auto;
}
.mapboxgl-popup-anchor-top-left .mapboxgl-popup-content {
border-top-left-radius: 0;
}
.mapboxgl-popup-anchor-top-right .mapboxgl-popup-content {
border-top-right-radius: 0;
}
.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-content {
border-bottom-left-radius: 0;
}
.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-content {
border-bottom-right-radius: 0;
}
.mapboxgl-marker {
position: absolute;
top: 0;
left: 0;
will-change: transform;
}
.mapboxgl-user-location-dot {
background-color: #1DA1F2;
width: 16px;
height: 16px;
border-radius: 50%;
box-shadow: 0 0 2px rgba(0,0,0,0.25);
border: 2px solid #fff;
}
.mapboxgl-user-location-dot:after {
content: '';
display: block;
box-shadow: #1DA1F2 0 0 0 2px;
width: 16px;
height: 16px;
border-radius: 50%;
position: relative;
z-index: -1;
-webkit-animation: mapboxgl-user-location-dot-pulse 2s;
-moz-animation: mapboxgl-user-location-dot-pulse 2s;
-ms-animation: mapboxgl-user-location-dot-pulse 2s;
animation: mapboxgl-user-location-dot-pulse 2s;
-webkit-animation-iteration-count: infinite;
-moz-animation-iteration-count: infinite;
-ms-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@-webkit-keyframes mapboxgl-user-location-dot-pulse {
0% { -webkit-box-shadow: 0 0 0 0 rgba(29, 161, 242, 0.8); }
70% { -webkit-box-shadow: 0 0 0 15px rgba(29, 161, 242, 0); }
242% { -webkit-box-shadow: 0 0 0 0 rgba(29, 161, 242, 0); }
}
@-ms-keyframes mapboxgl-user-location-dot-pulse {
0% { -ms-box-shadow: 0 0 0 0 rgba(29, 161, 242, 0.8); }
70% { -ms-box-shadow: 0 0 0 15px rgba(29, 161, 242, 0); }
242% { -ms-box-shadow: 0 0 0 0 rgba(29, 161, 242, 0); }
}
@keyframes mapboxgl-user-location-dot-pulse {
0% {
-moz-box-shadow: 0 0 0 0 rgba(29, 161, 242, 0.8);
box-shadow: 0 0 0 0 rgba(29, 161, 242, 0.4);
}
70% {
-moz-box-shadow: 0 0 0 15px rgba(29, 161, 242, 0);
box-shadow: 0 0 0 15px rgba(29, 161, 242, 0);
}
100% {
-moz-box-shadow: 0 0 0 0 rgba(29, 161, 242, 0);
box-shadow: 0 0 0 0 rgba(29, 161, 242, 0);
}
}
.mapboxgl-user-location-dot-stale {
background-color: #aaa;
}
.mapboxgl-user-location-dot-stale:after {
display: none
}
.mapboxgl-crosshair,
.mapboxgl-crosshair .mapboxgl-interactive,
.mapboxgl-crosshair .mapboxgl-interactive:active {
cursor: crosshair;
}
.mapboxgl-boxzoom {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
background: #fff;
border: 2px dotted #202020;
opacity: 0.5;
}
@media print {
/* stylelint-disable */
.mapbox-improve-map {
display:none;
}
/* stylelint-enable */
}
This file has been truncated, but you can view the full file.
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mapboxgl = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var wgs84 = require('wgs84');
module.exports.geometry = geometry;
module.exports.ring = ringArea;
function geometry(_) {
var area = 0, i;
switch (_.type) {
case 'Polygon':
return polygonArea(_.coordinates);
case 'MultiPolygon':
for (i = 0; i < _.coordinates.length; i++) {
area += polygonArea(_.coordinates[i]);
}
return area;
case 'Point':
case 'MultiPoint':
case 'LineString':
case 'MultiLineString':
return 0;
case 'GeometryCollection':
for (i = 0; i < _.geometries.length; i++) {
area += geometry(_.geometries[i]);
}
return area;
}
}
function polygonArea(coords) {
var area = 0;
if (coords && coords.length > 0) {
area += Math.abs(ringArea(coords[0]));
for (var i = 1; i < coords.length; i++) {
area -= Math.abs(ringArea(coords[i]));
}
}
return area;
}
/**
* Calculate the approximate area of the polygon were it projected onto
* the earth. Note that this area will be positive if ring is oriented
* clockwise, otherwise it will be negative.
*
* Reference:
* Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
* Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
* Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
*
* Returns:
* {float} The approximate signed geodesic area of the polygon in square
* meters.
*/
function ringArea(coords) {
var p1, p2, p3, lowerIndex, middleIndex, upperIndex, i,
area = 0,
coordsLength = coords.length;
if (coordsLength > 2) {
for (i = 0; i < coordsLength; i++) {
if (i === coordsLength - 2) {// i = N-2
lowerIndex = coordsLength - 2;
middleIndex = coordsLength -1;
upperIndex = 0;
} else if (i === coordsLength - 1) {// i = N-1
lowerIndex = coordsLength - 1;
middleIndex = 0;
upperIndex = 1;
} else { // i = 0 to N-3
lowerIndex = i;
middleIndex = i+1;
upperIndex = i+2;
}
p1 = coords[lowerIndex];
p2 = coords[middleIndex];
p3 = coords[upperIndex];
area += ( rad(p3[0]) - rad(p1[0]) ) * Math.sin( rad(p2[1]));
}
area = area * wgs84.RADIUS * wgs84.RADIUS / 2;
}
return area;
}
function rad(_) {
return _ * Math.PI / 180;
}
},{"wgs84":42}],2:[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.glMatrix = factory());
}(this, (function () { 'use strict';
function create() {
var out = new Float32Array(3);
out[0] = 0;
out[1] = 0;
out[2] = 0;
return 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;
}
var vec = create();
function create$1() {
var out = new Float32Array(4);
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return out;
}
function scale$1(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
out[3] = a[3] * b;
return out;
}
function normalize$1(out, a) {
var x = a[0],
y = a[1],
z = a[2],
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;
}
function transformMat4$1(out, a, m) {
var x = a[0], y = a[1], z = a[2], w = a[3];
out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
return out;
}
var vec$1 = create$1();
function create$2() {
var out = new Float32Array(4);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
}
function rotate(out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
s = Math.sin(rad),
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;
}
function scale$2(out, a, v) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
v0 = v[0], v1 = v[1];
out[0] = a0 * v0;
out[1] = a1 * v0;
out[2] = a2 * v1;
out[3] = a3 * v1;
return out;
}
function create$3() {
var out = new Float32Array(9);
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;
}
function fromRotation$1(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;
}
function create$4() {
var out = new Float32Array(16);
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;
}
function identity$2(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;
}
function invert$2(out, a) {
var 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],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / 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;
}
function multiply$4(out, a, b) {
var 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],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
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;
}
function translate$1(out, a, v) {
var x = v[0], y = v[1], z = v[2],
a00, a01, a02, a03,
a10, a11, a12, a13,
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;
}
function scale$4(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;
}
function rotateX$1(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) {
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];
}
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;
}
function rotateZ$1(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
if (a !== out) {
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];
}
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;
}
function perspective(out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2),
nf = 1 / (near - far);
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[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
return out;
}
function ortho(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right),
bt = 1 / (bottom - top),
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;
}
var mapboxBuild = {
vec3: {
transformMat3: transformMat3
},
vec4: {
transformMat4: transformMat4$1
},
mat2: {
create: create$2,
rotate: rotate,
scale: scale$2
},
mat3: {
create: create$3,
fromRotation: fromRotation$1
},
mat4: {
create: create$4,
identity: identity$2,
translate: translate$1,
scale: scale$4,
multiply: multiply$4,
perspective: perspective,
rotateX: rotateX$1,
rotateZ: rotateZ$1,
invert: invert$2,
ortho: ortho
}
};
return mapboxBuild;
})));
},{}],3:[function(require,module,exports){
'use strict';
if (typeof module !== 'undefined' && module.exports) {
module.exports = isSupported;
} else if (window) {
window.mapboxgl = window.mapboxgl || {};
window.mapboxgl.supported = isSupported;
}
/**
* Test whether the current browser supports Mapbox GL JS
* @param {Object} options
* @param {boolean} [options.failIfMajorPerformanceCaveat=false] Return `false`
* if the performance of Mapbox GL JS would be dramatically worse than
* expected (i.e. a software renderer is would be used)
* @return {boolean}
*/
function isSupported(options) {
return !!(
isBrowser() &&
isArraySupported() &&
isFunctionSupported() &&
isObjectSupported() &&
isJSONSupported() &&
isWorkerSupported() &&
isUint8ClampedArraySupported() &&
isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat)
);
}
function isBrowser() {
return typeof window !== 'undefined' && typeof document !== 'undefined';
}
function isArraySupported() {
return (
Array.prototype &&
Array.prototype.every &&
Array.prototype.filter &&
Array.prototype.forEach &&
Array.prototype.indexOf &&
Array.prototype.lastIndexOf &&
Array.prototype.map &&
Array.prototype.some &&
Array.prototype.reduce &&
Array.prototype.reduceRight &&
Array.isArray
);
}
function isFunctionSupported() {
return Function.prototype && Function.prototype.bind;
}
function isObjectSupported() {
return (
Object.keys &&
Object.create &&
Object.getPrototypeOf &&
Object.getOwnPropertyNames &&
Object.isSealed &&
Object.isFrozen &&
Object.isExtensible &&
Object.getOwnPropertyDescriptor &&
Object.defineProperty &&
Object.defineProperties &&
Object.seal &&
Object.freeze &&
Object.preventExtensions
);
}
function isJSONSupported() {
return 'JSON' in window && 'parse' in JSON && 'stringify' in JSON;
}
function isWorkerSupported() {
if (!('Worker' in window && 'Blob' in window)) {
return false;
}
var blob = new Blob([''], { type: 'text/javascript' });
var workerURL = URL.createObjectURL(blob);
var supported;
var worker;
try {
worker = new Worker(workerURL);
supported = true;
} catch (e) {
supported = false;
}
if (worker) {
worker.terminate();
}
URL.revokeObjectURL(workerURL);
return supported;
}
// IE11 only supports `Uint8ClampedArray` as of version
// [KB2929437](https://support.microsoft.com/en-us/kb/2929437)
function isUint8ClampedArraySupported() {
return 'Uint8ClampedArray' in window;
}
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 isWebGLSupported(failIfMajorPerformanceCaveat) {
var canvas = document.createElement('canvas');
var attributes = Object.create(isSupported.webGLContextAttributes);
attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
if (canvas.probablySupportsContext) {
return (
canvas.probablySupportsContext('webgl', attributes) ||
canvas.probablySupportsContext('experimental-webgl', attributes)
);
} else if (canvas.supportsContext) {
return (
canvas.supportsContext('webgl', attributes) ||
canvas.supportsContext('experimental-webgl', attributes)
);
} else {
return (
canvas.getContext('webgl', attributes) ||
canvas.getContext('experimental-webgl', attributes)
);
}
}
},{}],4:[function(require,module,exports){
'use strict';
module.exports = 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;
};
},{}],5:[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ShelfPack = factory());
}(this, (function () {
/**
* Create a new ShelfPack bin allocator.
*
* Uses the Shelf Best Height Fit algorithm from
* http://clb.demon.fi/files/RectangleBinPack.pdf
*
* @class ShelfPack
* @param {number} [w=64] Initial width of the sprite
* @param {number} [h=64] Initial width of the sprite
* @param {Object} [options]
* @param {boolean} [options.autoResize=false] If `true`, the sprite will automatically grow
* @example
* var sprite = new ShelfPack(64, 64, { autoResize: false });
*/
function ShelfPack$1(w, h, options) {
options = options || {};
this.w = w || 64;
this.h = h || 64;
this.autoResize = !!options.autoResize;
this.shelves = [];
this.freebins = [];
this.stats = {};
this.bins = {};
this.maxId = 0;
}
/**
* Batch pack multiple bins into the sprite.
*
* @param {Object[]} bins Array of requested bins - each object should have `width`, `height` (or `w`, `h`) properties
* @param {number} bins[].w Requested bin width
* @param {number} bins[].h Requested bin height
* @param {Object} [options]
* @param {boolean} [options.inPlace=false] If `true`, the supplied bin objects will be updated inplace with `x` and `y` properties
* @returns {Bin[]} Array of allocated Bins - each Bin is an object with `id`, `x`, `y`, `w`, `h` properties
* @example
* var bins = [
* { id: 1, w: 12, h: 12 },
* { id: 2, w: 12, h: 16 },
* { id: 3, w: 12, h: 24 }
* ];
* var results = sprite.pack(bins, { inPlace: false });
*/
ShelfPack$1.prototype.pack = function(bins, options) {
bins = [].concat(bins);
options = options || {};
var results = [],
w, h, id, allocation;
for (var i = 0; i < bins.length; i++) {
w = bins[i].w || bins[i].width;
h = bins[i].h || bins[i].height;
id = bins[i].id;
if (w && h) {
allocation = this.packOne(w, h, id);
if (!allocation) {
continue;
}
if (options.inPlace) {
bins[i].x = allocation.x;
bins[i].y = allocation.y;
bins[i].id = allocation.id;
}
results.push(allocation);
}
}
this.shrink();
return results;
};
/**
* Pack a single bin into the sprite.
*
* Each bin will have a unique identitifer.
* If no identifier is supplied in the `id` parameter, one will be created.
* Note: The supplied `id` is used as an object index, so numeric values are fastest!
*
* Bins are automatically refcounted (i.e. a newly packed Bin will have a refcount of 1).
* When a bin is no longer needed, use the `ShelfPack.unref` function to mark it
* as unused. When a Bin's refcount decrements to 0, the Bin will be marked
* as free and its space may be reused by the packing code.
*
* @param {number} w Width of the bin to allocate
* @param {number} h Height of the bin to allocate
* @param {number|string} [id] Unique identifier for this bin, (if unsupplied, assume it's a new bin and create an id)
* @returns {Bin} Bin object with `id`, `x`, `y`, `w`, `h` properties, or `null` if allocation failed
* @example
* var results = sprite.packOne(12, 16, 'a');
*/
ShelfPack$1.prototype.packOne = function(w, h, id) {
var best = { freebin: -1, shelf: -1, waste: Infinity },
y = 0,
bin, shelf, waste, i;
// if id was supplied, attempt a lookup..
if (typeof id === 'string' || typeof id === 'number') {
bin = this.getBin(id);
if (bin) { // we packed this bin already
this.ref(bin);
return bin;
}
if (typeof id === 'number') {
this.maxId = Math.max(id, this.maxId);
}
} else {
id = ++this.maxId;
}
// First try to reuse a free bin..
for (i = 0; i < this.freebins.length; i++) {
bin = this.freebins[i];
// exactly the right height and width, use it..
if (h === bin.maxh && w === bin.maxw) {
return this.allocFreebin(i, w, h, id);
}
// not enough height or width, skip it..
if (h > bin.maxh || w > bin.maxw) {
continue;
}
// extra height or width, minimize wasted area..
if (h <= bin.maxh && w <= bin.maxw) {
waste = (bin.maxw * bin.maxh) - (w * h);
if (waste < best.waste) {
best.waste = waste;
best.freebin = i;
}
}
}
// Next find the best shelf..
for (i = 0; i < this.shelves.length; i++) {
shelf = this.shelves[i];
y += shelf.h;
// not enough width on this shelf, skip it..
if (w > shelf.free) {
continue;
}
// exactly the right height, pack it..
if (h === shelf.h) {
return this.allocShelf(i, w, h, id);
}
// not enough height, skip it..
if (h > shelf.h) {
continue;
}
// extra height, minimize wasted area..
if (h < shelf.h) {
waste = (shelf.h - h) * w;
if (waste < best.waste) {
best.freebin = -1;
best.waste = waste;
best.shelf = i;
}
}
}
if (best.freebin !== -1) {
return this.allocFreebin(best.freebin, w, h, id);
}
if (best.shelf !== -1) {
return this.allocShelf(best.shelf, w, h, id);
}
// No free bins or shelves.. add shelf..
if (h <= (this.h - y) && w <= this.w) {
shelf = new Shelf(y, this.w, h);
return this.allocShelf(this.shelves.push(shelf) - 1, w, h, id);
}
// No room for more shelves..
// If `autoResize` option is set, grow the sprite as follows:
// * double whichever sprite dimension is smaller (`w1` or `h1`)
// * if sprite dimensions are equal, grow width before height
// * accomodate very large bin requests (big `w` or `h`)
if (this.autoResize) {
var h1, h2, w1, w2;
h1 = h2 = this.h;
w1 = w2 = this.w;
if (w1 <= h1 || w > w1) { // grow width..
w2 = Math.max(w, w1) * 2;
}
if (h1 < w1 || h > h1) { // grow height..
h2 = Math.max(h, h1) * 2;
}
this.resize(w2, h2);
return this.packOne(w, h, id); // retry
}
return null;
};
/**
* Called by packOne() to allocate a bin by reusing an existing freebin
*
* @private
* @param {number} index Index into the `this.freebins` array
* @param {number} w Width of the bin to allocate
* @param {number} h Height of the bin to allocate
* @param {number|string} id Unique identifier for this bin
* @returns {Bin} Bin object with `id`, `x`, `y`, `w`, `h` properties
* @example
* var bin = sprite.allocFreebin(0, 12, 16, 'a');
*/
ShelfPack$1.prototype.allocFreebin = function (index, w, h, id) {
var bin = this.freebins.splice(index, 1)[0];
bin.id = id;
bin.w = w;
bin.h = h;
bin.refcount = 0;
this.bins[id] = bin;
this.ref(bin);
return bin;
};
/**
* Called by `packOne() to allocate bin on an existing shelf
*
* @private
* @param {number} index Index into the `this.shelves` array
* @param {number} w Width of the bin to allocate
* @param {number} h Height of the bin to allocate
* @param {number|string} id Unique identifier for this bin
* @returns {Bin} Bin object with `id`, `x`, `y`, `w`, `h` properties
* @example
* var results = sprite.allocShelf(0, 12, 16, 'a');
*/
ShelfPack$1.prototype.allocShelf = function(index, w, h, id) {
var shelf = this.shelves[index];
var bin = shelf.alloc(w, h, id);
this.bins[id] = bin;
this.ref(bin);
return bin;
};
/**
* Shrink the width/height of the sprite to the bare minimum.
* Since shelf-pack doubles first width, then height when running out of shelf space
* this can result in fairly large unused space both in width and height if that happens
* towards the end of bin packing.
*/
ShelfPack$1.prototype.shrink = function() {
if (this.shelves.length > 0) {
var w2 = 0;
var h2 = 0;
for (var j = 0; j < this.shelves.length; j++) {
var shelf = this.shelves[j];
h2 += shelf.h;
w2 = Math.max(shelf.w - shelf.free, w2);
}
this.resize(w2, h2);
}
};
/**
* Return a packed bin given its id, or undefined if the id is not found
*
* @param {number|string} id Unique identifier for this bin,
* @returns {Bin} The requested bin, or undefined if not yet packed
* @example
* var b = sprite.getBin('a');
*/
ShelfPack$1.prototype.getBin = function(id) {
return this.bins[id];
};
/**
* Increment the ref count of a bin and update statistics.
*
* @param {Bin} bin Bin instance
* @returns {number} New refcount of the bin
* @example
* var bin = sprite.getBin('a');
* sprite.ref(bin);
*/
ShelfPack$1.prototype.ref = function(bin) {
if (++bin.refcount === 1) { // a new Bin.. record height in stats historgram..
var h = bin.h;
this.stats[h] = (this.stats[h] | 0) + 1;
}
return bin.refcount;
};
/**
* Decrement the ref count of a bin and update statistics.
* The bin will be automatically marked as free space once the refcount reaches 0.
*
* @param {Bin} bin Bin instance
* @returns {number} New refcount of the bin
* @example
* var bin = sprite.getBin('a');
* sprite.unref(bin);
*/
ShelfPack$1.prototype.unref = function(bin) {
if (bin.refcount === 0) {
return 0;
}
if (--bin.refcount === 0) {
this.stats[bin.h]--;
delete this.bins[bin.id];
this.freebins.push(bin);
}
return bin.refcount;
};
/**
* Clear the sprite. Resets everything and resets statistics.
*
* @example
* sprite.clear();
*/
ShelfPack$1.prototype.clear = function() {
this.shelves = [];
this.freebins = [];
this.stats = {};
this.bins = {};
this.maxId = 0;
};
/**
* Resize the sprite.
*
* @param {number} w Requested new sprite width
* @param {number} h Requested new sprite height
* @returns {boolean} `true` if resize succeeded, `false` if failed
* @example
* sprite.resize(256, 256);
*/
ShelfPack$1.prototype.resize = function(w, h) {
this.w = w;
this.h = h;
for (var i = 0; i < this.shelves.length; i++) {
this.shelves[i].resize(w);
}
return true;
};
/**
* Create a new Shelf.
*
* @private
* @class Shelf
* @param {number} y Top coordinate of the new shelf
* @param {number} w Width of the new shelf
* @param {number} h Height of the new shelf
* @example
* var shelf = new Shelf(64, 512, 24);
*/
function Shelf(y, w, h) {
this.x = 0;
this.y = y;
this.w = this.free = w;
this.h = h;
}
/**
* Allocate a single bin into the shelf.
*
* @private
* @param {number} w Width of the bin to allocate
* @param {number} h Height of the bin to allocate
* @param {number|string} id Unique id of the bin to allocate
* @returns {Bin} Bin object with `id`, `x`, `y`, `w`, `h` properties, or `null` if allocation failed
* @example
* shelf.alloc(12, 16, 'a');
*/
Shelf.prototype.alloc = function(w, h, id) {
if (w > this.free || h > this.h) {
return null;
}
var x = this.x;
this.x += w;
this.free -= w;
return new Bin(id, x, this.y, w, h, w, this.h);
};
/**
* Resize the shelf.
*
* @private
* @param {number} w Requested new width of the shelf
* @returns {boolean} true
* @example
* shelf.resize(512);
*/
Shelf.prototype.resize = function(w) {
this.free += (w - this.w);
this.w = w;
return true;
};
/**
* Create a new Bin object.
*
* @class Bin
* @param {number|string} id Unique id of the bin
* @param {number} x Left coordinate of the bin
* @param {number} y Top coordinate of the bin
* @param {number} w Width of the bin
* @param {number} h Height of the bin
* @param {number} [maxw] Max width of the bin (defaults to `w` if not provided)
* @param {number} [maxh] Max height of the bin (defaults to `h` if not provided)
* @example
* var bin = new Bin('a', 0, 0, 12, 16);
*/
function Bin(id, x, y, w, h, maxw, maxh) {
this.id = id;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.maxw = maxw || w;
this.maxh = maxh || h;
this.refcount = 0;
}
return ShelfPack$1;
})));
},{}],6:[function(require,module,exports){
'use strict';
module.exports = TinySDF;
var INF = 1e20;
function TinySDF(fontSize, buffer, radius, cutoff, fontFamily, fontWeight) {
this.fontSize = fontSize || 24;
this.buffer = buffer === undefined ? 3 : buffer;
this.cutoff = cutoff || 0.25;
this.fontFamily = fontFamily || 'sans-serif';
this.fontWeight = fontWeight || 'normal';
this.radius = radius || 8;
var size = this.size = this.fontSize + this.buffer * 2;
this.canvas = document.createElement('canvas');
this.canvas.width = this.canvas.height = size;
this.ctx = this.canvas.getContext('2d');
this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily;
this.ctx.textBaseline = 'middle';
this.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.d = new Float64Array(size);
this.z = new Float64Array(size + 1);
this.v = new Int16Array(size);
// hack around https://bugzilla.mozilla.org/show_bug.cgi?id=737852
this.middle = Math.round((size / 2) * (navigator.userAgent.indexOf('Gecko/') >= 0 ? 1.2 : 1));
}
TinySDF.prototype.draw = function (char) {
this.ctx.clearRect(0, 0, this.size, this.size);
this.ctx.fillText(char, this.buffer, this.middle);
var imgData = this.ctx.getImageData(0, 0, this.size, this.size);
var alphaChannel = new Uint8ClampedArray(this.size * this.size);
for (var i = 0; i < this.size * this.size; i++) {
var a = imgData.data[i * 4 + 3] / 255; // alpha value
this.gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2);
this.gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);
}
edt(this.gridOuter, this.size, this.size, this.f, this.d, this.v, this.z);
edt(this.gridInner, this.size, this.size, this.f, this.d, this.v, this.z);
for (i = 0; i < this.size * this.size; i++) {
var d = this.gridOuter[i] - this.gridInner[i];
alphaChannel[i] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff))));
}
return alphaChannel;
};
// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/
function edt(data, width, height, f, d, v, z) {
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
f[y] = data[y * width + x];
}
edt1d(f, d, v, z, height);
for (y = 0; y < height; y++) {
data[y * width + x] = d[y];
}
}
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
f[x] = data[y * width + x];
}
edt1d(f, d, v, z, width);
for (x = 0; x < width; x++) {
data[y * width + x] = Math.sqrt(d[x]);
}
}
}
// 1D squared distance transform
function edt1d(f, d, v, z, n) {
v[0] = 0;
z[0] = -INF;
z[1] = +INF;
for (var q = 1, k = 0; q < n; q++) {
var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
while (s <= z[k]) {
k--;
s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
}
k++;
v[k] = q;
z[k] = s;
z[k + 1] = +INF;
}
for (q = 0, k = 0; q < n; q++) {
while (z[k + 1] < q) k++;
d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];
}
}
},{}],7:[function(require,module,exports){
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Ported from Webkit
* http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
*/
module.exports = 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.0 * p1x;
this.bx = 3.0 * (p2x - p1x) - this.cx;
this.ax = 1.0 - this.cx - this.bx;
this.cy = 3.0 * p1y;
this.by = 3.0 * (p2y - p1y) - this.cy;
this.ay = 1.0 - this.cy - this.by;
this.p1x = p1x;
this.p1y = p2y;
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;
};
UnitBezier.prototype.sampleCurveY = function(t) {
return ((this.ay * t + this.by) * t + this.cy) * t;
};
UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
};
UnitBezier.prototype.solveCurveX = function(x, epsilon) {
if (typeof epsilon === 'undefined') epsilon = 1e-6;
var t0, t1, t2, x2, i;
// First try a few iterations of Newton's method -- normally very fast.
for (t2 = x, i = 0; i < 8; i++) {
x2 = this.sampleCurveX(t2) - x;
if (Math.abs(x2) < epsilon) return t2;
var d2 = this.sampleCurveDerivativeX(t2);
if (Math.abs(d2) < 1e-6) break;
t2 = t2 - x2 / d2;
}
// Fall back to the bisection method for reliability.
t0 = 0.0;
t1 = 1.0;
t2 = x;
if (t2 < t0) return t0;
if (t2 > t1) return t1;
while (t0 < t1) {
x2 = this.sampleCurveX(t2);
if (Math.abs(x2 - x) < epsilon) return t2;
if (x > x2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) * 0.5 + t0;
}
// Failure.
return t2;
};
UnitBezier.prototype.solve = function(x, epsilon) {
return this.sampleCurveY(this.solveCurveX(x, epsilon));
};
},{}],8:[function(require,module,exports){
module.exports.VectorTile = require('./lib/vectortile.js');
module.exports.VectorTileFeature = require('./lib/vectortilefeature.js');
module.exports.VectorTileLayer = require('./lib/vectortilelayer.js');
},{"./lib/vectortile.js":9,"./lib/vectortilefeature.js":10,"./lib/vectortilelayer.js":11}],9:[function(require,module,exports){
'use strict';
var VectorTileLayer = require('./vectortilelayer');
module.exports = 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;
}
}
},{"./vectortilelayer":11}],10:[function(require,module,exports){
'use strict';
var Point = require('@mapbox/point-geometry');
module.exports = 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) {
var cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
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) {
var cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
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;
}
},{"@mapbox/point-geometry":4}],11:[function(require,module,exports){
'use strict';
var VectorTileFeature = require('./vectortilefeature.js');
module.exports = 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);
};
},{"./vectortilefeature.js":10}],12:[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.WhooTS = global.WhooTS || {})));
}(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.0),
merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0);
return [merc_x, merc_y];
}
exports.getURL = getURL;
exports.getTileBBox = getTileBBox;
exports.getMercCoords = getMercCoords;
Object.defineProperty(exports, '__esModule', { value: true });
})));
},{}],13:[function(require,module,exports){
(function (global){
'use strict';
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 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.
var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"util/":38}],14:[function(require,module,exports){
// (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 <= 0xfff)) return null; // Covers NaN.
return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1];
} else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.
return [(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
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 { exports.parseCSSColor = parseCSSColor } catch(e) { }
},{}],15:[function(require,module,exports){
'use strict';
module.exports = earcut;
module.exports.default = earcut;
function earcut(data, holeIndices, dim) {
dim = dim || 2;
var hasHoles = holeIndices && holeIndices.length,
outerLen = hasHoles ? holeIndices[0] * dim : data.length,
outerNode = linkedList(data, 0, outerLen, dim, true),
triangles = [];
if (!outerNode) return triangles;
var minX, minY, maxX, maxY, x, y, invSize;
if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if (data.length > 80 * dim) {
minX = maxX = data[0];
minY = maxY = data[1];
for (var i = dim; i < outerLen; i += dim) {
x = data[i];
y = data[i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
// minX, minY and invSize are later used to transform coords into integers for z-order calculation
invSize = Math.max(maxX - minX, maxY - minY);
invSize = invSize !== 0 ? 1 / invSize : 0;
}
earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
return triangles;
}
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
var i, last;
if (clockwise === (signedArea(data, start, end, dim) > 0)) {
for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
} else {
for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
}
if (last && equals(last, last.next)) {
removeNode(last);
last = last.next;
}
return last;
}
// eliminate colinear or duplicate points
function filterPoints(start, end) {
if (!start) return start;
if (!end) end = start;
var p = start,
again;
do {
again = false;
if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
removeNode(p);
p = end = p.prev;
if (p === p.next) break;
again = true;
} else {
p = p.next;
}
} while (again || p !== end);
return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
if (!ear) return;
// interlink polygon nodes in z-order
if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
var stop = ear,
prev, next;
// iterate through ears, slicing them one by one
while (ear.prev !== ear.next) {
prev = ear.prev;
next = ear.next;
if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
// cut off the triangle
triangles.push(prev.i / dim);
triangles.push(ear.i / dim);
triangles.push(next.i / dim);
removeNode(ear);
// skipping the next vertice 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(ear, triangles, dim);
earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
// as a last resort, try splitting the remaining polygon into two
} else if (pass === 2) {
splitEarcut(ear, triangles, dim, minX, minY, invSize);
}
break;
}
}
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
var p = ear.next.next;
while (p !== ear.prev) {
if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.next;
}
return true;
}
function isEarHashed(ear, minX, minY, invSize) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
// z-order range for the current triangle bbox;
var minZ = zOrder(minTX, minTY, minX, minY, invSize),
maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
var p = ear.prevZ,
n = ear.nextZ;
// look for points inside the triangle in both directions
while (p && p.z >= minZ && n && n.z <= maxZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.prevZ;
if (n !== ear.prev && n !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, 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 !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, 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 !== ear.prev && n !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
area(n.prev, n, n.next) >= 0) return false;
n = n.nextZ;
}
return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
var p = start;
do {
var a = p.prev,
b = p.next.next;
if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
triangles.push(a.i / dim);
triangles.push(p.i / dim);
triangles.push(b.i / dim);
// remove two nodes involved
removeNode(p);
removeNode(p.next);
p = start = b;
}
p = p.next;
} while (p !== start);
return p;
}
// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
// look for a valid diagonal that divides the polygon into two
var a = start;
do {
var b = a.next.next;
while (b !== a.prev) {
if (a.i !== b.i && isValidDiagonal(a, b)) {
// split the polygon in two by the diagonal
var c = splitPolygon(a, b);
// filter colinear points around the cuts
a = filterPoints(a, a.next);
c = filterPoints(c, c.next);
// run earcut on each half
earcutLinked(a, triangles, dim, minX, minY, invSize);
earcutLinked(c, triangles, dim, minX, minY, invSize);
return;
}
b = b.next;
}
a = a.next;
} while (a !== start);
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
var queue = [],
i, len, start, end, list;
for (i = 0, len = holeIndices.length; i < len; i++) {
start = holeIndices[i] * dim;
end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
list = linkedList(data, start, end, dim, false);
if (list === list.next) list.steiner = true;
queue.push(getLeftmost(list));
}
queue.sort(compareX);
// process holes from left to right
for (i = 0; i < queue.length; i++) {
eliminateHole(queue[i], outerNode);
outerNode = filterPoints(outerNode, outerNode.next);
}
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) {
outerNode = findHoleBridge(hole, outerNode);
if (outerNode) {
var b = splitPolygon(outerNode, hole);
filterPoints(b, b.next);
}
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
var p = outerNode,
hx = hole.x,
hy = hole.y,
qx = -Infinity,
m;
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do {
if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
if (x <= hx && x > qx) {
qx = x;
if (x === hx) {
if (hy === p.y) return p;
if (hy === p.next.y) return p.next;
}
m = p.x < p.next.x ? p : p.next;
}
}
p = p.next;
} while (p !== outerNode);
if (!m) return null;
if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
var stop = m,
mx = m.x,
my = m.y,
tanMin = Infinity,
tan;
p = m.next;
while (p !== stop) {
if (hx >= p.x && p.x >= mx && hx !== p.x &&
pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
m = p;
tanMin = tan;
}
}
p = p.next;
}
return m;
}
// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, invSize) {
var p = start;
do {
if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next;
} while (p !== start);
p.prevZ.nextZ = null;
p.prevZ = null;
sortLinked(p);
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
var i, p, q, e, tail, numMerges, pSize, qSize,
inSize = 1;
do {
p = list;
list = null;
tail = null;
numMerges = 0;
while (p) {
numMerges++;
q = p;
pSize = 0;
for (i = 0; i < inSize; i++) {
pSize++;
q = q.nextZ;
if (!q) break;
}
qSize = inSize;
while (pSize > 0 || (qSize > 0 && q)) {
if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
e = p;
p = p.nextZ;
pSize--;
} else {
e = q;
q = q.nextZ;
qSize--;
}
if (tail) tail.nextZ = e;
else list = e;
e.prevZ = tail;
tail = e;
}
p = q;
}
tail.nextZ = null;
inSize *= 2;
} while (numMerges > 1);
return list;
}
// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder(x, y, minX, minY, invSize) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * (x - minX) * invSize;
y = 32767 * (y - minY) * invSize;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
// find the leftmost node of a polygon ring
function getLeftmost(start) {
var p = start,
leftmost = start;
do {
if (p.x < leftmost.x) 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) >= 0 &&
(ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
(bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
// 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);
}
// 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) {
if ((equals(p1, q1) && equals(p2, q2)) ||
(equals(p1, q2) && equals(p2, q1))) return true;
return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
var p = a;
do {
if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
intersects(p, p.next, a, b)) return true;
p = p.next;
} while (p !== a);
return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
return area(a.prev, a, a.next) < 0 ?
area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
var p = a,
inside = false,
px = (a.x + b.x) / 2,
py = (a.y + b.y) / 2;
do {
if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
(px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
inside = !inside;
p = p.next;
} while (p !== a);
return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
var a2 = new Node(a.i, a.x, a.y),
b2 = new Node(b.i, b.x, b.y),
an = a.next,
bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
var p = new Node(i, x, y);
if (!last) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next.prev = p;
last.next = p;
}
return p;
}
function removeNode(p) {
p.next.prev = p.prev;
p.prev.next = p.next;
if (p.prevZ) p.prevZ.nextZ = p.nextZ;
if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}
function Node(i, x, y) {
// vertice index in coordinates array
this.i = i;
// vertex coordinates
this.x = x;
this.y = y;
// previous and next vertice nodes in a polygon ring
this.prev = null;
this.next = null;
// z-order curve value
this.z = null;
// previous and next nodes in z-order
this.prevZ = null;
this.nextZ = null;
// indicates whether this is a steiner point
this.steiner = false;
}
// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
var hasHoles = holeIndices && holeIndices.length;
var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
if (hasHoles) {
for (var i = 0, len = holeIndices.length; i < len; i++) {
var start = holeIndices[i] * dim;
var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
polygonArea -= Math.abs(signedArea(data, start, end, dim));
}
}
var trianglesArea = 0;
for (i = 0; i < triangles.length; i += 3) {
var a = triangles[i] * dim;
var b = triangles[i + 1] * dim;
var c = triangles[i + 2] * dim;
trianglesArea += Math.abs(
(data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
(data[a] - data[b]) * (data[c + 1] - data[a + 1]));
}
return polygonArea === 0 && trianglesArea === 0 ? 0 :
Math.abs((trianglesArea - polygonArea) / polygonArea);
};
function signedArea(data, start, end, dim) {
var sum = 0;
for (var i = start, j = end - dim; i < end; i += dim) {
sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
j = i;
}
return sum;
}
// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
var dim = data[0][0].length,
result = {vertices: [], holes: [], dimensions: dim},
holeIndex = 0;
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
}
if (i > 0) {
holeIndex += data[i - 1].length;
result.holes.push(holeIndex);
}
}
return result;
};
},{}],16:[function(require,module,exports){
var geojsonArea = require('@mapbox/geojson-area');
module.exports = rewind;
function rewind(gj, outer) {
switch ((gj && gj.type) || null) {
case 'FeatureCollection':
gj.features = gj.features.map(curryOuter(rewind, outer));
return gj;
case 'Feature':
gj.geometry = rewind(gj.geometry, outer);
return gj;
case 'Polygon':
case 'MultiPolygon':
return correct(gj, outer);
default:
return gj;
}
}
function curryOuter(a, b) {
return function(_) { return a(_, b); };
}
function correct(_, outer) {
if (_.type === 'Polygon') {
_.coordinates = correctRings(_.coordinates, outer);
} else if (_.type === 'MultiPolygon') {
_.coordinates = _.coordinates.map(curryOuter(correctRings, outer));
}
return _;
}
function correctRings(_, outer) {
outer = !!outer;
_[0] = wind(_[0], outer);
for (var i = 1; i < _.length; i++) {
_[i] = wind(_[i], !outer);
}
return _;
}
function wind(_, dir) {
return cw(_) === dir ? _ : _.reverse();
}
function cw(_) {
return geojsonArea.ring(_) >= 0;
}
},{"@mapbox/geojson-area":1}],17:[function(require,module,exports){
'use strict';
module.exports = clip;
var createFeature = require('./feature');
/* clip features between two axis-parallel lines:
* | |
* ___|___ | /
* / | \____|____/
* | |
*/
function clip(features, scale, k1, k2, axis, minAll, maxAll) {
k1 /= scale;
k2 /= scale;
if (minAll >= k1 && maxAll <= k2) return features; // trivial accept
else if (minAll > k2 || maxAll < k1) return null; // trivial reject
var clipped = [];
for (var i = 0; i < features.length; i++) {
var feature = features[i];
var geometry = feature.geometry;
var type = feature.type;
var min = axis === 0 ? feature.minX : feature.minY;
var max = axis === 0 ? feature.maxX : feature.maxY;
if (min >= k1 && max <= k2) { // trivial accept
clipped.push(feature);
continue;
} else if (min > k2 || max < k1) { // trivial reject
continue;
}
var newGeometry = [];
if (type === 'Point' || type === 'MultiPoint') {
clipPoints(geometry, newGeometry, k1, k2, axis);
} else if (type === 'LineString') {
clipLine(geometry, newGeometry, k1, k2, axis, false);
} else if (type === 'MultiLineString') {
clipLines(geometry, newGeometry, k1, k2, axis, false);
} else if (type === 'Polygon') {
clipLines(geometry, newGeometry, k1, k2, axis, true);
} else if (type === 'MultiPolygon') {
for (var j = 0; j < geometry.length; j++) {
var polygon = [];
clipLines(geometry[j], polygon, k1, k2, axis, true);
if (polygon.length) {
newGeometry.push(polygon);
}
}
}
if (newGeometry.length) {
if (type === 'LineString' || type === 'MultiLineString') {
if (newGeometry.length === 1) {
type = 'LineString';
newGeometry = newGeometry[0];
} else {
type = 'MultiLineString';
}
}
if (type === 'Point' || type === 'MultiPoint') {
type = newGeometry.length === 3 ? 'Point' : 'MultiPoint';
}
clipped.push(createFeature(feature.id, type, newGeometry, feature.tags));
}
}
return clipped.length ? clipped : null;
}
function clipPoints(geom, newGeom, k1, k2, axis) {
for (var i = 0; i < geom.length; i += 3) {
var a = geom[i + axis];
if (a >= k1 && a <= k2) {
newGeom.push(geom[i]);
newGeom.push(geom[i + 1]);
newGeom.push(geom[i + 2]);
}
}
}
function clipLine(geom, newGeom, k1, k2, axis, isPolygon) {
var slice = [];
var intersect = axis === 0 ? intersectX : intersectY;
for (var i = 0; i < geom.length - 3; i += 3) {
var ax = geom[i];
var ay = geom[i + 1];
var az = geom[i + 2];
var bx = geom[i + 3];
var by = geom[i + 4];
var a = axis === 0 ? ax : ay;
var b = axis === 0 ? bx : by;
var sliced = false;
if (a < k1) {
// ---|--> |
if (b >= k1) intersect(slice, ax, ay, bx, by, k1);
} else if (a > k2) {
// | <--|---
if (b <= k2) intersect(slice, ax, ay, bx, by, k2);
} else {
addPoint(slice, ax, ay, az);
}
if (b < k1 && a >= k1) {
// <--|--- | or <--|-----|---
intersect(slice, ax, ay, bx, by, k1);
sliced = true;
}
if (b > k2 && a <= k2) {
// | ---|--> or ---|-----|-->
intersect(slice, ax, ay, bx, by, k2);
sliced = true;
}
if (!isPolygon && sliced) {
slice.size = geom.size;
newGeom.push(slice);
slice = [];
}
}
// add the last point
var last = geom.length - 3;
ax = geom[last];
ay = geom[last + 1];
az = geom[last + 2];
a = axis === 0 ? ax : ay;
if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az);
// close the polygon if its endpoints are not the same after clipping
last = slice.length - 3;
if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {
addPoint(slice, slice[0], slice[1], slice[2]);
}
// add the final slice
if (slice.length) {
slice.size = geom.size;
newGeom.push(slice);
}
}
function clipLines(geom, newGeom, k1, k2, axis, isPolygon) {
for (var i = 0; i < geom.length; i++) {
clipLine(geom[i], newGeom, k1, k2, axis, isPolygon);
}
}
function addPoint(out, x, y, z) {
out.push(x);
out.push(y);
out.push(z);
}
function intersectX(out, ax, ay, bx, by, x) {
out.push(x);
out.push(ay + (x - ax) * (by - ay) / (bx - ax));
out.push(1);
}
function intersectY(out, ax, ay, bx, by, y) {
out.push(ax + (y - ay) * (bx - ax) / (by - ay));
out.push(y);
out.push(1);
}
},{"./feature":19}],18:[function(require,module,exports){
'use strict';
module.exports = convert;
var simplify = require('./simplify');
var createFeature = require('./feature');
// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data
function convert(data, tolerance) {
var features = [];
if (data.type === 'FeatureCollection') {
for (var i = 0; i < data.features.length; i++) {
convertFeature(features, data.features[i], tolerance);
}
} else if (data.type === 'Feature') {
convertFeature(features, data, tolerance);
} else {
// single geometry or a geometry collection
convertFeature(features, {geometry: data}, tolerance);
}
return features;
}
function convertFeature(features, geojson, tolerance) {
if (!geojson.geometry) return;
var coords = geojson.geometry.coordinates;
var type = geojson.geometry.type;
var tol = tolerance * tolerance;
var geometry = [];
if (type === 'Point') {
convertPoint(coords, geometry);
} else if (type === 'MultiPoint') {
for (var i = 0; i < coords.length; i++) {
convertPoint(coords[i], geometry);
}
} else if (type === 'LineString') {
convertLine(coords, geometry, tol, false);
} else if (type === 'MultiLineString') {
convertLines(coords, geometry, tol, false);
} else if (type === 'Polygon') {
convertLines(coords, geometry, tol, true);
} else if (type === 'MultiPolygon') {
for (i = 0; i < coords.length; i++) {
var polygon = [];
convertLines(coords[i], polygon, tol, true);
geometry.push(polygon);
}
} else if (type === 'GeometryCollection') {
for (i = 0; i < geojson.geometry.geometries.length; i++) {
convertFeature(features, {
geometry: geojson.geometry.geometries[i],
properties: geojson.properties
}, tolerance);
}
return;
} else {
throw new Error('Input data is not a valid GeoJSON object.');
}
features.push(createFeature(geojson.id, type, geometry, geojson.properties));
}
function convertPoint(coords, out) {
out.push(projectX(coords[0]));
out.push(projectY(coords[1]));
out.push(0);
}
function convertLine(ring, out, tol, isPolygon) {
var x0, y0;
var size = 0;
for (var j = 0; j < ring.length; j++) {
var x = projectX(ring[j][0]);
var y = projectY(ring[j][1]);
out.push(x);
out.push(y);
out.push(0);
if (j > 0) {
if (isPolygon) {
size += (x0 * y - x * y0) / 2; // area
} else {
size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length
}
}
x0 = x;
y0 = y;
}
var last = out.length - 3;
out[2] = 1;
simplify(out, 0, last, tol);
out[last + 2] = 1;
out.size = Math.abs(size);
}
function convertLines(rings, out, tol, isPolygon) {
for (var i = 0; i < rings.length; i++) {
var geom = [];
convertLine(rings[i], geom, tol, isPolygon);
out.push(geom);
}
}
function projectX(x) {
return x / 360 + 0.5;
}
function projectY(y) {
var sin = Math.sin(y * Math.PI / 180);
var y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
}
},{"./feature":19,"./simplify":21}],19:[function(require,module,exports){
'use strict';
module.exports = createFeature;
function createFeature(id, type, geom, tags) {
var feature = {
id: id || null,
type: type,
geometry: geom,
tags: tags,
minX: Infinity,
minY: Infinity,
maxX: -Infinity,
maxY: -Infinity
};
calcBBox(feature);
return feature;
}
function calcBBox(feature) {
var geom = feature.geometry;
var type = feature.type;
if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
calcLineBBox(feature, geom);
} else if (type === 'Polygon' || type === 'MultiLineString') {
for (var i = 0; i < geom.length; i++) {
calcLineBBox(feature, geom[i]);
}
} else if (type === 'MultiPolygon') {
for (i = 0; i < geom.length; i++) {
for (var j = 0; j < geom[i].length; j++) {
calcLineBBox(feature, geom[i][j]);
}
}
}
}
function calcLineBBox(feature, geom) {
for (var i = 0; i < geom.length; i += 3) {
feature.minX = Math.min(feature.minX, geom[i]);
feature.minY = Math.min(feature.minY, geom[i + 1]);
feature.maxX = Math.max(feature.maxX, geom[i]);
feature.maxY = Math.max(feature.maxY, geom[i + 1]);
}
}
},{}],20:[function(require,module,exports){
'use strict';
module.exports = geojsonvt;
var convert = require('./convert'), // GeoJSON conversion and preprocessing
transform = require('./transform'), // coordinate transformation
clip = require('./clip'), // stripe clipping algorithm
wrap = require('./wrap'), // date line processing
createTile = require('./tile'); // final simplified tile generation
function geojsonvt(data, options) {
return new GeoJSONVT(data, options);
}
function GeoJSONVT(data, options) {
options = this.options = extend(Object.create(this.options), options);
var debug = options.debug;
if (debug) console.time('preprocess data');
if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range');
var z2 = 1 << options.maxZoom, // 2^z
features = convert(data, options.tolerance / (z2 * options.extent));
this.tiles = {};
this.tileCoords = [];
if (debug) {
console.timeEnd('preprocess data');
console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
console.time('generate tiles');
this.stats = {};
this.total = 0;
}
features = wrap(features, options.buffer / options.extent);
// start slicing from the top tile down
if (features.length) this.splitTile(features, 0, 0, 0);
if (debug) {
if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
console.timeEnd('generate tiles');
console.log('tiles generated:', this.total, JSON.stringify(this.stats));
}
}
GeoJSONVT.prototype.options = {
maxZoom: 14, // max zoom to preserve detail on
indexMaxZoom: 5, // max zoom in the tile index
indexMaxPoints: 100000, // max number of points per tile in the tile index
tolerance: 3, // simplification tolerance (higher means simpler)
extent: 4096, // tile extent
buffer: 64, // tile buffer on each side
debug: 0 // logging level (0, 1 or 2)
};
GeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {
var stack = [features, z, x, y],
options = this.options,
debug = options.debug;
// avoid recursion by using a processing queue
while (stack.length) {
y = stack.pop();
x = stack.pop();
z = stack.pop();
features = stack.pop();
var z2 = 1 << z,
id = toID(z, x, y),
tile = this.tiles[id],
tileTolerance = z === options.maxZoom ? 0 : options.tolerance / (z2 * options.extent);
if (!tile) {
if (debug > 1) console.time('creation');
tile = this.tiles[id] = createTile(features, z2, x, y, tileTolerance, z === options.maxZoom);
this.tileCoords.push({z: z, x: x, y: y});
if (debug) {
if (debug > 1) {
console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)',
z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
console.timeEnd('creation');
}
var key = 'z' + z;
this.stats[key] = (this.stats[key] || 0) + 1;
this.total++;
}
}
// save reference to original geometry in tile so that we can drill down later if we stop now
tile.source = features;
// if it's the first-pass tiling
if (!cz) {
// stop tiling if we reached max zoom, or if the tile is too simple
if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;
// if a drilldown to a specific tile
} else {
// stop tiling if we reached base zoom or our target tile zoom
if (z === options.maxZoom || z === cz) continue;
// stop tiling if it's not an ancestor of the target tile
var m = 1 << (cz - z);
if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m)) continue;
}
// if we slice further down, no need to keep source geometry
tile.source = null;
if (features.length === 0) continue;
if (debug > 1) console.time('clipping');
// values we'll use for clipping
var k1 = 0.5 * options.buffer / options.extent,
k2 = 0.5 - k1,
k3 = 0.5 + k1,
k4 = 1 + k1,
tl, bl, tr, br, left, right;
tl = bl = tr = br = null;
left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX);
right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX);
features = null;
if (left) {
tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY);
bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY);
left = null;
}
if (right) {
tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY);
br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY);
right = null;
}
if (debug > 1) console.timeEnd('clipping');
stack.push(tl || [], z + 1, x * 2, y * 2);
stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
}
};
GeoJSONVT.prototype.getTile = function (z, x, y) {
var options = this.options,
extent = options.extent,
debug = options.debug;
if (z < 0 || z > 24) return null;
var z2 = 1 << z;
x = ((x % z2) + z2) % z2; // wrap tile x coordinate
var id = toID(z, x, y);
if (this.tiles[id]) return transform.tile(this.tiles[id], extent);
if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y);
var z0 = z,
x0 = x,
y0 = y,
parent;
while (!parent && z0 > 0) {
z0--;
x0 = Math.floor(x0 / 2);
y0 = Math.floor(y0 / 2);
parent = this.tiles[toID(z0, x0, y0)];
}
if (!parent || !parent.source) return null;
// if we found a parent tile containing the original geometry, we can drill down from it
if (debug > 1) console.log('found parent tile z%d-%d-%d', z0, x0, y0);
if (debug > 1) console.time('drilling down');
this.splitTile(parent.source, z0, x0, y0, z, x, y);
if (debug > 1) console.timeEnd('drilling down');
return this.tiles[id] ? transform.tile(this.tiles[id], extent) : null;
};
function toID(z, x, y) {
return (((1 << z) * y + x) * 32) + z;
}
function extend(dest, src) {
for (var i in src) dest[i] = src[i];
return dest;
}
},{"./clip":17,"./convert":18,"./tile":22,"./transform":23,"./wrap":24}],21:[function(require,module,exports){
'use strict';
module.exports = simplify;
// calculate simplification data using optimized Douglas-Peucker algorithm
function simplify(coords, first, last, sqTolerance) {
var maxSqDist = sqTolerance;
var index;
var ax = coords[first];
var ay = coords[first + 1];
var bx = coords[last];
var by = coords[last + 1];
for (var i = first + 3; i < last; i += 3) {
var d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
if (d > maxSqDist) {
index = i;
maxSqDist = d;
}
}
if (maxSqDist > sqTolerance) {
if (index - first > 3) simplify(coords, first, index, sqTolerance);
coords[index + 2] = maxSqDist;
if (last - index > 3) simplify(coords, index, last, sqTolerance);
}
}
// square distance from a point to a segment
function getSqSegDist(px, py, x, y, bx, by) {
var dx = bx - x;
var dy = by - y;
if (dx !== 0 || dy !== 0) {
var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = bx;
y = by;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = px - x;
dy = py - y;
return dx * dx + dy * dy;
}
},{}],22:[function(require,module,exports){
'use strict';
module.exports = createTile;
function createTile(features, z2, tx, ty, tolerance, noSimplify) {
var tile = {
features: [],
numPoints: 0,
numSimplified: 0,
numFeatures: 0,
source: null,
x: tx,
y: ty,
z2: z2,
transformed: false,
minX: 2,
minY: 1,
maxX: -1,
maxY: 0
};
for (var i = 0; i < features.length; i++) {
tile.numFeatures++;
addFeature(tile, features[i], tolerance, noSimplify);
var minX = features[i].minX;
var minY = features[i].minY;
var maxX = features[i].maxX;
var maxY = features[i].maxY;
if (minX < tile.minX) tile.minX = minX;
if (minY < tile.minY) tile.minY = minY;
if (maxX > tile.maxX) tile.maxX = maxX;
if (maxY > tile.maxY) tile.maxY = maxY;
}
return tile;
}
function addFeature(tile, feature, tolerance, noSimplify) {
var geom = feature.geometry,
type = feature.type,
simplified = [];
if (type === 'Point' || type === 'MultiPoint') {
for (var i = 0; i < geom.length; i += 3) {
simplified.push(geom[i]);
simplified.push(geom[i + 1]);
tile.numPoints++;
tile.numSimplified++;
}
} else if (type === 'LineString') {
addLine(simplified, geom, tile, tolerance, noSimplify, false, false);
} else if (type === 'MultiLineString' || type === 'Polygon') {
for (i = 0; i < geom.length; i++) {
addLine(simplified, geom[i], tile, tolerance, noSimplify, type === 'Polygon', i === 0);
}
} else if (type === 'MultiPolygon') {
for (var k = 0; k < geom.length; k++) {
var polygon = geom[k];
for (i = 0; i < polygon.length; i++) {
addLine(simplified, polygon[i], tile, tolerance, noSimplify, true, i === 0);
}
}
}
if (simplified.length) {
var tileFeature = {
geometry: simplified,
type: type === 'Polygon' || type === 'MultiPolygon' ? 3 :
type === 'LineString' || type === 'MultiLineString' ? 2 : 1,
tags: feature.tags || null
};
if (feature.id !== null) {
tileFeature.id = feature.id;
}
tile.features.push(tileFeature);
}
}
function addLine(result, geom, tile, tolerance, noSimplify, isPolygon, isOuter) {
var sqTolerance = tolerance * tolerance;
if (!noSimplify && (geom.size < (isPolygon ? sqTolerance : tolerance))) {
tile.numPoints += geom.length / 3;
return;
}
var ring = [];
for (var i = 0; i < geom.length; i += 3) {
if (noSimplify || geom[i + 2] > sqTolerance) {
tile.numSimplified++;
ring.push(geom[i]);
ring.push(geom[i + 1]);
}
tile.numPoints++;
}
if (isPolygon) rewind(ring, isOuter);
result.push(ring);
}
function rewind(ring, clockwise) {
var area = 0;
for (var i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
}
if (area > 0 === clockwise) {
for (i = 0, len = ring.length; i < len / 2; i += 2) {
var x = ring[i];
var y = ring[i + 1];
ring[i] = ring[len - 2 - i];
ring[i + 1] = ring[len - 1 - i];
ring[len - 2 - i] = x;
ring[len - 1 - i] = y;
}
}
}
},{}],23:[function(require,module,exports){
'use strict';
exports.tile = transformTile;
exports.point = transformPoint;
// Transforms the coordinates of each feature in the given tile from
// mercator-projected space into (extent x extent) tile space.
function transformTile(tile, extent) {
if (tile.transformed) return tile;
var z2 = tile.z2,
tx = tile.x,
ty = tile.y,
i, j, k;
for (i = 0; i < tile.features.length; i++) {
var feature = tile.features[i],
geom = feature.geometry,
type = feature.type;
feature.geometry = [];
if (type === 1) {
for (j = 0; j < geom.length; j += 2) {
feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));
}
} else {
for (j = 0; j < geom.length; j++) {
var ring = [];
for (k = 0; k < geom[j].length; k += 2) {
ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));
}
feature.geometry.push(ring);
}
}
}
tile.transformed = true;
return tile;
}
function transformPoint(x, y, extent, z2, tx, ty) {
return [
Math.round(extent * (x * z2 - tx)),
Math.round(extent * (y * z2 - ty))];
}
},{}],24:[function(require,module,exports){
'use strict';
var clip = require('./clip');
var createFeature = require('./feature');
module.exports = wrap;
function wrap(features, buffer) {
var merged = features,
left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2), // left world copy
right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2); // right world copy
if (left || right) {
merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2) || []; // center world copy
if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center
if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center
}
return merged;
}
function shiftFeatureCoords(features, offset) {
var newFeatures = [];
for (var i = 0; i < features.length; i++) {
var feature = features[i],
type = feature.type;
var newGeometry;
if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
newGeometry = shiftCoords(feature.geometry, offset);
} else if (type === 'MultiLineString' || type === 'Polygon') {
newGeometry = [];
for (var j = 0; j < feature.geometry.length; j++) {
newGeometry.push(shiftCoords(feature.geometry[j], offset));
}
} else if (type === 'MultiPolygon') {
newGeometry = [];
for (j = 0; j < feature.geometry.length; j++) {
var newPolygon = [];
for (var k = 0; k < feature.geometry[j].length; k++) {
newPolygon.push(shiftCoords(feature.geometry[j][k], offset));
}
newGeometry.push(newPolygon);
}
}
newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));
}
return newFeatures;
}
function shiftCoords(points, offset) {
var newPoints = [];
newPoints.size = points.size;
for (var i = 0; i < points.length; i += 3) {
newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);
}
return newPoints;
}
},{"./clip":17,"./feature":19}],25:[function(require,module,exports){
'use strict';
module.exports = 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) {
var min = this.min;
var max = this.max;
if (x1 <= min && y1 <= min && max <= x2 && max <= y2) {
// 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);
return result;
}
};
GridIndex.prototype._queryCell = function(x1, y1, x2, y2, cellIndex, result, seenUids) {
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 ((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) {
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 (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2)) return;
}
}
};
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;
};
},{}],26:[function(require,module,exports){
exports.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)
}
exports.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 & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],27:[function(require,module,exports){
'use strict';
var sort = require('./sort');
var range = require('./range');
var within = require('./within');
module.exports = kdbush;
function kdbush(points, getX, getY, nodeSize, ArrayType) {
return new KDBush(points, getX, getY, nodeSize, ArrayType);
}
function KDBush(points, getX, getY, nodeSize, ArrayType) {
getX = getX || defaultGetX;
getY = getY || defaultGetY;
ArrayType = ArrayType || Array;
this.nodeSize = nodeSize || 64;
this.points = points;
this.ids = new ArrayType(points.length);
this.coords = new ArrayType(points.length * 2);
for (var i = 0; i < points.length; i++) {
this.ids[i] = i;
this.coords[2 * i] = getX(points[i]);
this.coords[2 * i + 1] = getY(points[i]);
}
sort(this.ids, this.coords, this.nodeSize, 0, this.ids.length - 1, 0);
}
KDBush.prototype = {
range: function (minX, minY, maxX, maxY) {
return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);
},
within: function (x, y, r) {
return within(this.ids, this.coords, x, y, r, this.nodeSize);
}
};
function defaultGetX(p) { return p[0]; }
function defaultGetY(p) { return p[1]; }
},{"./range":28,"./sort":29,"./within":30}],28:[function(require,module,exports){
'use strict';
module.exports = range;
function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {
var stack = [0, ids.length - 1, 0];
var result = [];
var x, y;
while (stack.length) {
var axis = stack.pop();
var right = stack.pop();
var left = stack.pop();
if (right - left <= nodeSize) {
for (var i = left; i <= right; i++) {
x = coords[2 * i];
y = coords[2 * i + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
}
continue;
}
var m = Math.floor((left + right) / 2);
x = coords[2 * m];
y = coords[2 * m + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
var nextAxis = (axis + 1) % 2;
if (axis === 0 ? minX <= x : minY <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(nextAxis);
}
if (axis === 0 ? maxX >= x : maxY >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(nextAxis);
}
}
return result;
}
},{}],29:[function(require,module,exports){
'use strict';
module.exports = sortKD;
function sortKD(ids, coords, nodeSize, left, right, depth) {
if (right - left <= nodeSize) return;
var m = Math.floor((left + right) / 2);
select(ids, coords, m, left, right, depth % 2);
sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);
sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);
}
function select(ids, coords, k, left, right, inc) {
while (right > left) {
if (right - left > 600) {
var n = right - left + 1;
var m = k - left + 1;
var z = Math.log(n);
var s = 0.5 * Math.exp(2 * z / 3);
var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
select(ids, coords, k, newLeft, newRight, inc);
}
var t = coords[2 * k + inc];
var i = left;
var j = right;
swapItem(ids, coords, left, k);
if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right);
while (i < j) {
swapItem(ids, coords, i, j);
i++;
j--;
while (coords[2 * i + inc] < t) i++;
while (coords[2 * j + inc] > t) j--;
}
if (coords[2 * left + inc] === 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;
}
}
function swapItem(ids, coords, i, j) {
swap(ids, i, j);
swap(coords, 2 * i, 2 * j);
swap(coords, 2 * i + 1, 2 * j + 1);
}
function swap(arr, i, j) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
},{}],30:[function(require,module,exports){
'use strict';
module.exports = within;
function within(ids, coords, qx, qy, r, nodeSize) {
var stack = [0, ids.length - 1, 0];
var result = [];
var r2 = r * r;
while (stack.length) {
var axis = stack.pop();
var right = stack.pop();
var left = stack.pop();
if (right - left <= nodeSize) {
for (var i = left; i <= right; i++) {
if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
}
continue;
}
var m = Math.floor((left + right) / 2);
var x = coords[2 * m];
var y = coords[2 * m + 1];
if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);
var nextAxis = (axis + 1) % 2;
if (axis === 0 ? qx - r <= x : qy - r <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(nextAxis);
}
if (axis === 0 ? qx + r >= x : qy + r >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(nextAxis);
}
}
return result;
}
function sqDist(ax, ay, bx, by) {
var dx = ax - bx;
var dy = ay - by;
return dx * dx + dy * dy;
}
},{}],31:[function(require,module,exports){
'use strict';
module.exports = Pbf;
var ieee754 = require('ieee754');
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;
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 & 0x7;
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 & 0x7f; if (b < 0x80) return val;
b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
b = buf[this.pos]; val |= (b & 0x0f) << 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,
str = readUtf8(this.buf, this.pos, end);
this.pos = end;
return str;
},
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) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readVarint(isSigned));
return arr;
},
readPackedSVarint: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readSVarint());
return arr;
},
readPackedBoolean: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readBoolean());
return arr;
},
readPackedFloat: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readFloat());
return arr;
},
readPackedDouble: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readDouble());
return arr;
},
readPackedFixed32: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readFixed32());
return arr;
},
readPackedSFixed32: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readSFixed32());
return arr;
},
readPackedFixed64: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readFixed64());
return arr;
},
readPackedSFixed64: function(arr) {
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readSFixed64());
return arr;
},
skip: function(val) {
var type = val & 0x7;
if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
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 > 0xfffffff || val < 0) {
writeBigVarint(val, this);
return;
}
this.realloc(4);
this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
this.buf[this.pos++] = (val >>> 7) & 0x7f;
},
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 >= 0x80) 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 >= 0x80) 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) { this.writeMessage(tag, writePackedVarint, arr); },
writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
writePackedSFixed64: function(tag, arr) { 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 & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) 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 * 0x100000000 + (low >>> 0);
}
return ((high >>> 0) * 0x100000000) + (low >>> 0);
}
function writeBigVarint(val, pbf) {
var low, high;
if (val >= 0) {
low = (val % 0x100000000) | 0;
high = (val / 0x100000000) | 0;
} else {
low = ~(-val % 0x100000000);
high = ~(-val / 0x100000000);
if (low ^ 0xffffffff) {
low = (low + 1) | 0;
} else {
low = 0;
high = (high + 1) | 0;
}
}
if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
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 & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
pbf.buf[pbf.pos] = low & 0x7f;
}
function writeBigVarintHigh(high, pbf) {
var lsb = (high & 0x07) << 4;
pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
pbf.buf[pbf.pos++] = high & 0x7f;
}
function makeRoomForExtraLength(startPos, len, pbf) {
var extraLen =
len <= 0x3fff ? 1 :
len <= 0x1fffff ? 2 :
len <= 0xfffffff ? 3 : Math.ceil(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] * 0x1000000);
}
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 > 0xEF ? 4 :
b0 > 0xDF ? 3 :
b0 > 0xBF ? 2 : 1;
if (i + bytesPerSequence > end) break;
var b1, b2, b3;
if (bytesPerSequence === 1) {
if (b0 < 0x80) {
c = b0;
}
} else if (bytesPerSequence === 2) {
b1 = buf[i + 1];
if ((b1 & 0xC0) === 0x80) {
c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
if (c <= 0x7F) {
c = null;
}
}
} else if (bytesPerSequence === 3) {
b1 = buf[i + 1];
b2 = buf[i + 2];
if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
c = null;
}
}
} else if (bytesPerSequence === 4) {
b1 = buf[i + 1];
b2 = buf[i + 2];
b3 = buf[i + 3];
if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
if (c <= 0xFFFF || c >= 0x110000) {
c = null;
}
}
}
if (c === null) {
c = 0xFFFD;
bytesPerSequence = 1;
} else if (c > 0xFFFF) {
c -= 0x10000;
str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
c = 0xDC00 | c & 0x3FF;
}
str += String.fromCharCode(c);
i += bytesPerSequence;
}
return str;
}
function writeUtf8(buf, str, pos) {
for (var i = 0, c, lead; i < str.length; i++) {
c = str.charCodeAt(i); // code point
if (c > 0xD7FF && c < 0xE000) {
if (lead) {
if (c < 0xDC00) {
buf[pos++] = 0xEF;
buf[pos++] = 0xBF;
buf[pos++] = 0xBD;
lead = c;
continue;
} else {
c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
lead = null;
}
} else {
if (c > 0xDBFF || (i + 1 === str.length)) {
buf[pos++] = 0xEF;
buf[pos++] = 0xBF;
buf[pos++] = 0xBD;
} else {
lead = c;
}
continue;
}
} else if (lead) {
buf[pos++] = 0xEF;
buf[pos++] = 0xBF;
buf[pos++] = 0xBD;
lead = null;
}
if (c < 0x80) {
buf[pos++] = c;
} else {
if (c < 0x800) {
buf[pos++] = c >> 0x6 | 0xC0;
} else {
if (c < 0x10000) {
buf[pos++] = c >> 0xC | 0xE0;
} else {
buf[pos++] = c >> 0x12 | 0xF0;
buf[pos++] = c >> 0xC & 0x3F | 0x80;
}
buf[pos++] = c >> 0x6 & 0x3F | 0x80;
}
buf[pos++] = c & 0x3F | 0x80;
}
}
return pos;
}
},{"ieee754":26}],32:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],33:[function(require,module,exports){
'use strict';
module.exports = partialSort;
// Floyd-Rivest selection algorithm:
// Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
// The k-th element will have the (k - left + 1)th smallest value in [left, right]
function partialSort(arr, k, left, right, compare) {
left = left || 0;
right = right || (arr.length - 1);
compare = compare || defaultCompare;
while (right > left) {
if (right - left > 600) {
var n = right - left + 1;
var m = k - left + 1;
var z = Math.log(n);
var s = 0.5 * Math.exp(2 * z / 3);
var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
partialSort(arr, k, newLeft, newRight, compare);
}
var t = arr[k];
var i = left;
var j = right;
swap(arr, left, k);
if (compare(arr[right], t) > 0) swap(arr, left, right);
while (i < j) {
swap(arr, i, j);
i++;
j--;
while (compare(arr[i], t) < 0) i++;
while (compare(arr[j], t) > 0) j--;
}
if (compare(arr[left], t) === 0) swap(arr, left, j);
else {
j++;
swap(arr, j, right);
}
if (j <= k) left = j + 1;
if (k <= j) right = j - 1;
}
}
function swap(arr, i, j) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function defaultCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
},{}],34:[function(require,module,exports){
'use strict';
var kdbush = require('kdbush');
module.exports = supercluster;
function supercluster(options) {
return new SuperCluster(options);
}
function SuperCluster(options) {
this.options = extend(Object.create(this.options), options);
this.trees = new Array(this.options.maxZoom + 1);
}
SuperCluster.prototype = {
options: {
minZoom: 0, // min zoom to generate clusters on
maxZoom: 16, // max zoom level to cluster the points on
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
// a reduce function for calculating custom cluster properties
reduce: null, // function (accumulated, props) { accumulated.sum += props.sum; }
// initial properties of a cluster (before running the reducer)
initial: function () { return {}; }, // function () { return {sum: 0}; },
// properties to use for individual points when running the reducer
map: function (props) { return props; } // function (props) { return {sum: props.my_value}; },
},
load: function (points) {
var log = this.options.log;
if (log) console.time('total time');
var timerId = 'prepare ' + points.length + ' points';
if (log) console.time(timerId);
this.points = points;
// generate a cluster object for each point
var clusters = points.map(createPointCluster);
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 (var z = this.options.maxZoom; z >= this.options.minZoom; z--) {
var now = +Date.now();
// index input points into a KD-tree
this.trees[z + 1] = kdbush(clusters, getX, getY, this.options.nodeSize, Float32Array);
clusters = this._cluster(clusters, z); // create a new set of clusters for the zoom
if (log) console.log('z%d: %d clusters in %dms', z, clusters.length, +Date.now() - now);
}
// index top-level clusters
this.trees[this.options.minZoom] = kdbush(clusters, getX, getY, this.options.nodeSize, Float32Array);
if (log) console.timeEnd('total time');
return this;
},
getClusters: function (bbox, zoom) {
var tree = this.trees[this._limitZoom(zoom)];
var ids = tree.range(lngX(bbox[0]), latY(bbox[3]), lngX(bbox[2]), latY(bbox[1]));
var clusters = [];
for (var i = 0; i < ids.length; i++) {
var c = tree.points[ids[i]];
clusters.push(c.numPoints ? getClusterJSON(c) : this.points[c.id]);
}
return clusters;
},
getChildren: function (clusterId, clusterZoom) {
var origin = this.trees[clusterZoom + 1].points[clusterId];
var r = this.options.radius / (this.options.extent * Math.pow(2, clusterZoom));
var points = this.trees[clusterZoom + 1].within(origin.x, origin.y, r);
var children = [];
for (var i = 0; i < points.length; i++) {
var c = this.trees[clusterZoom + 1].points[points[i]];
if (c.parentId === clusterId) {
children.push(c.numPoints ? getClusterJSON(c) : this.points[c.id]);
}
}
return children;
},
getLeaves: function (clusterId, clusterZoom, limit, offset) {
limit = limit || 10;
offset = offset || 0;
var leaves = [];
this._appendLeaves(leaves, clusterId, clusterZoom, limit, offset, 0);
return leaves;
},
getTile: function (z, x, y) {
var tree = this.trees[this._limitZoom(z)];
var z2 = Math.pow(2, z);
var extent = this.options.extent;
var r = this.options.radius;
var p = r / extent;
var top = (y - p) / z2;
var bottom = (y + 1 + p) / z2;
var tile = {
features: []
};
this._addTileFeatures(
tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom),
tree.points, x, y, z2, tile);
if (x === 0) {
this._addTileFeatures(
tree.range(1 - p / z2, top, 1, bottom),
tree.points, z2, y, z2, tile);
}
if (x === z2 - 1) {
this._addTileFeatures(
tree.range(0, top, p / z2, bottom),
tree.points, -1, y, z2, tile);
}
return tile.features.length ? tile : null;
},
getClusterExpansionZoom: function (clusterId, clusterZoom) {
while (clusterZoom < this.options.maxZoom) {
var children = this.getChildren(clusterId, clusterZoom);
clusterZoom++;
if (children.length !== 1) break;
clusterId = children[0].properties.cluster_id;
}
return clusterZoom;
},
_appendLeaves: function (result, clusterId, clusterZoom, limit, offset, skipped) {
var children = this.getChildren(clusterId, clusterZoom);
for (var i = 0; i < children.length; i++) {
var props = children[i].properties;
if (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, clusterZoom + 1, limit, offset, skipped);
// exit the cluster
}
} else if (skipped < offset) {
// skip a single point
skipped++;
} else {
// add a single point
result.push(children[i]);
}
if (result.length === limit) break;
}
return skipped;
},
_addTileFeatures: function (ids, points, x, y, z2, tile) {
for (var i = 0; i < ids.length; i++) {
var c = points[ids[i]];
tile.features.push({
type: 1,
geometry: [[
Math.round(this.options.extent * (c.x * z2 - x)),
Math.round(this.options.extent * (c.y * z2 - y))
]],
tags: c.numPoints ? getClusterProperties(c) : this.points[c.id].properties
});
}
},
_limitZoom: function (z) {
return Math.max(this.options.minZoom, Math.min(z, this.options.maxZoom + 1));
},
_cluster: function (points, zoom) {
var clusters = [];
var r = this.options.radius / (this.options.extent * Math.pow(2, zoom));
// loop through each point
for (var i = 0; i < points.length; i++) {
var p = points[i];
// if we've already visited the point at this zoom level, skip it
if (p.zoom <= zoom) continue;
p.zoom = zoom;
// find all nearby points
var tree = this.trees[zoom + 1];
var neighborIds = tree.within(p.x, p.y, r);
var numPoints = p.numPoints || 1;
var wx = p.x * numPoints;
var wy = p.y * numPoints;
var clusterProperties = null;
if (this.options.reduce) {
clusterProperties = this.options.initial();
this._accumulate(clusterProperties, p);
}
for (var j = 0; j < neighborIds.length; j++) {
var b = tree.points[neighborIds[j]];
// filter out neighbors that are too far or already processed
if (zoom < b.zoom) {
var numPoints2 = b.numPoints || 1;
b.zoom = zoom; // save the zoom (so it doesn't get processed twice)
wx += b.x * numPoints2; // accumulate coordinates for calculating weighted center
wy += b.y * numPoints2;
numPoints += numPoints2;
b.parentId = i;
if (this.options.reduce) {
this._accumulate(clusterProperties, b);
}
}
}
if (numPoints === 1) {
clusters.push(p);
} else {
p.parentId = i;
clusters.push(createCluster(wx / numPoints, wy / numPoints, numPoints, i, clusterProperties));
}
}
return clusters;
},
_accumulate: function (clusterProperties, point) {
var properties = point.numPoints ?
point.properties :
this.options.map(this.points[point.id].properties);
this.options.reduce(clusterProperties, properties);
}
};
function createCluster(x, y, numPoints, id, properties) {
return {
x: x, // weighted cluster center
y: y,
zoom: Infinity, // the last zoom the cluster was processed at
id: id, // index of the first child of the cluster in the zoom level tree
properties: properties,
parentId: -1, // parent cluster id
numPoints: numPoints
};
}
function createPointCluster(p, id) {
var coords = p.geometry.coordinates;
return {
x: lngX(coords[0]), // projected point coordinates
y: latY(coords[1]),
zoom: Infinity, // the last zoom the point was processed at
id: id, // index of the source feature in the original input array
parentId: -1 // parent cluster id
};
}
function getClusterJSON(cluster) {
return {
type: 'Feature',
properties: getClusterProperties(cluster),
geometry: {
type: 'Point',
coordinates: [xLng(cluster.x), yLat(cluster.y)]
}
};
}
function getClusterProperties(cluster) {
var count = cluster.numPoints;
var abbrev = count >= 10000 ? Math.round(count / 1000) + 'k' :
count >= 1000 ? (Math.round(count / 100) / 10) + 'k' : count;
return extend(extend({}, cluster.properties), {
cluster: true,
cluster_id: cluster.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) {
var sin = Math.sin(lat * Math.PI / 180),
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) {
var y2 = (180 - y * 360) * Math.PI / 180;
return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
}
function extend(dest, src) {
for (var id in src) dest[id] = src[id];
return dest;
}
function getX(p) {
return p.x;
}
function getY(p) {
return p.y;
}
},{"kdbush":27}],35:[function(require,module,exports){
'use strict';
module.exports = TinyQueue;
function TinyQueue(data, compare) {
if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
this.data = data || [];
this.length = this.data.length;
this.compare = compare || defaultCompare;
if (this.length > 0) {
for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
}
}
function defaultCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
TinyQueue.prototype = {
push: function (item) {
this.data.push(item);
this.length++;
this._up(this.length - 1);
},
pop: function () {
if (this.length === 0) return undefined;
var top = this.data[0];
this.length--;
if (this.length > 0) {
this.data[0] = this.data[this.length];
this._down(0);
}
this.data.pop();
return top;
},
peek: function () {
return this.data[0];
},
_up: function (pos) {
var data = this.data;
var compare = this.compare;
var item = data[pos];
while (pos > 0) {
var parent = (pos - 1) >> 1;
var current = data[parent];
if (compare(item, current) >= 0) break;
data[pos] = current;
pos = parent;
}
data[pos] = item;
},
_down: function (pos) {
var data = this.data;
var compare = this.compare;
var len = this.length;
var halfLen = len >> 1;
var item = data[pos];
while (pos < halfLen) {
var left = (pos << 1) + 1;
var right = left + 1;
var best = data[left];
if (right < len && compare(data[right], best) < 0) {
left = right;
best = data[right];
}
if (compare(best, item) >= 0) break;
data[pos] = best;
pos = left;
}
data[pos] = item;
}
};
},{}],36:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],37:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],38:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":37,"_process":32,"inherits":36}],39:[function(require,module,exports){
var Pbf = require('pbf')
var GeoJSONWrapper = require('./lib/geojson_wrapper')
module.exports = fromVectorTileJs
module.exports.fromVectorTileJs = fromVectorTileJs
module.exports.fromGeojsonVt = fromGeojsonVt
module.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
* @return {Buffer} uncompressed, pbf-serialized tile data
*/
function fromGeojsonVt (layers) {
var l = {}
for (var k in layers) {
l[k] = new GeoJSONWrapper(layers[k].features)
l[k].name = k
}
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 keyIndex = keycache[key]
if (typeof keyIndex === 'undefined') {
keys.push(key)
keyIndex = keys.length - 1
keycache[key] = keyIndex
}
pbf.writeVarint(keyIndex)
var value = feature.properties[key]
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 & 0x7)
}
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
for (var i = 0; i < ring.length; i++) {
if (i === 1 && type !== 1) {
pbf.writeVarint(command(2, ring.length - 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
}
}
}
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)
}
}
}
},{"./lib/geojson_wrapper":40,"pbf":31}],40:[function(require,module,exports){
'use strict'
var Point = require('@mapbox/point-geometry')
var VectorTileFeature = require('@mapbox/vector-tile').VectorTileFeature
module.exports = GeoJSONWrapper
// conform to vectortile api
function GeoJSONWrapper (features) {
this.features = features
this.length = features.length
}
GeoJSONWrapper.prototype.feature = function (i) {
return new FeatureWrapper(this.features[i])
}
function FeatureWrapper (feature) {
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 = 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
},{"@mapbox/point-geometry":4,"@mapbox/vector-tile":8}],41:[function(require,module,exports){
var bundleFn = arguments[3];
var sources = arguments[4];
var cache = arguments[5];
var stringify = JSON.stringify;
module.exports = function (fn, options) {
var wkey;
var cacheKeys = Object.keys(cache);
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
var exp = cache[key].exports;
// Using babel as a transpiler to use esmodule, the export will always
// be an object with the default export as a property of it. To ensure
// the existing api and babel esmodule exports are both supported we
// check for both
if (exp === fn || exp && exp.default === fn) {
wkey = key;
break;
}
}
if (!wkey) {
wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var wcache = {};
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
wcache[key] = key;
}
sources[wkey] = [
'function(require,module,exports){' + fn + '(self); }',
wcache
];
}
var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var scache = {}; scache[wkey] = wkey;
sources[skey] = [
'function(require,module,exports){' +
// try to call default if defined to also support babel esmodule exports
'var f = require(' + stringify(wkey) + ');' +
'(f.default ? f.default : f)(self);' +
'}',
scache
];
var workerSources = {};
resolveSources(skey);
function resolveSources(key) {
workerSources[key] = true;
for (var depPath in sources[key][1]) {
var depKey = sources[key][1][depPath];
if (!workerSources[depKey]) {
resolveSources(depKey);
}
}
}
var src = '(' + bundleFn + ')({'
+ Object.keys(workerSources).map(function (key) {
return stringify(key) + ':['
+ sources[key][0]
+ ',' + stringify(sources[key][1]) + ']'
;
}).join(',')
+ '},{},[' + stringify(skey) + '])'
;
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
var blob = new Blob([src], { type: 'text/javascript' });
if (options && options.bare) { return blob; }
var workerUrl = URL.createObjectURL(blob);
var worker = new Worker(workerUrl);
worker.objectURL = workerUrl;
return worker;
};
},{}],42:[function(require,module,exports){
module.exports.RADIUS = 6378137;
module.exports.FLATTENING = 1/298.257223563;
module.exports.POLAR_RADIUS = 6356752.3142;
},{}],43:[function(require,module,exports){
module.exports={
"version": "0.44.0"
}
},{}],44:[function(require,module,exports){
'use strict';// This file is generated. Edit build/generate-struct-arrays.js, then run `yarn run codegen`.
//
var assert = require('assert');
var ref = require('../util/struct_array');
var StructArray = ref.StructArray;
var ref$1 = require('../util/struct_array');
var Struct = ref$1.Struct;
var ref$2 = require('../util/web_worker_transfer');
var register = ref$2.register;
var Point = require('@mapbox/point-geometry');
/**
* Implementation of the StructArray layout:
* [0]: Int16[2]
*
* @private
*/
var StructArrayLayout2i4 = (function (StructArray) {
function StructArrayLayout2i4 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2i4.__proto__ = StructArray;
StructArrayLayout2i4.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2i4.prototype.constructor = StructArrayLayout2i4;
StructArrayLayout2i4.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
};
StructArrayLayout2i4.prototype.emplaceBack = function emplaceBack (v0 , v1 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 2;
this.int16[o2 + 0] = v0;
this.int16[o2 + 1] = v1;
return i;
};
return StructArrayLayout2i4;
}(StructArray));
StructArrayLayout2i4.prototype.bytesPerElement = 4;
register('StructArrayLayout2i4', StructArrayLayout2i4);
/**
* Implementation of the StructArray layout:
* [0]: Int16[4]
*
* @private
*/
var StructArrayLayout4i8 = (function (StructArray) {
function StructArrayLayout4i8 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout4i8.__proto__ = StructArray;
StructArrayLayout4i8.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout4i8.prototype.constructor = StructArrayLayout4i8;
StructArrayLayout4i8.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
};
StructArrayLayout4i8.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 ) {
var i = this.length;
this.resize(i + 1);
var 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;
};
return StructArrayLayout4i8;
}(StructArray));
StructArrayLayout4i8.prototype.bytesPerElement = 8;
register('StructArrayLayout4i8', StructArrayLayout4i8);
/**
* Implementation of the StructArray layout:
* [0]: Int16[2]
* [4]: Int16[4]
*
* @private
*/
var StructArrayLayout2i4i12 = (function (StructArray) {
function StructArrayLayout2i4i12 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2i4i12.__proto__ = StructArray;
StructArrayLayout2i4i12.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2i4i12.prototype.constructor = StructArrayLayout2i4i12;
StructArrayLayout2i4i12.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
};
StructArrayLayout2i4i12.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 , v4 , v5 ) {
var i = this.length;
this.resize(i + 1);
var 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;
};
return StructArrayLayout2i4i12;
}(StructArray));
StructArrayLayout2i4i12.prototype.bytesPerElement = 12;
register('StructArrayLayout2i4i12', StructArrayLayout2i4i12);
/**
* Implementation of the StructArray layout:
* [0]: Int16[4]
* [8]: Uint8[4]
*
* @private
*/
var StructArrayLayout4i4ub12 = (function (StructArray) {
function StructArrayLayout4i4ub12 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout4i4ub12.__proto__ = StructArray;
StructArrayLayout4i4ub12.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout4i4ub12.prototype.constructor = StructArrayLayout4i4ub12;
StructArrayLayout4i4ub12.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
};
StructArrayLayout4i4ub12.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 , v4 , v5 , v6 , v7 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 6;
var o1 = i * 12;
this.int16[o2 + 0] = v0;
this.int16[o2 + 1] = v1;
this.int16[o2 + 2] = v2;
this.int16[o2 + 3] = v3;
this.uint8[o1 + 8] = v4;
this.uint8[o1 + 9] = v5;
this.uint8[o1 + 10] = v6;
this.uint8[o1 + 11] = v7;
return i;
};
return StructArrayLayout4i4ub12;
}(StructArray));
StructArrayLayout4i4ub12.prototype.bytesPerElement = 12;
register('StructArrayLayout4i4ub12', StructArrayLayout4i4ub12);
/**
* Implementation of the StructArray layout:
* [0]: Int16[4]
* [8]: Uint16[4]
*
* @private
*/
var StructArrayLayout4i4ui16 = (function (StructArray) {
function StructArrayLayout4i4ui16 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout4i4ui16.__proto__ = StructArray;
StructArrayLayout4i4ui16.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout4i4ui16.prototype.constructor = StructArrayLayout4i4ui16;
StructArrayLayout4i4ui16.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
this.uint16 = new Uint16Array(this.arrayBuffer);
};
StructArrayLayout4i4ui16.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 , v4 , v5 , v6 , v7 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 8;
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;
return i;
};
return StructArrayLayout4i4ui16;
}(StructArray));
StructArrayLayout4i4ui16.prototype.bytesPerElement = 16;
register('StructArrayLayout4i4ui16', StructArrayLayout4i4ui16);
/**
* Implementation of the StructArray layout:
* [0]: Float32[3]
*
* @private
*/
var StructArrayLayout3f12 = (function (StructArray) {
function StructArrayLayout3f12 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout3f12.__proto__ = StructArray;
StructArrayLayout3f12.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout3f12.prototype.constructor = StructArrayLayout3f12;
StructArrayLayout3f12.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.float32 = new Float32Array(this.arrayBuffer);
};
StructArrayLayout3f12.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 ) {
var i = this.length;
this.resize(i + 1);
var o4 = i * 3;
this.float32[o4 + 0] = v0;
this.float32[o4 + 1] = v1;
this.float32[o4 + 2] = v2;
return i;
};
return StructArrayLayout3f12;
}(StructArray));
StructArrayLayout3f12.prototype.bytesPerElement = 12;
register('StructArrayLayout3f12', StructArrayLayout3f12);
/**
* Implementation of the StructArray layout:
* [0]: Uint32[1]
*
* @private
*/
var StructArrayLayout1ul4 = (function (StructArray) {
function StructArrayLayout1ul4 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout1ul4.__proto__ = StructArray;
StructArrayLayout1ul4.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout1ul4.prototype.constructor = StructArrayLayout1ul4;
StructArrayLayout1ul4.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.uint32 = new Uint32Array(this.arrayBuffer);
};
StructArrayLayout1ul4.prototype.emplaceBack = function emplaceBack (v0 ) {
var i = this.length;
this.resize(i + 1);
var o4 = i * 1;
this.uint32[o4 + 0] = v0;
return i;
};
return StructArrayLayout1ul4;
}(StructArray));
StructArrayLayout1ul4.prototype.bytesPerElement = 4;
register('StructArrayLayout1ul4', StructArrayLayout1ul4);
/**
* Implementation of the StructArray layout:
* [0]: Int16[6]
* [12]: Uint32[1]
* [16]: Uint16[2]
* [20]: Int16[2]
*
* @private
*/
var StructArrayLayout6i1ul2ui2i24 = (function (StructArray) {
function StructArrayLayout6i1ul2ui2i24 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout6i1ul2ui2i24.__proto__ = StructArray;
StructArrayLayout6i1ul2ui2i24.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout6i1ul2ui2i24.prototype.constructor = StructArrayLayout6i1ul2ui2i24;
StructArrayLayout6i1ul2ui2i24.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
this.uint32 = new Uint32Array(this.arrayBuffer);
this.uint16 = new Uint16Array(this.arrayBuffer);
};
StructArrayLayout6i1ul2ui2i24.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 , v4 , v5 , v6 , v7 , v8 , v9 , v10 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 12;
var o4 = 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;
this.uint32[o4 + 3] = v6;
this.uint16[o2 + 8] = v7;
this.uint16[o2 + 9] = v8;
this.int16[o2 + 10] = v9;
this.int16[o2 + 11] = v10;
return i;
};
return StructArrayLayout6i1ul2ui2i24;
}(StructArray));
StructArrayLayout6i1ul2ui2i24.prototype.bytesPerElement = 24;
register('StructArrayLayout6i1ul2ui2i24', StructArrayLayout6i1ul2ui2i24);
/**
* Implementation of the StructArray layout:
* [0]: Int16[2]
* [4]: Int16[2]
* [8]: Int16[2]
*
* @private
*/
var StructArrayLayout2i2i2i12 = (function (StructArray) {
function StructArrayLayout2i2i2i12 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2i2i2i12.__proto__ = StructArray;
StructArrayLayout2i2i2i12.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2i2i2i12.prototype.constructor = StructArrayLayout2i2i2i12;
StructArrayLayout2i2i2i12.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
};
StructArrayLayout2i2i2i12.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 , v4 , v5 ) {
var i = this.length;
this.resize(i + 1);
var 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;
};
return StructArrayLayout2i2i2i12;
}(StructArray));
StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12;
register('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12);
/**
* Implementation of the StructArray layout:
* [0]: Uint8[2]
*
* @private
*/
var StructArrayLayout2ub4 = (function (StructArray) {
function StructArrayLayout2ub4 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2ub4.__proto__ = StructArray;
StructArrayLayout2ub4.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2ub4.prototype.constructor = StructArrayLayout2ub4;
StructArrayLayout2ub4.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
};
StructArrayLayout2ub4.prototype.emplaceBack = function emplaceBack (v0 , v1 ) {
var i = this.length;
this.resize(i + 1);
var o1 = i * 4;
this.uint8[o1 + 0] = v0;
this.uint8[o1 + 1] = v1;
return i;
};
return StructArrayLayout2ub4;
}(StructArray));
StructArrayLayout2ub4.prototype.bytesPerElement = 4;
register('StructArrayLayout2ub4', StructArrayLayout2ub4);
/**
* Implementation of the StructArray layout:
* [0]: Int16[2]
* [4]: Uint16[2]
* [8]: Uint32[3]
* [20]: Uint16[3]
* [28]: Float32[2]
* [36]: Uint8[2]
*
* @private
*/
var StructArrayLayout2i2ui3ul3ui2f2ub40 = (function (StructArray) {
function StructArrayLayout2i2ui3ul3ui2f2ub40 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2i2ui3ul3ui2f2ub40.__proto__ = StructArray;
StructArrayLayout2i2ui3ul3ui2f2ub40.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2i2ui3ul3ui2f2ub40.prototype.constructor = StructArrayLayout2i2ui3ul3ui2f2ub40;
StructArrayLayout2i2ui3ul3ui2f2ub40.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
this.uint16 = new Uint16Array(this.arrayBuffer);
this.uint32 = new Uint32Array(this.arrayBuffer);
this.float32 = new Float32Array(this.arrayBuffer);
};
StructArrayLayout2i2ui3ul3ui2f2ub40.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 , v4 , v5 , v6 , v7 , v8 , v9 , v10 , v11 , v12 , v13 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 20;
var o4 = i * 10;
var o1 = i * 40;
this.int16[o2 + 0] = v0;
this.int16[o2 + 1] = v1;
this.uint16[o2 + 2] = v2;
this.uint16[o2 + 3] = v3;
this.uint32[o4 + 2] = v4;
this.uint32[o4 + 3] = v5;
this.uint32[o4 + 4] = v6;
this.uint16[o2 + 10] = v7;
this.uint16[o2 + 11] = v8;
this.uint16[o2 + 12] = v9;
this.float32[o4 + 7] = v10;
this.float32[o4 + 8] = v11;
this.uint8[o1 + 36] = v12;
this.uint8[o1 + 37] = v13;
return i;
};
return StructArrayLayout2i2ui3ul3ui2f2ub40;
}(StructArray));
StructArrayLayout2i2ui3ul3ui2f2ub40.prototype.bytesPerElement = 40;
register('StructArrayLayout2i2ui3ul3ui2f2ub40', StructArrayLayout2i2ui3ul3ui2f2ub40);
/**
* Implementation of the StructArray layout:
* [0]: Float32[1]
*
* @private
*/
var StructArrayLayout1f4 = (function (StructArray) {
function StructArrayLayout1f4 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout1f4.__proto__ = StructArray;
StructArrayLayout1f4.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout1f4.prototype.constructor = StructArrayLayout1f4;
StructArrayLayout1f4.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.float32 = new Float32Array(this.arrayBuffer);
};
StructArrayLayout1f4.prototype.emplaceBack = function emplaceBack (v0 ) {
var i = this.length;
this.resize(i + 1);
var o4 = i * 1;
this.float32[o4 + 0] = v0;
return i;
};
return StructArrayLayout1f4;
}(StructArray));
StructArrayLayout1f4.prototype.bytesPerElement = 4;
register('StructArrayLayout1f4', StructArrayLayout1f4);
/**
* Implementation of the StructArray layout:
* [0]: Int16[3]
*
* @private
*/
var StructArrayLayout3i6 = (function (StructArray) {
function StructArrayLayout3i6 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout3i6.__proto__ = StructArray;
StructArrayLayout3i6.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout3i6.prototype.constructor = StructArrayLayout3i6;
StructArrayLayout3i6.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.int16 = new Int16Array(this.arrayBuffer);
};
StructArrayLayout3i6.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 3;
this.int16[o2 + 0] = v0;
this.int16[o2 + 1] = v1;
this.int16[o2 + 2] = v2;
return i;
};
return StructArrayLayout3i6;
}(StructArray));
StructArrayLayout3i6.prototype.bytesPerElement = 6;
register('StructArrayLayout3i6', StructArrayLayout3i6);
/**
* Implementation of the StructArray layout:
* [0]: Uint32[1]
* [4]: Uint16[2]
*
* @private
*/
var StructArrayLayout1ul2ui8 = (function (StructArray) {
function StructArrayLayout1ul2ui8 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout1ul2ui8.__proto__ = StructArray;
StructArrayLayout1ul2ui8.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout1ul2ui8.prototype.constructor = StructArrayLayout1ul2ui8;
StructArrayLayout1ul2ui8.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.uint32 = new Uint32Array(this.arrayBuffer);
this.uint16 = new Uint16Array(this.arrayBuffer);
};
StructArrayLayout1ul2ui8.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 ) {
var i = this.length;
this.resize(i + 1);
var o4 = i * 2;
var o2 = i * 4;
this.uint32[o4 + 0] = v0;
this.uint16[o2 + 2] = v1;
this.uint16[o2 + 3] = v2;
return i;
};
return StructArrayLayout1ul2ui8;
}(StructArray));
StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8;
register('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8);
/**
* Implementation of the StructArray layout:
* [0]: Uint16[3]
*
* @private
*/
var StructArrayLayout3ui6 = (function (StructArray) {
function StructArrayLayout3ui6 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout3ui6.__proto__ = StructArray;
StructArrayLayout3ui6.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout3ui6.prototype.constructor = StructArrayLayout3ui6;
StructArrayLayout3ui6.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.uint16 = new Uint16Array(this.arrayBuffer);
};
StructArrayLayout3ui6.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 3;
this.uint16[o2 + 0] = v0;
this.uint16[o2 + 1] = v1;
this.uint16[o2 + 2] = v2;
return i;
};
return StructArrayLayout3ui6;
}(StructArray));
StructArrayLayout3ui6.prototype.bytesPerElement = 6;
register('StructArrayLayout3ui6', StructArrayLayout3ui6);
/**
* Implementation of the StructArray layout:
* [0]: Uint16[2]
*
* @private
*/
var StructArrayLayout2ui4 = (function (StructArray) {
function StructArrayLayout2ui4 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2ui4.__proto__ = StructArray;
StructArrayLayout2ui4.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2ui4.prototype.constructor = StructArrayLayout2ui4;
StructArrayLayout2ui4.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.uint16 = new Uint16Array(this.arrayBuffer);
};
StructArrayLayout2ui4.prototype.emplaceBack = function emplaceBack (v0 , v1 ) {
var i = this.length;
this.resize(i + 1);
var o2 = i * 2;
this.uint16[o2 + 0] = v0;
this.uint16[o2 + 1] = v1;
return i;
};
return StructArrayLayout2ui4;
}(StructArray));
StructArrayLayout2ui4.prototype.bytesPerElement = 4;
register('StructArrayLayout2ui4', StructArrayLayout2ui4);
/**
* Implementation of the StructArray layout:
* [0]: Float32[2]
*
* @private
*/
var StructArrayLayout2f8 = (function (StructArray) {
function StructArrayLayout2f8 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout2f8.__proto__ = StructArray;
StructArrayLayout2f8.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout2f8.prototype.constructor = StructArrayLayout2f8;
StructArrayLayout2f8.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.float32 = new Float32Array(this.arrayBuffer);
};
StructArrayLayout2f8.prototype.emplaceBack = function emplaceBack (v0 , v1 ) {
var i = this.length;
this.resize(i + 1);
var o4 = i * 2;
this.float32[o4 + 0] = v0;
this.float32[o4 + 1] = v1;
return i;
};
return StructArrayLayout2f8;
}(StructArray));
StructArrayLayout2f8.prototype.bytesPerElement = 8;
register('StructArrayLayout2f8', StructArrayLayout2f8);
/**
* Implementation of the StructArray layout:
* [0]: Float32[4]
*
* @private
*/
var StructArrayLayout4f16 = (function (StructArray) {
function StructArrayLayout4f16 () {
StructArray.apply(this, arguments);
}
if ( StructArray ) StructArrayLayout4f16.__proto__ = StructArray;
StructArrayLayout4f16.prototype = Object.create( StructArray && StructArray.prototype );
StructArrayLayout4f16.prototype.constructor = StructArrayLayout4f16;
StructArrayLayout4f16.prototype._refreshViews = function _refreshViews () {
this.uint8 = new Uint8Array(this.arrayBuffer);
this.float32 = new Float32Array(this.arrayBuffer);
};
StructArrayLayout4f16.prototype.emplaceBack = function emplaceBack (v0 , v1 , v2 , v3 ) {
var i = this.length;
this.resize(i + 1);
var 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;
};
return StructArrayLayout4f16;
}(StructArray));
StructArrayLayout4f16.prototype.bytesPerElement = 16;
register('StructArrayLayout4f16', StructArrayLayout4f16);
var CollisionBoxStruct = (function (Struct) {
function CollisionBoxStruct () {
Struct.apply(this, arguments);
}
if ( Struct ) CollisionBoxStruct.__proto__ = Struct;
CollisionBoxStruct.prototype = Object.create( Struct && Struct.prototype );
CollisionBoxStruct.prototype.constructor = CollisionBoxStruct;
var prototypeAccessors = { anchorPointX: {},anchorPointY: {},x1: {},y1: {},x2: {},y2: {},featureIndex: {},sourceLayerIndex: {},bucketIndex: {},radius: {},signedDistanceFromAnchor: {},anchorPoint: {} };
prototypeAccessors.anchorPointX.get = function () { return this._structArray.int16[this._pos2 + 0]; };
prototypeAccessors.anchorPointX.set = function (x) { this._structArray.int16[this._pos2 + 0] = x; };
prototypeAccessors.anchorPointY.get = function () { return this._structArray.int16[this._pos2 + 1]; };
prototypeAccessors.anchorPointY.set = function (x) { this._structArray.int16[this._pos2 + 1] = x; };
prototypeAccessors.x1.get = function () { return this._structArray.int16[this._pos2 + 2]; };
prototypeAccessors.x1.set = function (x) { this._structArray.int16[this._pos2 + 2] = x; };
prototypeAccessors.y1.get = function () { return this._structArray.int16[this._pos2 + 3]; };
prototypeAccessors.y1.set = function (x) { this._structArray.int16[this._pos2 + 3] = x; };
prototypeAccessors.x2.get = function () { return this._structArray.int16[this._pos2 + 4]; };
prototypeAccessors.x2.set = function (x) { this._structArray.int16[this._pos2 + 4] = x; };
prototypeAccessors.y2.get = function () { return this._structArray.int16[this._pos2 + 5]; };
prototypeAccessors.y2.set = function (x) { this._structArray.int16[this._pos2 + 5] = x; };
prototypeAccessors.featureIndex.get = function () { return this._structArray.uint32[this._pos4 + 3]; };
prototypeAccessors.featureIndex.set = function (x) { this._structArray.uint32[this._pos4 + 3] = x; };
prototypeAccessors.sourceLayerIndex.get = function () { return this._structArray.uint16[this._pos2 + 8]; };
prototypeAccessors.sourceLayerIndex.set = function (x) { this._structArray.uint16[this._pos2 + 8] = x; };
prototypeAccessors.bucketIndex.get = function () { return this._structArray.uint16[this._pos2 + 9]; };
prototypeAccessors.bucketIndex.set = function (x) { this._structArray.uint16[this._pos2 + 9] = x; };
prototypeAccessors.radius.get = function () { return this._structArray.int16[this._pos2 + 10]; };
prototypeAccessors.radius.set = function (x) { this._structArray.int16[this._pos2 + 10] = x; };
prototypeAccessors.signedDistanceFromAnchor.get = function () { return this._structArray.int16[this._pos2 + 11]; };
prototypeAccessors.signedDistanceFromAnchor.set = function (x) { this._structArray.int16[this._pos2 + 11] = x; };
prototypeAccessors.anchorPoint.get = function () { return new Point(this.anchorPointX, this.anchorPointY); };
Object.defineProperties( CollisionBoxStruct.prototype, prototypeAccessors );
return CollisionBoxStruct;
}(Struct));
CollisionBoxStruct.prototype.size = 24;
/**
* @private
*/
var CollisionBoxArray = (function (StructArrayLayout6i1ul2ui2i24) {
function CollisionBoxArray () {
StructArrayLayout6i1ul2ui2i24.apply(this, arguments);
}
if ( StructArrayLayout6i1ul2ui2i24 ) CollisionBoxArray.__proto__ = StructArrayLayout6i1ul2ui2i24;
CollisionBoxArray.prototype = Object.create( StructArrayLayout6i1ul2ui2i24 && StructArrayLayout6i1ul2ui2i24.prototype );
CollisionBoxArray.prototype.constructor = CollisionBoxArray;
CollisionBoxArray.prototype.get = function get (index ) {
assert(!this.isTransferred);
return new CollisionBoxStruct(this, index);
};
return CollisionBoxArray;
}(StructArrayLayout6i1ul2ui2i24));
register('CollisionBoxArray', CollisionBoxArray);
var PlacedSymbolStruct = (function (Struct) {
function PlacedSymbolStruct () {
Struct.apply(this, arguments);
}
if ( Struct ) PlacedSymbolStruct.__proto__ = Struct;
PlacedSymbolStruct.prototype = Object.create( Struct && Struct.prototype );
PlacedSymbolStruct.prototype.constructor = PlacedSymbolStruct;
var prototypeAccessors$1 = { anchorX: {},anchorY: {},glyphStartIndex: {},numGlyphs: {},vertexStartIndex: {},lineStartIndex: {},lineLength: {},segment: {},lowerSize: {},upperSize: {},lineOffsetX: {},lineOffsetY: {},writingMode: {},hidden: {} };
prototypeAccessors$1.anchorX.get = function () { return this._structArray.int16[this._pos2 + 0]; };
prototypeAccessors$1.anchorX.set = function (x) { this._structArray.int16[this._pos2 + 0] = x; };
prototypeAccessors$1.anchorY.get = function () { return this._structArray.int16[this._pos2 + 1]; };
prototypeAccessors$1.anchorY.set = function (x) { this._structArray.int16[this._pos2 + 1] = x; };
prototypeAccessors$1.glyphStartIndex.get = function () { return this._structArray.uint16[this._pos2 + 2]; };
prototypeAccessors$1.glyphStartIndex.set = function (x) { this._structArray.uint16[this._pos2 + 2] = x; };
prototypeAccessors$1.numGlyphs.get = function () { return this._structArray.uint16[this._pos2 + 3]; };
prototypeAccessors$1.numGlyphs.set = function (x) { this._structArray.uint16[this._pos2 + 3] = x; };
prototypeAccessors$1.vertexStartIndex.get = function () { return this._structArray.uint32[this._pos4 + 2]; };
prototypeAccessors$1.vertexStartIndex.set = function (x) { this._structArray.uint32[this._pos4 + 2] = x; };
prototypeAccessors$1.lineStartIndex.get = function () { return this._structArray.uint32[this._pos4 + 3]; };
prototypeAccessors$1.lineStartIndex.set = function (x) { this._structArray.uint32[this._pos4 + 3] = x; };
prototypeAccessors$1.lineLength.get = function () { return this._structArray.uint32[this._pos4 + 4]; };
prototypeAccessors$1.lineLength.set = function (x) { this._structArray.uint32[this._pos4 + 4] = x; };
prototypeAccessors$1.segment.get = function () { return this._structArray.uint16[this._pos2 + 10]; };
prototypeAccessors$1.segment.set = function (x) { this._structArray.uint16[this._pos2 + 10] = x; };
prototypeAccessors$1.lowerSize.get = function () { return this._structArray.uint16[this._pos2 + 11]; };
prototypeAccessors$1.lowerSize.set = function (x) { this._structArray.uint16[this._pos2 + 11] = x; };
prototypeAccessors$1.upperSize.get = function () { return this._structArray.uint16[this._pos2 + 12]; };
prototypeAccessors$1.upperSize.set = function (x) { this._structArray.uint16[this._pos2 + 12] = x; };
prototypeAccessors$1.lineOffsetX.get = function () { return this._structArray.float32[this._pos4 + 7]; };
prototypeAccessors$1.lineOffsetX.set = function (x) { this._structArray.float32[this._pos4 + 7] = x; };
prototypeAccessors$1.lineOffsetY.get = function () { return this._structArray.float32[this._pos4 + 8]; };
prototypeAccessors$1.lineOffsetY.set = function (x) { this._structArray.float32[this._pos4 + 8] = x; };
prototypeAccessors$1.writingMode.get = function () { return this._structArray.uint8[this._pos1 + 36]; };
prototypeAccessors$1.writingMode.set = function (x) { this._structArray.uint8[this._pos1 + 36] = x; };
prototypeAccessors$1.hidden.get = function () { return this._structArray.uint8[this._pos1 + 37]; };
prototypeAccessors$1.hidden.set = function (x) { this._structArray.uint8[this._pos1 + 37] = x; };
Object.defineProperties( PlacedSymbolStruct.prototype, prototypeAccessors$1 );
return PlacedSymbolStruct;
}(Struct));
PlacedSymbolStruct.prototype.size = 40;
/**
* @private
*/
var PlacedSymbolArray = (function (StructArrayLayout2i2ui3ul3ui2f2ub40) {
function PlacedSymbolArray () {
StructArrayLayout2i2ui3ul3ui2f2ub40.apply(this, arguments);
}
if ( StructArrayLayout2i2ui3ul3ui2f2ub40 ) PlacedSymbolArray.__proto__ = StructArrayLayout2i2ui3ul3ui2f2ub40;
PlacedSymbolArray.prototype = Object.create( StructArrayLayout2i2ui3ul3ui2f2ub40 && StructArrayLayout2i2ui3ul3ui2f2ub40.prototype );
PlacedSymbolArray.prototype.constructor = PlacedSymbolArray;
PlacedSymbolArray.prototype.get = function get (index ) {
assert(!this.isTransferred);
return new PlacedSymbolStruct(this, index);
};
return PlacedSymbolArray;
}(StructArrayLayout2i2ui3ul3ui2f2ub40));
register('PlacedSymbolArray', PlacedSymbolArray);
var GlyphOffsetStruct = (function (Struct) {
function GlyphOffsetStruct () {
Struct.apply(this, arguments);
}
if ( Struct ) GlyphOffsetStruct.__proto__ = Struct;
GlyphOffsetStruct.prototype = Object.create( Struct && Struct.prototype );
GlyphOffsetStruct.prototype.constructor = GlyphOffsetStruct;
var prototypeAccessors$2 = { offsetX: {} };
prototypeAccessors$2.offsetX.get = function () { return this._structArray.float32[this._pos4 + 0]; };
prototypeAccessors$2.offsetX.set = function (x) { this._structArray.float32[this._pos4 + 0] = x; };
Object.defineProperties( GlyphOffsetStruct.prototype, prototypeAccessors$2 );
return GlyphOffsetStruct;
}(Struct));
GlyphOffsetStruct.prototype.size = 4;
/**
* @private
*/
var GlyphOffsetArray = (function (StructArrayLayout1f4) {
function GlyphOffsetArray () {
StructArrayLayout1f4.apply(this, arguments);
}
if ( StructArrayLayout1f4 ) GlyphOffsetArray.__proto__ = StructArrayLayout1f4;
GlyphOffsetArray.prototype = Object.create( StructArrayLayout1f4 && StructArrayLayout1f4.prototype );
GlyphOffsetArray.prototype.constructor = GlyphOffsetArray;
GlyphOffsetArray.prototype.getoffsetX = function getoffsetX (index ) { return this.float32[index * 1 + 0]; };
/**
* Return the GlyphOffsetStruct at the given location in the array.
* @param {number} index The index of the element.
*/
GlyphOffsetArray.prototype.get = function get (index ) {
assert(!this.isTransferred);
return new GlyphOffsetStruct(this, index);
};
return GlyphOffsetArray;
}(StructArrayLayout1f4));
register('GlyphOffsetArray', GlyphOffsetArray);
var SymbolLineVertexStruct = (function (Struct) {
function SymbolLineVertexStruct () {
Struct.apply(this, arguments);
}
if ( Struct ) SymbolLineVertexStruct.__proto__ = Struct;
SymbolLineVertexStruct.prototype = Object.create( Struct && Struct.prototype );
SymbolLineVertexStruct.prototype.constructor = SymbolLineVertexStruct;
var prototypeAccessors$3 = { x: {},y: {},tileUnitDistanceFromAnchor: {} };
prototypeAccessors$3.x.get = function () { return this._structArray.int16[this._pos2 + 0]; };
prototypeAccessors$3.x.set = function (x) { this._structArray.int16[this._pos2 + 0] = x; };
prototypeAccessors$3.y.get = function () { return this._structArray.int16[this._pos2 + 1]; };
prototypeAccessors$3.y.set = function (x) { this._structArray.int16[this._pos2 + 1] = x; };
prototypeAccessors$3.tileUnitDistanceFromAnchor.get = function () { return this._structArray.int16[this._pos2 + 2]; };
prototypeAccessors$3.tileUnitDistanceFromAnchor.set = function (x) { this._structArray.int16[this._pos2 + 2] = x; };
Object.defineProperties( SymbolLineVertexStruct.prototype, prototypeAccessors$3 );
return SymbolLineVertexStruct;
}(Struct));
SymbolLineVertexStruct.prototype.size = 6;
/**
* @private
*/
var SymbolLineVertexArray = (function (StructArrayLayout3i6) {
function SymbolLineVertexArray () {
StructArrayLayout3i6.apply(this, arguments);
}
if ( StructArrayLayout3i6 ) SymbolLineVertexArray.__proto__ = StructArrayLayout3i6;
SymbolLineVertexArray.prototype = Object.create( StructArrayLayout3i6 && StructArrayLayout3i6.prototype );
SymbolLineVertexArray.prototype.constructor = SymbolLineVertexArray;
SymbolLineVertexArray.prototype.getx = function getx (index ) { return this.int16[index * 3 + 0]; };
SymbolLineVertexArray.prototype.gety = function gety (index ) { return this.int16[index * 3 + 1]; };
SymbolLineVertexArray.prototype.gettileUnitDistanceFromAnchor = function gettileUnitDistanceFromAnchor (index ) { return this.int16[index * 3 + 2]; };
/**
* Return the SymbolLineVertexStruct at the given location in the array.
* @param {number} index The index of the element.
*/
SymbolLineVertexArray.prototype.get = function get (index ) {
assert(!this.isTransferred);
return new SymbolLineVertexStruct(this, index);
};
return SymbolLineVertexArray;
}(StructArrayLayout3i6));
register('SymbolLineVertexArray', SymbolLineVertexArray);
var FeatureIndexStruct = (function (Struct) {
function FeatureIndexStruct () {
Struct.apply(this, arguments);
}
if ( Struct ) FeatureIndexStruct.__proto__ = Struct;
FeatureIndexStruct.prototype = Object.create( Struct && Struct.prototype );
FeatureIndexStruct.prototype.constructor = FeatureIndexStruct;
var prototypeAccessors$4 = { featureIndex: {},sourceLayerIndex: {},bucketIndex: {} };
prototypeAccessors$4.featureIndex.get = function () { return this._structArray.uint32[this._pos4 + 0]; };
prototypeAccessors$4.featureIndex.set = function (x) { this._structArray.uint32[this._pos4 + 0] = x; };
prototypeAccessors$4.sourceLayerIndex.get = function () { return this._structArray.uint16[this._pos2 + 2]; };
prototypeAccessors$4.sourceLayerIndex.set = function (x) { this._structArray.uint16[this._pos2 + 2] = x; };
prototypeAccessors$4.bucketIndex.get = function () { return this._structArray.uint16[this._pos2 + 3]; };
prototypeAccessors$4.bucketIndex.set = function (x) { this._structArray.uint16[this._pos2 + 3] = x; };
Object.defineProperties( FeatureIndexStruct.prototype, prototypeAccessors$4 );
return FeatureIndexStruct;
}(Struct));
FeatureIndexStruct.prototype.size = 8;
/**
* @private
*/
var FeatureIndexArray = (function (StructArrayLayout1ul2ui8) {
function FeatureIndexArray () {
StructArrayLayout1ul2ui8.apply(this, arguments);
}
if ( StructArrayLayout1ul2ui8 ) FeatureIndexArray.__proto__ = StructArrayLayout1ul2ui8;
FeatureIndexArray.prototype = Object.create( StructArrayLayout1ul2ui8 && StructArrayLayout1ul2ui8.prototype );
FeatureIndexArray.prototype.constructor = FeatureIndexArray;
FeatureIndexArray.prototype.get = function get (index ) {
assert(!this.isTransferred);
return new FeatureIndexStruct(this, index);
};
return FeatureIndexArray;
}(StructArrayLayout1ul2ui8));
register('FeatureIndexArray', FeatureIndexArray);
module.exports = {
StructArrayLayout2i4: StructArrayLayout2i4,
StructArrayLayout4i8: StructArrayLayout4i8,
StructArrayLayout2i4i12: StructArrayLayout2i4i12,
StructArrayLayout4i4ub12: StructArrayLayout4i4ub12,
StructArrayLayout4i4ui16: StructArrayLayout4i4ui16,
StructArrayLayout3f12: StructArrayLayout3f12,
StructArrayLayout1ul4: StructArrayLayout1ul4,
StructArrayLayout6i1ul2ui2i24: StructArrayLayout6i1ul2ui2i24,
StructArrayLayout2i2i2i12: StructArrayLayout2i2i2i12,
StructArrayLayout2ub4: StructArrayLayout2ub4,
StructArrayLayout2i2ui3ul3ui2f2ub40: StructArrayLayout2i2ui3ul3ui2f2ub40,
StructArrayLayout1f4: StructArrayLayout1f4,
StructArrayLayout3i6: StructArrayLayout3i6,
StructArrayLayout1ul2ui8: StructArrayLayout1ul2ui8,
StructArrayLayout3ui6: StructArrayLayout3ui6,
StructArrayLayout2ui4: StructArrayLayout2ui4,
StructArrayLayout2f8: StructArrayLayout2f8,
StructArrayLayout4f16: StructArrayLayout4f16,
PosArray: StructArrayLayout2i4,
RasterBoundsArray: StructArrayLayout4i8,
CircleLayoutArray: StructArrayLayout2i4,
FillLayoutArray: StructArrayLayout2i4,
FillExtrusionLayoutArray: StructArrayLayout2i4i12,
HeatmapLayoutArray: StructArrayLayout2i4,
LineLayoutArray: StructArrayLayout4i4ub12,
SymbolLayoutArray: StructArrayLayout4i4ui16,
SymbolDynamicLayoutArray: StructArrayLayout3f12,
SymbolOpacityArray: StructArrayLayout1ul4,
CollisionBoxLayoutArray: StructArrayLayout2i2i2i12,
CollisionCircleLayoutArray: StructArrayLayout2i2i2i12,
CollisionVertexArray: StructArrayLayout2ub4,
TriangleIndexArray: StructArrayLayout3ui6,
LineIndexArray: StructArrayLayout2ui4,
CollisionBoxArray: CollisionBoxArray,
PlacedSymbolArray: PlacedSymbolArray,
GlyphOffsetArray: GlyphOffsetArray,
SymbolLineVertexArray: SymbolLineVertexArray,
FeatureIndexArray: FeatureIndexArray
};
},{"../util/struct_array":279,"../util/web_worker_transfer":286,"@mapbox/point-geometry":4,"assert":13}],45:[function(require,module,exports){
'use strict';//
/**
* The `Bucket` interface is the single point of knowledge about turning vector
* tiles into WebGL buffers.
*
* `Bucket` is an abstract interface. An implementation exists for each style layer type.
* Create a bucket via the `StyleLayer#createBucket` method.
*
* The concrete bucket types, using layout options from the style layer,
* transform feature geometries into vertex and index data for use by the
* vertex shader. They also (via `ProgramConfiguration`) use feature
* properties and the zoom level to populate the attributes needed for
* data-driven styling.
*
* Buckets are designed to be built on a worker thread and then serialized and
* transferred back to the main thread for rendering. On the worker side, a
* bucket's vertex, index, and attribute data is stored in `bucket.arrays:
* ArrayGroup`. When a bucket's data is serialized and sent back to the main
* thread, is gets deserialized (using `new Bucket(serializedBucketData)`, with
* the array data now stored in `bucket.buffers: BufferGroup`. BufferGroups
* hold the same data as ArrayGroups, but are tuned for consumption by WebGL.
*
* @private
*/
module.exports = {
deserialize: function deserialize(input , style ) {
var output = {};
// Guard against the case where the map's style has been set to null while
// this bucket has been parsing.
if (!style) { return output; }
for (var i = 0, list = input; i < list.length; i += 1) {
var bucket = list[i];
var layers = bucket.layerIds
.map(function (id) { return style.getLayer(id); })
.filter(Boolean);
if (layers.length === 0) {
continue;
}
// look up StyleLayer objects from layer ids (since we don't
// want to waste time serializing/copying them from the worker)
(bucket ).layers = layers;
for (var i$1 = 0, list$1 = layers; i$1 < list$1.length; i$1 += 1) {
var layer = list$1[i$1];
output[layer.id] = bucket;
}
}
return output;
}
};
},{}],46:[function(require,module,exports){
'use strict';//
var ref = require('../../util/struct_array');
var createLayout = ref.createLayout;
module.exports = createLayout([
{name: 'a_pos', components: 2, type: 'Int16'}
], 4);
},{"../../util/struct_array":279}],47:[function(require,module,exports){
'use strict';//
var ref = require('../array_types');
var CircleLayoutArray = ref.CircleLayoutArray;
var layoutAttributes = require('./circle_attributes').members;
var ref$1 = require('../segment');
var SegmentVector = ref$1.SegmentVector;
var ref$2 = require('../program_configuration');
var ProgramConfigurationSet = ref$2.ProgramConfigurationSet;
var ref$3 = require('../index_array_type');
var TriangleIndexArray = ref$3.TriangleIndexArray;
var loadGeometry = require('../load_geometry');
var EXTENT = require('../extent');
var ref$4 = require('../../util/web_worker_transfer');
var register = ref$4.register;
function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {
layoutVertexArray.emplaceBack(
(x * 2) + ((extrudeX + 1) / 2),
(y * 2) + ((extrudeY + 1) / 2));
}
/**
* Circles are represented by two triangles.
*
* Each corner has a pos that is the center of the circle and an extrusion
* vector that is where it points.
* @private
*/
var CircleBucket = function CircleBucket(options ) {
this.zoom = options.zoom;
this.overscaling = options.overscaling;
this.layers = options.layers;
this.layerIds = this.layers.map(function (layer) { return layer.id; });
this.index = options.index;
this.layoutVertexArray = new CircleLayoutArray();
this.indexArray = new TriangleIndexArray();
this.segments = new SegmentVector();
this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, options.layers, options.zoom);
};
CircleBucket.prototype.populate = function populate (features , options ) {
var this$1 = this;
for (var i = 0, list = features; i < list.length; i += 1) {
var ref = list[i];
var feature = ref.feature;
var index = ref.index;
var sourceLayerIndex = ref.sourceLayerIndex;
if (this$1.layers[0]._featureFilter({zoom: this$1.zoom}, feature)) {
var geometry = loadGeometry(feature);
this$1.addFeature(feature, geometry);
options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this$1.index);
}
}
};
CircleBucket.prototype.isEmpty = function isEmpty () {
return this.layoutVertexArray.length === 0;
};
CircleBucket.prototype.upload = function upload (context ) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);
this.indexBuffer = context.createIndexBuffer(this.indexArray);
this.programConfigurations.upload(context);
};
CircleBucket.prototype.destroy = function destroy () {
if (!this.layoutVertexBuffer) { return; }
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.programConfigurations.destroy();
this.segments.destroy();
};
CircleBucket.prototype.addFeature = function addFeature (feature , geometry ) {
var this$1 = this;
for (var i = 0, list = geometry; i < list.length; i += 1) {
var ring = list[i];
for (var i$1 = 0, list$1 = ring; i$1 < list$1.length; i$1 += 1) {
var point = list$1[i$1];
var x = point.x;
var y = point.y;
// Do not include points that are outside the tile boundaries.
if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) { continue; }
// this geometry will be of the Point type, and we'll derive
// two triangles from it.
//
// ┌─────────┐
// │ 3 2 │
// │ │
// │ 0 1 │
// └─────────┘
var segment = this$1.segments.prepareSegment(4, this$1.layoutVertexArray, this$1.indexArray);
var index = segment.vertexLength;
addCircleVertex(this$1.layoutVertexArray, x, y, -1, -1);
addCircleVertex(this$1.layoutVertexArray, x, y, 1, -1);
addCircleVertex(this$1.layoutVertexArray, x, y, 1, 1);
addCircleVertex(this$1.layoutVertexArray, x, y, -1, 1);
this$1.indexArray.emplaceBack(index, index + 1, index + 2);
this$1.indexArray.emplaceBack(index, index + 3, index + 2);
segment.vertexLength += 4;
segment.primitiveLength += 2;
}
}
this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature);
};
register('CircleBucket', CircleBucket, {omit: ['layers']});
module.exports = CircleBucket;
},{"../../util/web_worker_transfer":286,"../array_types":44,"../extent":58,"../index_array_type":60,"../load_geometry":61,"../program_configuration":63,"../segment":65,"./circle_attributes":46}],48:[function(require,module,exports){
'use strict';//
var ref = require('../../util/struct_array');
var createLayout = ref.createLayout;
module.exports = createLayout([
{name: 'a_pos', components: 2, type: 'Int16'}
], 4);
},{"../../util/struct_array":279}],49:[function(require,module,exports){
'use strict';//
var ref = require('../array_types');
var FillLayoutArray = ref.FillLayoutArray;
var layoutAttributes = require('./fill_attributes').members;
var ref$1 = require('../segment');
var SegmentVector = ref$1.SegmentVector;
var ref$2 = require('../program_configuration');
var ProgramConfigurationSet = ref$2.ProgramConfigurationSet;
var ref$3 = require('../index_array_type');
var LineIndexArray = ref$3.LineIndexArray;
var TriangleIndexArray = ref$3.TriangleIndexArray;
var loadGeometry = require('../load_geometry');
var earcut = require('earcut');
var classifyRings = require('../../util/classify_rings');
var assert = require('assert');
var EARCUT_MAX_RINGS = 500;
var ref$4 = require('../../util/web_worker_transfer');
var register = ref$4.register;
var FillBucket = function FillBucket(options ) {
this.zoom = options.zoom;
this.overscaling = options.overscaling;
this.layers = options.layers;
this.layerIds = this.layers.map(function (layer) { return layer.id; });
this.index = options.index;
this.layoutVertexArray = new FillLayoutArray();
this.indexArray = new TriangleIndexArray();
this.indexArray2 = new LineIndexArray();
this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, options.layers, options.zoom);
this.segments = new SegmentVector();
this.segments2 = new SegmentVector();
};
FillBucket.prototype.populate = function populate (features , options ) {
var this$1 = this;
for (var i = 0, list = features; i < list.length; i += 1) {
var ref = list[i];
var feature = ref.feature;
var index = ref.index;
var sourceLayerIndex = ref.sourceLayerIndex;
if (this$1.layers[0]._featureFilter({zoom: this$1.zoom}, feature)) {
var geometry = loadGeometry(feature);
this$1.addFeature(feature, geometry);
options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this$1.index);
}
}
};
FillBucket.prototype.isEmpty = function isEmpty () {
return this.layoutVertexArray.length === 0;
};
FillBucket.prototype.upload = function upload (context ) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);
this.indexBuffer = context.createIndexBuffer(this.indexArray);
this.indexBuffer2 = context.createIndexBuffer(this.indexArray2);
this.programConfigurations.upload(context);
};
FillBucket.prototype.destroy = function destroy () {
if (!this.layoutVertexBuffer) { return; }
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.indexBuffer2.destroy();
this.programConfigurations.destroy();
this.segments.destroy();
this.segments2.destroy();
};
FillBucket.prototype.addFeature = function addFeature (feature , geometry ) {
var this$1 = this;
for (var i$2 = 0, list = classifyRings(geometry, EARCUT_MAX_RINGS); i$2 < list.length; i$2 += 1) {
var polygon = list[i$2];
var numVertices = 0;
for (var i$3 = 0, list$1 = polygon; i$3 < list$1.length; i$3 += 1) {
var ring = list$1[i$3];
numVertices += ring.length;
}
var triangleSegment = this$1.segments.prepareSegment(numVertices, this$1.layoutVertexArray, this$1.indexArray);
var triangleIndex = triangleSegment.vertexLength;
var flattened = [];
var holeIndices = [];
for (var i$4 = 0, list$2 = polygon; i$4 < list$2.length; i$4 += 1) {
var ring$1 = list$2[i$4];
if (ring$1.length === 0) {
continue;
}
if (ring$1 !== polygon[0]) {
holeIndices.push(flattened.length / 2);
}
var lineSegment = this$1.segments2.prepareSegment(ring$1.length, this$1.layoutVertexArray, this$1.indexArray2);
var lineIndex = lineSegment.vertexLength;
this$1.layoutVertexArray.emplaceBack(ring$1[0].x, ring$1[0].y);
this$1.indexArray2.emplaceBack(lineIndex + ring$1.length - 1, lineIndex);
flattened.push(ring$1[0].x);
flattened.push(ring$1[0].y);
for (var i = 1; i < ring$1.length; i++) {
this$1.layoutVertexArray.emplaceBack(ring$1[i].x, ring$1[i].y);
this$1.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i);
flattened.push(ring$1[i].x);
flattened.push(ring$1[i].y);
}
lineSegment.vertexLength += ring$1.length;
lineSegment.primitiveLength += ring$1.length;
}
var indices = earcut(flattened, holeIndices);
assert(indices.length % 3 === 0);
for (var i$1 = 0; i$1 < indices.length; i$1 += 3) {
this$1.indexArray.emplaceBack(
triangleIndex + indices[i$1],
triangleIndex + indices[i$1 + 1],
triangleIndex + indices[i$1 + 2]);
}
triangleSegment.vertexLength += numVertices;
triangleSegment.primitiveLength += indices.length / 3;
}
this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature);
};
register('FillBucket', FillBucket, {omit: ['layers']});
module.exports = FillBucket;
},{"../../util/classify_rings":263,"../../util/web_worker_transfer":286,"../array_types":44,"../index_array_type":60,"../load_geometry":61,"../program_configuration":63,"../segment":65,"./fill_attributes":48,"assert":13,"earcut":15}],50:[function(require,module,exports){
'use strict';//
var ref = require('../../util/struct_array');
var createLayout = ref.createLayout;
module.exports = createLayout([
{name: 'a_pos', components: 2, type: 'Int16'},
{name: 'a_normal_ed', components: 4, type: 'Int16'} ], 4);
},{"../../util/struct_array":279}],51:[function(require,module,exports){
'use strict';//
var ref = require('../array_types');
var FillExtrusionLayoutArray = ref.FillExtrusionLayoutArray;
var layoutAttributes = require('./fill_extrusion_attributes').members;
var ref$1 = require('../segment');
var SegmentVector = ref$1.SegmentVector;
var MAX_VERTEX_ARRAY_LENGTH = ref$1.MAX_VERTEX_ARRAY_LENGTH;
var ref$2 = require('../program_configuration');
var ProgramConfigurationSet = ref$2.ProgramConfigurationSet;
var ref$3 = require('../index_array_type');
var TriangleIndexArray = ref$3.TriangleIndexArray;
var loadGeometry = require('../load_geometry');
var EXTENT = require('../extent');
var earcut = require('earcut');
var classifyRings = require('../../util/classify_rings');
var assert = require('assert');
var EARCUT_MAX_RINGS = 500;
var ref$4 = require('../../util/web_worker_transfer');
var register = ref$4.register;
var FACTOR = Math.pow(2, 13);
function addVertex(vertexArray, x, y, nx, ny, nz, t, e) {
vertexArray.emplaceBack(
// a_pos
x,
y,
// a_normal_ed: 3-component normal and 1-component edgedistance
Math.floor(nx * FACTOR) * 2 + t,
ny * FACTOR * 2,
nz * FACTOR * 2,
// edgedistance (used for wrapping patterns around extrusion sides)
Math.round(e)
);
}
var FillExtrusionBucket = function FillExtrusionBucket(options ) {
this.zoom = options.zoom;
this.overscaling = options.overscaling;
this.layers = options.layers;
this.layerIds = this.layers.map(function (layer) { return layer.id; });
this.index = options.index;
this.layoutVertexArray = new FillExtrusionLayoutArray();
this.indexArray = new TriangleIndexArray();
this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, options.layers, options.zoom);
this.segments = new SegmentVector();
};
FillExtrusionBucket.prototype.populate = function populate (features , options ) {
var this$1 = this;
for (var i = 0, list = features; i < list.length; i += 1) {
var ref = list[i];
var feature = ref.feature;
var index = ref.index;
var sourceLayerIndex = ref.sourceLayerIndex;
if (this$1.layers[0]._featureFilter({zoom: this$1.zoom}, feature)) {
var geometry = loadGeometry(feature);
this$1.addFeature(feature, geometry);
options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this$1.index);
}
}
};
FillExtrusionBucket.prototype.isEmpty = function isEmpty () {
return this.layoutVertexArray.length === 0;
};
FillExtrusionBucket.prototype.upload = function upload (context ) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);
this.indexBuffer = context.createIndexBuffer(this.indexArray);
this.programConfigurations.upload(context);
};
FillExtrusionBucket.prototype.destroy = function destroy () {
if (!this.layoutVertexBuffer) { return; }
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.programConfigurations.destroy();
this.segments.destroy();
};
FillExtrusionBucket.prototype.addFeature = function addFeature (feature , geometry ) {
var this$1 = this;
for (var i$1 = 0, list = classifyRings(geometry, EARCUT_MAX_RINGS); i$1 < list.length; i$1 += 1) {
var polygon = list[i$1];
var numVertices = 0;
for (var i$2 = 0, list$1 = polygon; i$2 < list$1.length; i$2 += 1) {
var ring = list$1[i$2];
numVertices += ring.length;
}
var segment = this$1.segments.prepareSegment(4, this$1.layoutVertexArray, this$1.indexArray);
for (var i$3 = 0, list$2 = polygon; i$3 < list$2.length; i$3 += 1) {
var ring$1 = list$2[i$3];
if (ring$1.length === 0) {
continue;
}
if (isEntirelyOutside(ring$1)) {
continue;
}
var edgeDistance = 0;
for (var p = 0; p < ring$1.length; p++) {
var p1 = ring$1[p];
if (p >= 1) {
var p2 = ring$1[p - 1];
if (!isBoundaryEdge(p1, p2)) {
if (segment.vertexLength + 4 > MAX_VERTEX_ARRAY_LENGTH) {
segment = this$1.segments.prepareSegment(4, this$1.layoutVertexArray, this$1.indexArray);
}
var perp = p1.sub(p2)._perp()._unit();
var dist = p2.dist(p1);
if (edgeDistance + dist > 32768) { edgeDistance = 0; }
addVertex(this$1.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance);
addVertex(this$1.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance);
edgeDistance += dist;
addVertex(this$1.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance);
addVertex(this$1.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance);
var bottomRight = segment.vertexLength;
this$1.indexArray.emplaceBack(bottomRight, bottomRight + 1, bottomRight + 2);
this$1.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3);
segment.vertexLength += 4;
segment.primitiveLength += 2;
}
}
}
}
if (segment.vertexLength + numVertices > MAX_VERTEX_ARRAY_LENGTH) {
segment = this$1.segments.prepareSegment(numVertices, this$1.layoutVertexArray, this$1.indexArray);
}
var flattened = [];
var holeIndices = [];
var triangleIndex = segment.vertexLength;
for (var i$4 = 0, list$3 = polygon; i$4 < list$3.length; i$4 += 1) {
var ring$2 = list$3[i$4];
if (ring$2.length === 0) {
continue;
}
if (ring$2 !== polygon[0]) {
holeIndices.push(flattened.length / 2);
}
for (var i = 0; i < ring$2.length; i++) {
var p$1 = ring$2[i];
addVertex(this$1.layoutVertexArray, p$1.x, p$1.y, 0, 0, 1, 1, 0);
flattened.push(p$1.x);
flattened.push(p$1.y);
}
}
var indices = earcut(flattened, holeIndices);
assert(indices.length % 3 === 0);
for (var j = 0; j < indices.length; j += 3) {
this$1.indexArray.emplaceBack(
triangleIndex + indices[j],
triangleIndex + indices[j + 1],
triangleIndex + indices[j + 2]);
}
segment.primitiveLength += indices.length / 3;
segment.vertexLength += numVertices;
}
this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature);
};
register('FillExtrusionBucket', FillExtrusionBucket, {omit: ['layers']});
module.exports = FillExtrusionBucket;
function isBoundaryEdge(p1, p2) {
return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) ||
(p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT));
}
function isEntirelyOutside(ring) {
return ring.every(function (p) { return p.x < 0; }) ||
ring.every(function (p) { return p.x > EXTENT; }) ||
ring.every(function (p) { return p.y < 0; }) ||
ring.every(function (p) { return p.y > EXTENT; });
}
},{"../../util/classify_rings":263,"../../util/web_worker_transfer":286,"../array_types":44,"../extent":58,"../index_array_type":60,"../load_geometry":61,"../program_configuration":63,"../segment":65,"./fill_extrusion_attributes":50,"assert":13,"earcut":15}],52:[function(require,module,exports){
'use strict';//
var CircleBucket = require('./circle_bucket');
var ref = require('../../util/web_worker_transfer');
var register = ref.register;
var HeatmapBucket = (function (CircleBucket) {
function HeatmapBucket () {
CircleBucket.apply(this, arguments);
}if ( CircleBucket ) HeatmapBucket.__proto__ = CircleBucket;
HeatmapBucket.prototype = Object.create( CircleBucket && CircleBucket.prototype );
HeatmapBucket.prototype.constructor = HeatmapBucket;
return HeatmapBucket;
}(CircleBucket));
register('HeatmapBucket', HeatmapBucket, {omit: ['layers']});
module.exports = HeatmapBucket;
},{"../../util/web_worker_transfer":286,"./circle_bucket":47}],53:[function(require,module,exports){
'use strict';//
var ref = require('../../util/struct_array');
var createLayout = ref.createLayout;
module.exports = createLayout([
{name: 'a_pos_normal', components: 4, type: 'Int16'},
{name: 'a_data', components: 4, type: 'Uint8'}
], 4);
},{"../../util/struct_array":279}],54:[function(require,module,exports){
'use strict';//
var ref = require('../array_types');
var LineLayoutArray = ref.LineLayoutArray;
var layoutAttributes = require('./line_attributes').members;
var ref$1 = require('../segment');
var SegmentVector = ref$1.SegmentVector;
var ref$2 = require('../program_configuration');
var ProgramConfigurationSet = ref$2.ProgramConfigurationSet;
var ref$3 = require('../index_array_type');
var TriangleIndexArray = ref$3.TriangleIndexArray;
var loadGeometry = require('../load_geometry');
var EXTENT = require('../extent');
var vectorTileFeatureTypes = require('@mapbox/vector-tile').VectorTileFeature.types;
var ref$4 = require('../../util/web_worker_transfer');
var register = ref$4.register;
// NOTE ON EXTRUDE SCALE:
// scale the extrusion vector so that the normal length is this value.
// contains the "texture" normals (-1..1). this is distinct from the extrude
// normals for line joins, because the x-value remains 0 for the texture
// normal array, while the extrude normal actually moves the vertex to create
// the acute/bevelled line join.
var EXTRUDE_SCALE = 63;
/*
* Sharp corners cause dashed lines to tilt because the distance along the line
* is the same at both the inner and outer corners. To improve the appearance of
* dashed lines we add extra points near sharp corners so that a smaller part
* of the line is tilted.
*
* COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an
* extra vertex. The default is 75 degrees.
*
* The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner.
*/
var COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));
var SHARP_CORNER_OFFSET = 15;
// The number of bits that is used to store the line distance in the buffer.
var LINE_DISTANCE_BUFFER_BITS = 15;
// We don't have enough bits for the line distance as we'd like to have, so
// use this value to scale the line distance (in tile units) down to a smaller
// value. This lets us store longer distances while sacrificing precision.
var LINE_DISTANCE_SCALE = 1 / 2;
// The maximum line distance, in tile units, that fits in the buffer.
var MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE;
function addLineVertex(layoutVertexBuffer, point , extrude , round , up , dir , linesofar ) {
layoutVertexBuffer.emplaceBack(
// a_pos_normal
point.x,
point.y,
round ? 1 : 0,
up ? 1 : -1,
// a_data
// add 128 to store a byte in an unsigned byte
Math.round(EXTRUDE_SCALE * extrude.x) + 128,
Math.round(EXTRUDE_SCALE * extrude.y) + 128,
// Encode the -1/0/1 direction value into the first two bits of .z of a_data.
// Combine it with the lower 6 bits of `linesofar` (shifted by 2 bites to make
// room for the direction value). The upper 8 bits of `linesofar` are placed in
// the `w` component. `linesofar` is scaled down by `LINE_DISTANCE_SCALE` so that
// we can store longer distances while sacrificing precision.
((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | (((linesofar * LINE_DISTANCE_SCALE) & 0x3F) << 2),
(linesofar * LINE_DISTANCE_SCALE) >> 6);
}
/**
* @private
*/
var LineBucket = function LineBucket(options ) {
this.zoom = options.zoom;
this.overscaling = options.overscaling;
this.layers = options.layers;
this.layerIds = this.layers.map(function (layer) { return layer.id; });
this.index = options.index;
this.layoutVertexArray = new LineLayoutArray();
this.indexArray = new TriangleIndexArray();
this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, options.layers, options.zoom);
this.segments = new SegmentVector();
};
LineBucket.prototype.populate = function populate (features , options ) {
var this$1 = this;
for (var i = 0, list = features; i < list.length; i += 1) {
var ref = list[i];
var feature = ref.feature;
var index = ref.index;
var sourceLayerIndex = ref.sourceLayerIndex;
if (this$1.layers[0]._featureFilter({zoom: this$1.zoom}, feature)) {
var geometry = loadGeometry(feature);
this$1.addFeature(feature, geometry);
options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this$1.index);
}
}
};
LineBucket.prototype.isEmpty = function isEmpty () {
return this.layoutVertexArray.length === 0;
};
LineBucket.prototype.upload = function upload (context ) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);
this.indexBuffer = context.createIndexBuffer(this.indexArray);
this.programConfigurations.upload(context);
};
LineBucket.prototype.destroy = function destroy () {
if (!this.layoutVertexBuffer) { return; }
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.programConfigurations.destroy();
this.segments.destroy();
};
LineBucket.prototype.addFeature = function addFeature (feature , geometry ) {
var this$1 = this;
var layout = this.layers[0].layout;
var join = layout.get('line-join').evaluate(feature);
var cap = layout.get('line-cap');
var miterLimit = layout.get('line-miter-limit');
var roundLimit = layout.get('line-round-limit');
for (var i = 0, list = geometry; i < list.length; i += 1) {
var line = list[i];
this$1.addLine(line, feature, join, cap, miterLimit, roundLimit);
}
};
LineBucket.prototype.addLine = function addLine (vertices , feature , join , cap , miterLimit , roundLimit ) {
var this$1 = this;
var isPolygon = vectorTileFeatureTypes[feature.type] === 'Polygon';
// If the line has duplicate vertices at the ends, adjust start/length to remove them.
var len = vertices.length;
while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {
len--;
}
var first = 0;
while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {
first++;
}
// Ignore invalid geometry.
if (len < (isPolygon ? 3 : 2)) { return; }
if (join === 'bevel') { miterLimit = 1.05; }
var sharpCornerOffset = SHARP_CORNER_OFFSET * (EXTENT / (512 * this.overscaling));
var firstVertex = vertices[first];
// we could be more precise, but it would only save a negligible amount of space
var segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);
this.distance = 0;
var beginCap = cap,
endCap = isPolygon ? 'butt' : cap;
var startOfLine = true;
var currentVertex;
var prevVertex = ((undefined ) );
var nextVertex = ((undefined ) );
var prevNormal = ((undefined ) );
var nextNormal = ((undefined ) );
var offsetA;
var offsetB;
// the last three vertices added
this.e1 = this.e2 = this.e3 = -1;
if (isPolygon) {
currentVertex = vertices[len - 2];
nextNormal = firstVertex.sub(currentVertex)._unit()._perp();
}
for (var i = first; i < len; i++) {
nextVertex = isPolygon && i === len - 1 ?
vertices[first + 1] : // if the line is closed, we treat the last vertex like the first
vertices[i + 1]; // just the next vertex
// if two consecutive vertices exist, skip the current one
if (nextVertex && vertices[i].equals(nextVertex)) { continue; }
if (nextNormal) { prevNormal = nextNormal; }
if (currentVertex) { prevVertex = currentVertex; }
currentVertex = vertices[i];
// Calculate the normal towards the next vertex in this line. In case
// there is no next vertex, pretend that the line is continuing straight,
// meaning that we are just using the previous normal.
nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;
// If we still don't have a previous normal, this is the beginning of a
// non-closed line, so we're doing a straight "join".
prevNormal = prevNormal || nextNormal;
// Determine the normal of the join extrusion. It is the angle bisector
// of the segments between the previous line and the next line.
// In the case of 180° angles, the prev and next normals cancel each other out:
// prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be
// undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle
// below will also become 0 and miterLength will become Infinity.
var joinNormal = prevNormal.add(nextNormal);
if (joinNormal.x !== 0 || joinNormal.y !== 0) {
joinNormal._unit();
}
/* joinNormal prevNormal
* ↖ ↑
* .________. prevVertex
* |
* nextNormal ← | currentVertex
* |
* nextVertex !
*
*/
// Calculate the length of the miter (the ratio of the miter to the width).
// Find the cosine of the angle between the next and join normals
// using dot product. The inverse of that is the miter length.
var cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
var miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;
var isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;
if (isSharpCorner && i > first) {
var prevSegmentLength = currentVertex.dist(prevVertex);
if (prevSegmentLength > 2 * sharpCornerOffset) {
var newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());
this$1.distance += newPrevVertex.dist(prevVertex);
this$1.addCurrentVertex(newPrevVertex, this$1.distance, prevNormal.mult(1), 0, 0, false, segment);
prevVertex = newPrevVertex;
}
}
// The join if a middle vertex, otherwise the cap.
var middleVertex = prevVertex && nextVertex;
var currentJoin = middleVertex ? join : nextVertex ? beginCap : endCap;
if (middleVertex && currentJoin === 'round') {
if (miterLength < roundLimit) {
currentJoin = 'miter';
} else if (miterLength <= 2) {
currentJoin = 'fakeround';
}
}
if (currentJoin === 'miter' && miterLength > miterLimit) {
currentJoin = 'bevel';
}
if (currentJoin === 'bevel') {
// The maximum extrude length is 128 / 63 = 2 times the width of the line
// so if miterLength >= 2 we need to draw a different type of bevel here.
if (miterLength > 2) { currentJoin = 'flipbevel'; }
// If the miterLength is really small and the line bevel wouldn't be visible,
// just draw a miter join to save a triangle.
if (miterLength < miterLimit) { currentJoin = 'miter'; }
}
// Calculate how far along the line the currentVertex is
if (prevVertex) { this$1.distance += currentVertex.dist(prevVertex); }
if (currentJoin === 'miter') {
joinNormal._mult(miterLength);
this$1.addCurrentVertex(currentVertex, this$1.distance, joinNormal, 0, 0, false, segment);
} else if (currentJoin === 'flipbevel') {
// miter is too big, flip the direction to make a beveled join
if (miterLength > 100) {
// Almost parallel lines
joinNormal = nextNormal.clone().mult(-1);
} else {
var direction = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0 ? -1 : 1;
var bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();
joinNormal._perp()._mult(bevelLength * direction);
}
this$1.addCurrentVertex(currentVertex, this$1.distance, joinNormal, 0, 0, false, segment);
this$1.addCurrentVertex(currentVertex, this$1.distance, joinNormal.mult(-1), 0, 0, false, segment);
} else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {
var lineTurnsLeft = (prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x) > 0;
var offset = -Math.sqrt(miterLength * miterLength - 1);
if (lineTurnsLeft) {
offsetB = 0;
offsetA = offset;
} else {
offsetA = 0;
offsetB = offset;
}
// Close previous segment with a bevel
if (!startOfLine) {
this$1.addCurrentVertex(currentVertex, this$1.distance, prevNormal, offsetA, offsetB, false, segment);
}
if (currentJoin === 'fakeround') {
// The join angle is sharp enough that a round join would be visible.
// Bevel joins fill the gap between segments with a single pie slice triangle.
// Create a round join by adding multiple pie slices. The join isn't actually round, but
// it looks like it is at the sizes we render lines at.
// Add more triangles for sharper angles.
// This math is just a good enough approximation. It isn't "correct".
var n = Math.floor((0.5 - (cosHalfAngle - 0.5)) * 8);
var approxFractionalJoinNormal = (void 0);
for (var m = 0; m < n; m++) {
approxFractionalJoinNormal = nextNormal.mult((m + 1) / (n + 1))._add(prevNormal)._unit();
this$1.addPieSliceVertex(currentVertex, this$1.distance, approxFractionalJoinNormal, lineTurnsLeft, segment);
}
this$1.addPieSliceVertex(currentVertex, this$1.distance, joinNormal, lineTurnsLeft, segment);
for (var k = n - 1; k >= 0; k--) {
approxFractionalJoinNormal = prevNormal.mult((k + 1) / (n + 1))._add(nextNormal)._unit();
this$1.addPieSliceVertex(currentVertex, this$1.distance, approxFractionalJoinNormal, lineTurnsLeft, segment);
}
}
// Start next segment
if (nextVertex) {
this$1.addCurrentVertex(currentVertex, this$1.distance, nextNormal, -offsetA, -offsetB, false, segment);
}
} else if (currentJoin === 'butt') {
if (!startOfLine) {
// Close previous segment with a butt
this$1.addCurrentVertex(currentVertex, this$1.distance, prevNormal, 0, 0, false, segment);
}
// Start next segment with a butt
if (nextVertex) {
this$1.addCurrentVertex(currentVertex, this$1.distance, nextNormal, 0, 0, false, segment);
}
} else if (currentJoin === 'square') {
if (!startOfLine) {
// Close previous segment with a square cap
this$1.addCurrentVertex(currentVertex, this$1.distance, prevNormal, 1, 1, false, segment);
// The segment is done. Unset vertices to disconnect segments.
this$1.e1 = this$1.e2 = -1;
}
// Start next segment
if (nextVertex) {
this$1.addCurrentVertex(currentVertex, this$1.distance, nextNormal, -1, -1, false, segment);
}
} else if (currentJoin === 'round') {
if (!startOfLine) {
// Close previous segment with butt
this$1.addCurrentVertex(currentVertex, this$1.distance, prevNormal, 0, 0, false, segment);
// Add round cap or linejoin at end of segment
this$1.addCurrentVertex(currentVertex, this$1.distance, prevNormal, 1, 1, true, segment);
// The segment is done. Unset vertices to disconnect segments.
this$1.e1 = this$1.e2 = -1;
}
// Start next segment with a butt
if (nextVertex) {
// Add round cap before first segment
this$1.addCurrentVertex(currentVertex, this$1.distance, nextNormal, -1, -1, true, segment);
this$1.addCurrentVertex(currentVertex, this$1.distance, nextNormal, 0, 0, false, segment);
}
}
if (isSharpCorner && i < len - 1) {
var nextSegmentLength = currentVertex.dist(nextVertex);
if (nextSegmentLength > 2 * sharpCornerOffset) {
var newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round());
this$1.distance += newCurrentVertex.dist(currentVertex);
this$1.addCurrentVertex(newCurrentVertex, this$1.distance, nextNormal.mult(1), 0, 0, false, segment);
currentVertex = newCurrentVertex;
}
}
startOfLine = false;
}
this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature);
};
/**
* Add two vertices to the buffers.
*
* @param {Object} currentVertex the line vertex to add buffer vertices for
* @param {number} distance the distance from the beginning of the line to the vertex
* @param {number} endLeft extrude to shift the left vertex along the line
* @param {number} endRight extrude to shift the left vertex along the line
* @param {boolean} round whether this is a round cap
* @private
*/
LineBucket.prototype.addCurrentVertex = function addCurrentVertex (currentVertex ,
distance ,
normal ,
endLeft ,
endRight ,
round ,
segment ) {
var extrude;
var layoutVertexArray = this.layoutVertexArray;
var indexArray = this.indexArray;
extrude = normal.clone();
if (endLeft) { extrude._sub(normal.perp()._mult(endLeft)); }
addLineVertex(layoutVertexArray, currentVertex, extrude, round, false, endLeft, distance);
this.e3 = segment.vertexLength++;
if (this.e1 >= 0 && this.e2 >= 0) {
indexArray.emplaceBack(this.e1, this.e2, this.e3);
segment.primitiveLength++;
}
this.e1 = this.e2;
this.e2 = this.e3;
extrude = normal.mult(-1);
if (endRight) { extrude._sub(normal.perp()._mult(endRight)); }
addLineVertex(layoutVertexArray, currentVertex, extrude, round, true, -endRight, distance);
this.e3 = segment.vertexLength++;
if (this.e1 >= 0 && this.e2 >= 0) {
indexArray.emplaceBack(this.e1, this.e2, this.e3);
segment.primitiveLength++;
}
this.e1 = this.e2;
this.e2 = this.e3;
// There is a maximum "distance along the line" that we can store in the buffers.
// When we get close to the distance, reset it to zero and add the vertex again with
// a distance of zero. The max distance is determined by the number of bits we allocate
// to `linesofar`.
if (distance > MAX_LINE_DISTANCE / 2) {
this.distance = 0;
this.addCurrentVertex(currentVertex, this.distance, normal, endLeft, endRight, round, segment);
}
};
/**
* Add a single new vertex and a triangle using two previous vertices.
* This adds a pie slice triangle near a join to simulate round joins
*
* @param currentVertex the line vertex to add buffer vertices for
* @param distance the distance from the beggining of the line to the vertex
* @param extrude the offset of the new vertex from the currentVertex
* @param lineTurnsLeft whether the line is turning left or right at this angle
* @private
*/
LineBucket.prototype.addPieSliceVertex = function addPieSliceVertex (currentVertex ,
distance ,
extrude ,
lineTurnsLeft ,
segment ) {
extrude = extrude.mult(lineTurnsLeft ? -1 : 1);
var layoutVertexArray = this.layoutVertexArray;
var indexArray = this.indexArray;
addLineVertex(layoutVertexArray, currentVertex, extrude, false, lineTurnsLeft, 0, distance);
this.e3 = segment.vertexLength++;
if (this.e1 >= 0 && this.e2 >= 0) {
indexArray.emplaceBack(this.e1, this.e2, this.e3);
segment.primitiveLength++;
}
if (lineTurnsLeft) {
this.e2 = this.e3;
} else {
this.e1 = this.e3;
}
};
register('LineBucket', LineBucket, {omit: ['layers']});
module.exports = LineBucket;
},{"../../util/web_worker_transfer":286,"../array_types":44,"../extent":58,"../index_array_type":60,"../load_geometry":61,"../program_configuration":63,"../segment":65,"./line_attributes":53,"@mapbox/vector-tile":8}],55:[function(require,module,exports){
'use strict';//
var ref = require('../../util/struct_array');
var createLayout = ref.createLayout;
var symbolLayoutAttributes = createLayout([
{name: 'a_pos_offset', components: 4, type: 'Int16'},
{name: 'a_data', components: 4, type: 'Uint16'}
]);
var dynamicLayoutAttributes = createLayout([
{ name: 'a_projected_pos', components: 3, type: 'Float32' }
], 4);
var placementOpacityAttributes = createLayout([
{ name: 'a_fade_opacity', components: 1, type: 'Uint32' }
], 4);
var collisionVertexAttributes = createLayout([
{ name: 'a_placed', components: 2, type: 'Uint8' }
], 4);
var symbolAttributes = {
symbolLayoutAttributes: symbolLayoutAttributes,
dynamicLayoutAttributes: dynamicLayoutAttributes,
placementOpacityAttributes: placementOpacityAttributes,
collisionVertexAttributes: collisionVertexAttributes,
collisionBox: createLayout([
// the box is centered around the anchor point
{ type: 'Int16', name: 'anchorPointX' },
{ type: 'Int16', name: 'anchorPointY' },
// distances to the edges from the anchor
{ type: 'Int16', name: 'x1' },
{ type: 'Int16', name: 'y1' },
{ type: 'Int16', name: 'x2' },
{ type: 'Int16', name: 'y2' },
// 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' },
// collision circles for lines store their distance to the anchor in tile units
// so that they can be ignored if the projected label doesn't extend into
// the box area
{ type: 'Int16', name: 'radius' },
{ type: 'Int16', name: 'signedDistanceFromAnchor' }
]),
collisionBoxLayout: createLayout([ // used to render collision boxes for debugging purposes
{name: 'a_pos', components: 2, type: 'Int16'},
{name: 'a_anchor_pos', components: 2, type: 'Int16'},
{name: 'a_extrude', components: 2, type: 'Int16'}
], 4),
collisionCircleLayout: createLayout([ // used to render collision circles for debugging purposes
{name: 'a_pos', components: 2, type: 'Int16'},
{name: 'a_anchor_pos', components: 2, type: 'Int16'},
{name: 'a_extrude', components: 2, type: 'Int16'}
], 4),
placement: createLayout([
{ type: 'Int16', name: 'anchorX' },
{ type: 'Int16', name: 'anchorY' },
{ 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: 'hidden' }
]),
glyphOffset: createLayout([
{ type: 'Float32', name: 'offsetX' }
]),
lineVertex: createLayout([
{ type: 'Int16', name: 'x' },
{ type: 'Int16', name: 'y' },
{ type: 'Int16', name: 'tileUnitDistanceFromAnchor' }
])
};
module.exports = symbolAttributes;
},{"../../util/struct_array":279}],56:[function(require,module,exports){
'use strict';//
var ref = require('./symbol_attributes');
var symbolLayoutAttributes = ref.symbolLayoutAttributes;
var collisionVertexAttributes = ref.collisionVertexAttributes;
var collisionBoxLayout = ref.collisionBoxLayout;
var collisionCircleLayout = ref.collisionCircleLayout;
var dynamicLayoutAttributes = ref.dynamicLayoutAttributes;
var ref$1 = require('../array_types');
var SymbolLayoutArray = ref$1.SymbolLayoutArray;
var SymbolDynamicLayoutArray = ref$1.SymbolDynamicLayoutArray;
var SymbolOpacityArray = ref$1.SymbolOpacityArray;
var CollisionBoxLayoutArray = ref$1.CollisionBoxLayoutArray;
var CollisionCircleLayoutArray = ref$1.CollisionCircleLayoutArray;
var CollisionVertexArray = ref$1.CollisionVertexArray;
var PlacedSymbolArray = ref$1.PlacedSymbolArray;
var GlyphOffsetArray = ref$1.GlyphOffsetArray;
var SymbolLineVertexArray = ref$1.SymbolLineVertexArray;
var Point = require('@mapbox/point-geometry');
var ref$2 = require('../segment');
var SegmentVector = ref$2.SegmentVector;
var ref$3 = require('../program_configuration');
var ProgramConfigurationSet = ref$3.ProgramConfigurationSet;
var ref$4 = require('../index_array_type');
var TriangleIndexArray = ref$4.TriangleIndexArray;
var LineIndexArray = ref$4.LineIndexArray;
var transformText = require('../../symbol/transform_text');
var mergeLines = require('../../symbol/mergelines');
var scriptDetection = require('../../util/script_detection');
var loadGeometry = require('../load_geometry');
var vectorTileFeatureTypes = require('@mapbox/vector-tile').VectorTileFeature.types;
var verticalizePunctuation = require('../../util/verticalize_punctuation');
var Anchor = require('../../symbol/anchor');
var ref$5 = require('../../symbol/symbol_size');
var getSizeData = ref$5.getSizeData;
var ref$6 = require('../../util/web_worker_transfer');
var register = ref$6.register;
// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them
// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph
// 7 bits are for the current opacity, and the lowest bit is the target opacity
// actually defined in symbol_attributes.js
// const placementOpacityAttributes = [
// { name: 'a_fade_opacity', components: 1, type: 'Uint32' }
// ];
var shaderOpacityAttributes = [
{ name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0 }
];
function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex) {
array.emplaceBack(
// a_pos_offset
anchorX,
anchorY,
Math.round(ox * 64),
Math.round(oy * 64),
// a_data
tx, // x coordinate of symbol on glyph atlas texture
ty, // y coordinate of symbol on glyph atlas texture
sizeVertex ? sizeVertex[0] : 0,
sizeVertex ? sizeVertex[1] : 0
);
}
function addDynamicAttributes(dynamicLayoutVertexArray , p , angle ) {
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
}
var SymbolBuffers = function SymbolBuffers(programConfigurations ) {
this.layoutVertexArray = new SymbolLayoutArray();
this.indexArray = new TriangleIndexArray();
this.programConfigurations = programConfigurations;
this.segments = new SegmentVector();
this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray();
this.opacityVertexArray = new SymbolOpacityArray();
this.placedSymbolArray = new PlacedSymbolArray();
};
SymbolBuffers.prototype.upload = function upload (context , dynamicIndexBuffer ) {
this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);
this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);
this.programConfigurations.upload(context);
this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);
this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);
// This is a performance hack so that we can write to opacityVertexArray with uint32s
// even though the shaders read uint8s
this.opacityVertexBuffer.itemSize = 1;
};
SymbolBuffers.prototype.destroy = function destroy () {
if (!this.layoutVertexBuffer) { return; }
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.programConfigurations.destroy();
this.segments.destroy();
this.dynamicLayoutVertexBuffer.destroy();
this.opacityVertexBuffer.destroy();
};
register('SymbolBuffers', SymbolBuffers);
var CollisionBuffers = function CollisionBuffers(LayoutArray ,
layoutAttributes ,
IndexArray ) {
this.layoutVertexArray = new LayoutArray();
this.layoutAttributes = layoutAttributes;
this.indexArray = new IndexArray();
this.segments = new SegmentVector();
this.collisionVertexArray = new CollisionVertexArray();
};
CollisionBuffers.prototype.upload = function 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);
};
CollisionBuffers.prototype.destroy = function destroy () {
if (!this.layoutVertexBuffer) { return; }
this.layoutVertexBuffer.destroy();
this.indexBuffer.destroy();
this.segments.destroy();
this.collisionVertexBuffer.destroy();
};
register('CollisionBuffers', CollisionBuffers);
/**
* Unlike other buckets, which simply implement #addFeature with type-specific
* logic for (essentially) triangulating feature geometries, SymbolBucket
* requires specialized behavior:
*
* 1. WorkerTile#parse(), the logical owner of the bucket creation process,
* calls SymbolBucket#populate(), which resolves text and icon tokens on
* each feature, adds each glyphs and symbols needed to the passed-in
* collections options.glyphDependencies and options.iconDependencies, and
* stores the feature data for use in subsequent step (this.features).
*
* 2. WorkerTile asynchronously requests from the main thread all of the glyphs
* and icons needed (by this bucket and any others). When glyphs and icons
* have been received, the WorkerTile creates a CollisionIndex and invokes:
*
* 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and
* layout on a Symbol Bucket. This step populates:
* `this.symbolInstances`: metadata on generated symbols
* `this.collisionBoxArray`: collision data for use by foreground
* `this.text`: SymbolBuffers for text symbols
* `this.icons`: SymbolBuffers for icons
* `this.collisionBox`: Debug SymbolBuffers for collision boxes
* `this.collisionCircle`: Debug SymbolBuffers for collision circles
* The results are sent to the foreground for rendering
*
* 4. performSymbolPlacement(bucket, collisionIndex) is run on the foreground,
* and uses the CollisionIndex along with current camera settings to determine
* which symbols can actually show on the map. Collided symbols are hidden
* using a dynamic "OpacityVertexArray".
*
* @private
*/
var SymbolBucket = function SymbolBucket(options ) {
this.collisionBoxArray = options.collisionBoxArray;
this.zoom = options.zoom;
this.overscaling = options.overscaling;
this.layers = options.layers;
this.layerIds = this.layers.map(function (layer) { return layer.id; });
this.index = options.index;
this.pixelRatio = options.pixelRatio;
var layer = this.layers[0];
var unevaluatedLayoutValues = layer._unevaluatedLayout._values;
this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']);
this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']);
var layout = this.layers[0].layout;
this.sortFeaturesByY = layout.get('text-allow-overlap') || layout.get('icon-allow-overlap') ||
layout.get('text-ignore-placement') || layout.get('icon-ignore-placement');
};
SymbolBucket.prototype.createArrays = function createArrays () {
this.text = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, function (property) { return /^text/.test(property); }));
this.icon = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, function (property) { return /^icon/.test(property); }));
this.collisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);
this.collisionCircle = new CollisionBuffers(CollisionCircleLayoutArray, collisionCircleLayout.members, TriangleIndexArray);
this.glyphOffsetArray = new GlyphOffsetArray();
this.lineVertexArray = new SymbolLineVertexArray();
};
SymbolBucket.prototype.populate = function populate (features , options ) {
var this$1 = this;
var layer = this.layers[0];
var layout = layer.layout;
var textFont = layout.get('text-font');
var textField = layout.get('text-field');
var iconImage = layout.get('icon-image');
var hasText =
(textField.value.kind !== 'constant' || textField.value.value.length > 0) &&
(textFont.value.kind !== 'constant' || textFont.value.value.length > 0);
var hasIcon = iconImage.value.kind !== 'constant' || iconImage.value.value && iconImage.value.value.length > 0;
this.features = [];
if (!hasText && !hasIcon) {
return;
}
var icons = options.iconDependencies;
var stacks = options.glyphDependencies;
var globalProperties ={zoom: this.zoom};
for (var i$1 = 0, list = features; i$1 < list.length; i$1 += 1) {
var ref = list[i$1];
var feature = ref.feature;
var index = ref.index;
var sourceLayerIndex = ref.sourceLayerIndex;
if (!layer._featureFilter(globalProperties, feature)) {
continue;
}
var text = (void 0);
if (hasText) {
text = layer.getValueAndResolveTokens('text-field', feature);
text = transformText(text, layer, feature);
}
var icon = (void 0);
if (hasIcon) {
icon = layer.getValueAndResolveTokens('icon-image', feature);
}
if (!text && !icon) {
continue;
}
var symbolFeature = {
text: text,
icon: icon,
index: index,
sourceLayerIndex: sourceLayerIndex,
geometry: loadGeometry(feature),
properties: feature.properties,
type: vectorTileFeatureTypes[feature.type]
};
if (typeof feature.id !== 'undefined') {
symbolFeature.id = feature.id;
}
this$1.features.push(symbolFeature);
if (icon) {
icons[icon] = true;
}
if (text) {
var fontStack = textFont.evaluate(feature).join(',');
var stack = stacks[fontStack] = stacks[fontStack] || {};
var textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') === 'line';
var allowsVerticalWritingMode = scriptDetection.allowsVerticalWritingMode(text);
for (var i = 0; i < text.length; i++) {
stack[text.charCodeAt(i)] = true;
if (textAlongLine && allowsVerticalWritingMode) {
var verticalChar = verticalizePunctuation.lookup[text.charAt(i)];
if (verticalChar) {
stack[verticalChar.charCodeAt(0)] = true;
}
}
}
}
}
if (layout.get('symbol-placement') === 'line') {
// Merge adjacent lines with the same text to improve labelling.
// It's better to place labels on one long line than on many short segments.
this.features = mergeLines(this.features);
}
};
SymbolBucket.prototype.isEmpty = function isEmpty () {
return this.symbolInstances.length === 0;
};
SymbolBucket.prototype.upload = function upload (context ) {
this.text.upload(context, this.sortFeaturesByY);
this.icon.upload(context, this.sortFeaturesByY);
this.collisionBox.upload(context);
this.collisionCircle.upload(context);
};
SymbolBucket.prototype.destroy = function destroy () {
this.text.destroy();
this.icon.destroy();
this.collisionBox.destroy();
this.collisionCircle.destroy();
};
SymbolBucket.prototype.addToLineVertexArray = function addToLineVertexArray (anchor , line ) {
var this$1 = this;
var lineStartIndex = this.lineVertexArray.length;
if (anchor.segment !== undefined) {
var sumForwardLength = anchor.dist(line[anchor.segment + 1]);
var sumBackwardLength = anchor.dist(line[anchor.segment]);
var vertices = {};
for (var i = anchor.segment + 1; i < line.length; i++) {
vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength };
if (i < line.length - 1) {
sumForwardLength += line[i + 1].dist(line[i]);
}
}
for (var i$1 = anchor.segment || 0; i$1 >= 0; i$1--) {
vertices[i$1] = { x: line[i$1].x, y: line[i$1].y, tileUnitDistanceFromAnchor: sumBackwardLength };
if (i$1 > 0) {
sumBackwardLength += line[i$1 - 1].dist(line[i$1]);
}
}
for (var i$2 = 0; i$2 < line.length; i$2++) {
var vertex = vertices[i$2];
this$1.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor);
}
}
return {
lineStartIndex: lineStartIndex,
lineLength: this.lineVertexArray.length - lineStartIndex
};
};
SymbolBucket.prototype.addSymbols = function addSymbols (arrays ,
quads ,
sizeVertex ,
lineOffset ,
alongLine ,
feature ,
writingMode ,
labelAnchor ,
lineStartIndex ,
lineLength ) {
var this$1 = this;
var indexArray = arrays.indexArray;
var layoutVertexArray = arrays.layoutVertexArray;
var dynamicLayoutVertexArray = arrays.dynamicLayoutVertexArray;
var segment = arrays.segments.prepareSegment(4 * quads.length, arrays.layoutVertexArray, arrays.indexArray);
var glyphOffsetArrayStart = this.glyphOffsetArray.length;
var vertexStartIndex = segment.vertexLength;
for (var i = 0, list = quads; i < list.length; i += 1) {
var symbol = list[i];
var tl = symbol.tl,
tr = symbol.tr,
bl = symbol.bl,
br = symbol.br,
tex = symbol.tex;
var index = segment.vertexLength;
var y = symbol.glyphOffset[1];
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex);
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex);
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex);
addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex);
addDynamicAttributes(dynamicLayoutVertexArray, labelAnchor, 0);
indexArray.emplaceBack(index, index + 1, index + 2);
indexArray.emplaceBack(index + 1, index + 2, index + 3);
segment.vertexLength += 4;
segment.primitiveLength += 2;
this$1.glyphOffsetArray.emplaceBack(symbol.glyphOffset[0]);
}
arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y,
glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex,
lineStartIndex, lineLength, (labelAnchor.segment ),
sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0,
lineOffset[0], lineOffset[1],
writingMode, (false ));
arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature);
};
SymbolBucket.prototype._addCollisionDebugVertex = function _addCollisionDebugVertex (layoutVertexArray , collisionVertexArray , point , anchor , extrude ) {
collisionVertexArray.emplaceBack(0, 0);
return layoutVertexArray.emplaceBack(
// pos
point.x,
point.y,
// a_anchor_pos
anchor.x,
anchor.y,
// extrude
Math.round(extrude.x),
Math.round(extrude.y));
};
SymbolBucket.prototype.addCollisionDebugVertices = function addCollisionDebugVertices (x1 , y1 , x2 , y2 , arrays , boxAnchorPoint , symbolInstance , isCircle ) {
var segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);
var index = segment.vertexLength;
var layoutVertexArray = arrays.layoutVertexArray;
var collisionVertexArray = arrays.collisionVertexArray;
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, symbolInstance.anchor, new Point(x1, y1));
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, symbolInstance.anchor, new Point(x2, y1));
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, symbolInstance.anchor, new Point(x2, y2));
this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, symbolInstance.anchor, new Point(x1, y2));
segment.vertexLength += 4;
if (isCircle) {
var indexArray = (arrays.indexArray );
indexArray.emplaceBack(index, index + 1, index + 2);
indexArray.emplaceBack(index, index + 2, index + 3);
segment.primitiveLength += 2;
} else {
var indexArray$1 = (arrays.indexArray );
indexArray$1.emplaceBack(index, index + 1);
indexArray$1.emplaceBack(index + 1, index + 2);
indexArray$1.emplaceBack(index + 2, index + 3);
indexArray$1.emplaceBack(index + 3, index);
segment.primitiveLength += 4;
}
};
SymbolBucket.prototype.generateCollisionDebugBuffers = function generateCollisionDebugBuffers () {
var this$1 = this;
for (var i$1 = 0, list = this$1.symbolInstances; i$1 < list.length; i$1 += 1) {
var symbolInstance = list[i$1];
symbolInstance.textCollisionFeature = {boxStartIndex: symbolInstance.textBoxStartIndex, boxEndIndex: symbolInstance.textBoxEndIndex};
symbolInstance.iconCollisionFeature = {boxStartIndex: symbolInstance.iconBoxStartIndex, boxEndIndex: symbolInstance.iconBoxEndIndex};
for (var i = 0; i < 2; i++) {
var feature = symbolInstance[i === 0 ? 'textCollisionFeature' : 'iconCollisionFeature'];
if (!feature) { continue; }
for (var b = feature.boxStartIndex; b < feature.boxEndIndex; b++) {
var box = (this$1.collisionBoxArray.get(b) );
var x1 = box.x1;
var y1 = box.y1;
var x2 = box.x2;
var y2 = box.y2;
// If the radius > 0, this collision box is actually a circle
// The data we add to the buffers is exactly the same, but we'll render with a different shader.
var isCircle = box.radius > 0;
this$1.addCollisionDebugVertices(x1, y1, x2, y2, isCircle ? this$1.collisionCircle : this$1.collisionBox, box.anchorPoint, symbolInstance, isCircle);
}
}
}
};
// These flat arrays are meant to be quicker to iterate over than the source
// CollisionBoxArray
SymbolBucket.prototype.deserializeCollisionBoxes = function deserializeCollisionBoxes (collisionBoxArray , textStartIndex , textEndIndex , iconStartIndex , iconEndIndex ) {
var collisionArrays = {};
for (var k = textStartIndex; k < textEndIndex; k++) {
var box = (collisionBoxArray.get(k) );
if (box.radius === 0) {
collisionArrays.textBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY };
break; // Only one box allowed per instance
} else {
if (!collisionArrays.textCircles) {
collisionArrays.textCircles = [];
}
var used = 1; // May be updated at collision detection time
collisionArrays.textCircles.push(box.anchorPointX, box.anchorPointY, box.radius, box.signedDistanceFromAnchor, used);
}
}
for (var k$1 = iconStartIndex; k$1 < iconEndIndex; k$1++) {
// An icon can only have one box now, so this indexing is a bit vestigial...
var box$1 = (collisionBoxArray.get(k$1) );
if (box$1.radius === 0) {
collisionArrays.iconBox = { x1: box$1.x1, y1: box$1.y1, x2: box$1.x2, y2: box$1.y2, anchorPointX: box$1.anchorPointX, anchorPointY: box$1.anchorPointY };
break; // Only one box allowed per instance
}
}
return collisionArrays;
};
SymbolBucket.prototype.hasTextData = function hasTextData () {
return this.text.segments.get().length > 0;
};
SymbolBucket.prototype.hasIconData = function hasIconData () {
return this.icon.segments.get().length > 0;
};
SymbolBucket.prototype.hasCollisionBoxData = function hasCollisionBoxData () {
return this.collisionBox.segments.get().length > 0;
};
SymbolBucket.prototype.hasCollisionCircleData = function hasCollisionCircleData () {
return this.collisionCircle.segments.get().length > 0;
};
SymbolBucket.prototype.sortFeatures = function sortFeatures (angle ) {
var this$1 = this;
if (!this.sortFeaturesByY) { return; }
if (this.sortedAngle === angle) { return; }
this.sortedAngle = angle;
// The current approach to sorting doesn't sort across segments so don't try.
// Sorting within segments separately seemed not to be worth the complexity.
if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) { return; }
// If the symbols are allowed to overlap sort them by their vertical screen position.
// The index array buffer is rewritten to reference the (unchanged) vertices in the
// sorted order.
// To avoid sorting the actual symbolInstance array we sort an array of indexes.
var symbolInstanceIndexes = [];
for (var i = 0; i < this.symbolInstances.length; i++) {
symbolInstanceIndexes.push(i);
}
var sin = Math.sin(angle),
cos = Math.cos(angle);
symbolInstanceIndexes.sort(function (aIndex, bIndex) {
var a = this$1.symbolInstances[aIndex];
var b = this$1.symbolInstances[bIndex];
var aRotated = (sin * a.anchor.x + cos * a.anchor.y) | 0;
var bRotated = (sin * b.anchor.x + cos * b.anchor.y) | 0;
return (aRotated - bRotated) || (b.featureIndex - a.featureIndex);
});
this.text.indexArray.clear();
this.icon.indexArray.clear();
for (var i$2 = 0, list = symbolInstanceIndexes; i$2 < list.length; i$2 += 1) {
var i$1 = list[i$2];
var symbolInstance = this$1.symbolInstances[i$1];
for (var i$3 = 0, list$1 = symbolInstance.placedTextSymbolIndices; i$3 < list$1.length; i$3 += 1) {
var placedTextSymbolIndex = list$1[i$3];
var placedSymbol = this$1.text.placedSymbolArray.get(placedTextSymbolIndex);
var endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;
for (var vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {
this$1.text.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);
this$1.text.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);
}
}
var placedIcon = this$1.icon.placedSymbolArray.get(i$1);
if (placedIcon.numGlyphs) {
var vertexIndex$1 = placedIcon.vertexStartIndex;
this$1.icon.indexArray.emplaceBack(vertexIndex$1, vertexIndex$1 + 1, vertexIndex$1 + 2);
this$1.icon.indexArray.emplaceBack(vertexIndex$1 + 1, vertexIndex$1 + 2, vertexIndex$1 + 3);
}
}
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'],
shallow: ['symbolInstances']
});
// this constant is based on the size of StructArray indexes used in a symbol
// bucket--namely, glyphOffsetArrayStart
// eg the max valid UInt16 is 65,535
// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation
// lineStartIndex and textBoxStartIndex could potentially be concerns
// but we expect there to be many fewer boxes/lines than glyphs
SymbolBucket.MAX_GLYPHS = 65535;
SymbolBucket.addDynamicAttributes = addDynamicAttributes;
module.exports = SymbolBucket;
},{"../../symbol/anchor":221,"../../symbol/mergelines":229,"../../symbol/symbol_size":236,"../../symbol/transform_text":237,"../../util/script_detection":277,"../../util/verticalize_punctuation":285,"../../util/web_worker_transfer":286,"../array_types":44,"../index_array_type":60,"../load_geometry":61,"../program_configuration":63,"../segment":65,"./symbol_attributes":55,"@mapbox/point-geometry":4,"@mapbox/vector-tile":8}],57:[function(require,module,exports){
'use strict';//
var ref = require('../util/image');
var RGBAImage = ref.RGBAImage;
var util = require('../util/util');
var ref$1 = require('../util/web_worker_transfer');
var register = ref$1.register;
var Level = function Level(dim , border , data ) {
if (dim <= 0) { throw new RangeError('Level must have positive dimension'); }
this.dim = dim;
this.border = border;
this.stride = this.dim + 2 * this.border;
this.data = data || new Int32Array((this.dim + 2 * this.border) * (this.dim + 2 * this.border));
};
Level.prototype.set = function set (x , y , value ) {
this.data[this._idx(x, y)] = value + 65536;
};
Level.prototype.get = function get (x , y ) {
return this.data[this._idx(x, y)] - 65536;
};
Level.prototype._idx = function _idx (x , y ) {
if (x < -this.border || x >= this.dim + this.border || y < -this.border || y >= this.dim + this.border) { throw new RangeError('out of range source coordinates for DEM data'); }
return (y + this.border) * this.stride + (x + this.border);
};
register('Level', Level);
// DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders
// data can be populated either from a pngraw image tile or from serliazed data sent back from a worker. When data is initially
// loaded from a image tile, we decode the pixel values using the mapbox terrain-rgb tileset decoding formula, but we store the
// elevation data in a Level as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of
// integer overflow when creating the texture used in the hillshadePrepare step.
// DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8
// surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a
// tile's edge without backfilling from neighboring tiles.
var DEMData = function DEMData(uid , scale , data ) {
this.uid = uid;
this.scale = scale || 1;
// if no data is provided, use a temporary empty level to satisfy flow
this.level = data || new Level(256, 512);
this.loaded = !!data;
};
DEMData.prototype.loadFromImage = function loadFromImage (data ) {
var this$1 = this;
if (data.height !== data.width) { throw new RangeError('DEM tiles must be square'); }
// Build level 0
var level = this.level = new Level(data.width, data.width / 2);
var pixels = data.data;
// unpack
for (var y = 0; y < level.dim; y++) {
for (var x = 0; x < level.dim; x++) {
var i = y * level.dim + x;
var j = i * 4;
// decoding per https://blog.mapbox.com/global-elevation-data-6689f1d0ba65
level.set(x, y, this$1.scale * ((pixels[j] * 256 * 256 + pixels[j + 1] * 256.0 + pixels[j + 2]) / 10.0 - 10000.0));
}
}
// in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image
// with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring
// tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder
for (var x$1 = 0; x$1 < level.dim; x$1++) {
// left vertical border
level.set(-1, x$1, level.get(0, x$1));
// right vertical border
level.set(level.dim, x$1, level.get(level.dim - 1, x$1));
// left horizontal border
level.set(x$1, -1, level.get(x$1, 0));
// right horizontal border
level.set(x$1, level.dim, level.get(x$1, level.dim - 1));
}
// corners
level.set(-1, -1, level.get(0, 0));
level.set(level.dim, -1, level.get(level.dim - 1, 0));
level.set(-1, level.dim, level.get(0, level.dim - 1));
level.set(level.dim, level.dim, level.get(level.dim - 1, level.dim - 1));
this.loaded = true;
};
DEMData.prototype.getPixels = function getPixels () {
return new RGBAImage({width: this.level.dim + 2 * this.level.border, height: this.level.dim + 2 * this.level.border}, new Uint8Array(this.level.data.buffer));
};
DEMData.prototype.backfillBorder = function backfillBorder (borderTile , dx , dy ) {
var t = this.level;
var o = borderTile.level;
if (t.dim !== o.dim) { throw new Error('level mismatch (dem dimension)'); }
var _xMin = dx * t.dim,
_xMax = dx * t.dim + t.dim,
_yMin = dy * t.dim,
_yMax = dy * t.dim + t.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;
}
var xMin = util.clamp(_xMin, -t.border, t.dim + t.border);
var xMax = util.clamp(_xMax, -t.border, t.dim + t.border);
var yMin = util.clamp(_yMin, -t.border, t.dim + t.border);
var yMax = util.clamp(_yMax, -t.border, t.dim + t.border);
var ox = -dx * t.dim;
var oy = -dy * t.dim;
for (var y = yMin; y < yMax; y++) {
for (var x = xMin; x < xMax; x++) {
t.set(x, y, o.get(x + ox, y + oy));
}
}
};
register('DEMData', DEMData);
module.exports = {DEMData: DEMData, Level: Level};
},{"../util/image":271,"../util/util":283,"../util/web_worker_transfer":286}],58:[function(require,module,exports){
'use strict';//
/**
* The maximum value of a coordinate in the internal tile coordinate system. Coordinates of
* all source features normalized to this extent upon load.
*
* The value is a consequence of the following:
*
* * Vertex buffer store positions as signed 16 bit integers.
* * One bit is lost for signedness to support tile buffers.
* * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int.
* This is no longer the case but we're reserving this bit anyway.
* * One bit is lost to support features extending past the extent on the right edge of the tile.
* * This leaves us with 2^13 = 8192
*
* @private
* @readonly
*/
module.exports = 8192;
},{}],59:[function(require,module,exports){
'use strict';//
var Point = require('@mapbox/point-geometry');
var loadGeometry = require('./load_geometry');
var EXTENT = require('./extent');
var featureFilter = require('../style-spec/feature_filter');
var Grid = require('grid-index');
var DictionaryCoder = require('../util/dictionary_coder');
var vt = require('@mapbox/vector-tile');
var Protobuf = require('pbf');
var GeoJSONFeature = require('../util/vectortile_to_geojson');
var arraysIntersect = require('../util/util').arraysIntersect;
var ref = require('../source/tile_id');
var OverscaledTileID = ref.OverscaledTileID;
var ref$1 = require('../util/web_worker_transfer');
var register = ref$1.register;
var ref$2 = require('./array_types');
var FeatureIndexArray = ref$2.FeatureIndexArray;
var FeatureIndex = function FeatureIndex(tileID ,
overscaling ,
grid ,
featureIndexArray ) {
this.tileID = tileID;
this.overscaling = overscaling;
this.x = tileID.canonical.x;
this.y = tileID.canonical.y;
this.z = tileID.canonical.z;
this.grid = grid || new Grid(EXTENT, 16, 0);
this.featureIndexArray = featureIndexArray || new FeatureIndexArray();
};
FeatureIndex.prototype.insert = function insert (feature , geometry , featureIndex , sourceLayerIndex , bucketIndex ) {
var this$1 = this;
var key = this.featureIndexArray.length;
this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex);
for (var r = 0; r < geometry.length; r++) {
var ring = geometry[r];
var bbox = [Infinity, Infinity, -Infinity, -Infinity];
for (var i = 0; i < ring.length; i++) {
var 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);
}
this$1.grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);
}
};
// Finds features in this tile at a particular position.
FeatureIndex.prototype.query = function query (args , styleLayers ) {
if (!this.vtLayers) {
this.vtLayers = new vt.VectorTile(new Protobuf(this.rawTileData)).layers;
this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']);
}
var result = {};
var params = args.params || {},
pixelsToTileUnits = EXTENT / args.tileSize / args.scale,
filter = featureFilter(params.filter);
var queryGeometry = args.queryGeometry;
var additionalRadius = args.additionalRadius * pixelsToTileUnits;
var minX = Infinity;
var minY = Infinity;
var maxX = -Infinity;
var maxY = -Infinity;
for (var i = 0; i < queryGeometry.length; i++) {
var ring = queryGeometry[i];
for (var k = 0; k < ring.length; k++) {
var p = ring[k];
minX = Math.min(minX, p.x);
minY = Math.min(minY, p.y);
maxX = Math.max(maxX, p.x);
maxY = Math.max(maxY, p.y);
}
}
var matching = this.grid.query(minX - additionalRadius, minY - additionalRadius, maxX + additionalRadius, maxY + additionalRadius);
matching.sort(topDownFeatureComparator);
this.filterMatching(result, matching, this.featureIndexArray, queryGeometry, filter, params.layers, styleLayers, args.bearing, pixelsToTileUnits);
var matchingSymbols = args.collisionIndex ?
args.collisionIndex.queryRenderedSymbols(queryGeometry, this.tileID, EXTENT / args.tileSize, args.collisionBoxArray, args.sourceID, args.bucketInstanceIds) :
[];
matchingSymbols.sort();
this.filterMatching(result, matchingSymbols, args.collisionBoxArray, queryGeometry, filter, params.layers, styleLayers, args.bearing, pixelsToTileUnits);
return result;
};
FeatureIndex.prototype.filterMatching = function filterMatching (
result ,
matching ,
array ,
queryGeometry ,
filter ,
filterLayerIDs ,
styleLayers ,
bearing ,
pixelsToTileUnits
) {
var this$1 = this;
var previousIndex;
for (var k = 0; k < matching.length; k++) {
var index = matching[k];
// don't check the same feature more than once
if (index === previousIndex) { continue; }
previousIndex = index;
var match = array.get(index);
var layerIDs = this$1.bucketLayerIDs[match.bucketIndex];
if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs)) { continue; }
var sourceLayerName = this$1.sourceLayerCoder.decode(match.sourceLayerIndex);
var sourceLayer = this$1.vtLayers[sourceLayerName];
var feature = sourceLayer.feature(match.featureIndex);
if (!filter({zoom: this$1.tileID.overscaledZ}, feature)) { continue; }
var geometry = null;
for (var l = 0; l < layerIDs.length; l++) {
var layerID = layerIDs[l];
if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) {
continue;
}
var styleLayer = styleLayers[layerID];
if (!styleLayer) { continue; }
if (styleLayer.type !== 'symbol') {
// all symbols already match the style
if (!geometry) {
geometry = loadGeometry(feature);
}
if (!styleLayer.queryIntersectsFeature(queryGeometry, feature, geometry, this$1.z, bearing, pixelsToTileUnits)) {
continue;
}
}
var geojsonFeature = new GeoJSONFeature(feature, this$1.z, this$1.x, this$1.y);
(geojsonFeature ).layer = styleLayer.serialize();
var layerResult = result[layerID];
if (layerResult === undefined) {
layerResult = result[layerID] = [];
}
layerResult.push({ featureIndex: index, feature: geojsonFeature });
}
}
};
FeatureIndex.prototype.hasLayer = function hasLayer (id ) {
var this$1 = this;
for (var i = 0, list = this$1.bucketLayerIDs; i < list.length; i += 1) {
var layerIDs = list[i];
for (var i$1 = 0, list$1 = layerIDs; i$1 < list$1.length; i$1 += 1) {
var layerID = list$1[i$1];
if (id === layerID) { return true; }
}
}
return false;
};
register(
'FeatureIndex',
FeatureIndex,
{ omit: ['rawTileData', 'sourceLayerCoder', 'collisionIndex'] }
);
module.exports = FeatureIndex;
function topDownFeatureComparator(a, b) {
return b - a;
}
},{"../source/tile_id":120,"../style-spec/feature_filter":154,"../util/dictionary_coder":265,"../util/util":283,"../util/vectortile_to_geojson":284,"../util/web_worker_transfer":286,"./array_types":44,"./extent":58,"./load_geometry":61,"@mapbox/point-geometry":4,"@mapbox/vector-tile":8,"grid-index":25,"pbf":31}],60:[function(require,module,exports){
'use strict';//
/**
* An index array stores Uint16 indicies of vertexes in a corresponding vertex array. We use
* two kinds of index arrays: arrays storing groups of three indicies, forming triangles; and
* arrays storing pairs of indicies, forming line segments.
* @private
*/
module.exports = {
LineIndexArray: require('./array_types').LineIndexArray,
TriangleIndexArray: require('./array_types').TriangleIndexArray
};
},{"./array_types":44}],61:[function(require,module,exports){
'use strict';//
var util = require('../util/util');
var EXTENT = require('./extent');
// These bounds define the minimum and maximum supported coordinate values.
// While visible coordinates are within [0, EXTENT], tiles may theoretically
// contain cordinates within [-Infinity, Infinity]. Our range is limited by the
// number of bits used to represent the coordinate.
function createBounds(bits) {
return {
min: -1 * Math.pow(2, bits - 1),
max: Math.pow(2, bits - 1) - 1
};
}
var bounds = createBounds(16);
/**
* Loads a geometry from a VectorTileFeature and scales it to the common extent
* used internally.
* @param {VectorTileFeature} feature
* @private
*/
module.exports = function loadGeometry(feature ) {
var scale = EXTENT / feature.extent;
var geometry = feature.loadGeometry();
for (var r = 0; r < geometry.length; r++) {
var ring = geometry[r];
for (var p = 0; p < ring.length; p++) {
var point = ring[p];
// round here because mapbox-gl-native uses integers to represent
// points and we need to do the same to avoid renering differences.
point.x = Math.round(point.x * scale);
point.y = Math.round(point.y * scale);
if (point.x < bounds.min || point.x > bounds.max || point.y < bounds.min || point.y > bounds.max) {
util.warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');
}
}
}
return geometry;
};
},{"../util/util":283,"./extent":58}],62:[function(require,module,exports){
'use strict';//
var ref = require('../util/struct_array');
var createLayout = ref.createLayout;
module.exports = createLayout([
{ name: 'a_pos', type: 'Int16', components: 2 }
]);
},{"../util/struct_array":279}],63:[function(require,module,exports){
'use strict';//
var packUint8ToFloat = require('../shaders/encode_attribute').packUint8ToFloat;
var Color = require('../style-spec/util/color');
var ref = require('../util/web_worker_transfer');
var register = ref.register;
var ref$1 = require('../style/properties');
var PossiblyEvaluatedPropertyValue = ref$1.PossiblyEvaluatedPropertyValue;
var ref$2 = require('./array_types');
var StructArrayLayout1f4 = ref$2.StructArrayLayout1f4;
var StructArrayLayout2f8 = ref$2.StructArrayLayout2f8;
var StructArrayLayout4f16 = ref$2.StructArrayLayout4f16;
function packColor(color ) {
return [
packUint8ToFloat(255 * color.r, 255 * color.g),
packUint8ToFloat(255 * color.b, 255 * color.a)
];
}
/**
* `Binder` is the interface definition for the strategies for constructing,
* uploading, and binding paint property data as GLSL attributes.
*
* It has three implementations, one for each of the three strategies we use:
*
* * For _constant_ properties -- those whose value is a constant, or the constant
* result of evaluating a camera expression at a particular camera position -- we
* don't need a vertex buffer, and instead use a uniform.
* * For data expressions, we use a vertex buffer with a single attribute value,
* the evaluated result of the source function for the given feature.
* * For composite expressions, we use a vertex buffer with two attributes: min and
* max values covering the range of zooms at which we expect the tile to be
* displayed. These values are calculated by evaluating the composite expression for
* the given feature at strategically chosen zoom levels. In addition to this
* attribute data, we also use a uniform value which the shader uses to interpolate
* between the min and max value at the final displayed zoom level. The use of a
* uniform allows us to cheaply update the value on every frame.
*
* Note that the shader source varies depending on whether we're using a uniform or
* attribute. We dynamically compile shaders at runtime to accomodate this.
*
* @private
*/
var ConstantBinder = function ConstantBinder(value , name , type ) {
this.value = value;
this.name = name;
this.type = type;
this.statistics = { max: -Infinity };
};
ConstantBinder.prototype.defines = function defines () {
return [("#define HAS_UNIFORM_u_" + (this.name))];
};
ConstantBinder.prototype.populatePaintArray = function populatePaintArray () {};
ConstantBinder.prototype.upload = function upload () {};
ConstantBinder.prototype.destroy = function destroy () {};
ConstantBinder.prototype.setUniforms = function setUniforms (context ,
program ,
globals ,
currentValue ) {
var value = currentValue.constantOr(this.value);
var gl = context.gl;
if (this.type === 'color') {
gl.uniform4f(program.uniforms[("u_" + (this.name))], value.r, value.g, value.b, value.a);
} else {
gl.uniform1f(program.uniforms[("u_" + (this.name))], value);
}
};
var SourceExpressionBinder = function SourceExpressionBinder(expression , name , type ) {
this.expression = expression;
this.name = name;
this.type = type;
this.statistics = { max: -Infinity };
var PaintVertexArray = type === 'color' ? StructArrayLayout2f8 : StructArrayLayout1f4;
this.paintVertexAttributes = [{
name: ("a_" + name),
type: 'Float32',
components: type === 'color' ? 2 : 1,
offset: 0
}];
this.paintVertexArray = new PaintVertexArray();
};
SourceExpressionBinder.prototype.defines = function defines () {
return [];
};
SourceExpressionBinder.prototype.populatePaintArray = function populatePaintArray (length , feature ) {
var paintArray = this.paintVertexArray;
var start = paintArray.length;
paintArray.reserve(length);
var value = this.expression.evaluate({zoom: 0}, feature);
if (this.type === 'color') {
var color = packColor(value);
for (var i = start; i < length; i++) {
paintArray.emplaceBack(color[0], color[1]);
}
} else {
for (var i$1 = start; i$1 < length; i$1++) {
paintArray.emplaceBack(value);
}
this.statistics.max = Math.max(this.statistics.max, value);
}
};
SourceExpressionBinder.prototype.upload = function upload (context ) {
if (this.paintVertexArray) {
this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes);
}
};
SourceExpressionBinder.prototype.destroy = function destroy () {
if (this.paintVertexBuffer) {
this.paintVertexBuffer.destroy();
}
};
SourceExpressionBinder.prototype.setUniforms = function setUniforms (context , program ) {
context.gl.uniform1f(program.uniforms[("a_" + (this.name) + "_t")], 0);
};
var CompositeExpressionBinder = function CompositeExpressionBinder(expression , name , type , useIntegerZoom , zoom ) {
this.expression = expression;
this.name = name;
this.type = type;
this.useIntegerZoom = useIntegerZoom;
this.zoom = zoom;
this.statistics = { max: -Infinity };
var PaintVertexArray = type === 'color' ? StructArrayLayout4f16 : StructArrayLayout2f8;
this.paintVertexAttributes = [{
name: ("a_" + name),
type: 'Float32',
components: type === 'color' ? 4 : 2,
offset: 0
}];
this.paintVertexArray = new PaintVertexArray();
};
CompositeExpressionBinder.prototype.defines = function defines () {
return [];
};
CompositeExpressionBinder.prototype.populatePaintArray = function populatePaintArray (length , feature ) {
var paintArray = this.paintVertexArray;
var start = paintArray.length;
paintArray.reserve(length);
var min = this.expression.evaluate({zoom: this.zoom}, feature);
var max = this.expression.evaluate({zoom: this.zoom + 1}, feature);
if (this.type === 'color') {
var minColor = packColor(min);
var maxColor = packColor(max);
for (var i = start; i < length; i++) {
paintArray.emplaceBack(minColor[0], minColor[1], maxColor[0], maxColor[1]);
}
} else {
for (var i$1 = start; i$1 < length; i$1++) {
paintArray.emplaceBack(min, max);
}
this.statistics.max = Math.max(this.statistics.max, min, max);
}
};
CompositeExpressionBinder.prototype.upload = function upload (context ) {
if (this.paintVertexArray) {
this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes);
}
};
CompositeExpressionBinder.prototype.destroy = function destroy () {
if (this.paintVertexBuffer) {
this.paintVertexBuffer.destroy();
}
};
CompositeExpressionBinder.prototype.interpolationFactor = function interpolationFactor (currentZoom ) {
if (this.useIntegerZoom) {
return this.expression.interpolationFactor(Math.floor(currentZoom), this.zoom, this.zoom + 1);
} else {
return this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1);
}
};
CompositeExpressionBinder.prototype.setUniforms = function setUniforms (context , program , globals ) {
context.gl.uniform1f(program.uniforms[("a_" + (this.name) + "_t")], this.interpolationFactor(globals.zoom));
};
/**
* ProgramConfiguration contains the logic for binding style layer properties and tile
* layer feature data into GL program uniforms and vertex attributes.
*
* Non-data-driven property values are bound to shader uniforms. Data-driven property
* values are bound to vertex attributes. In order to support a uniform GLSL syntax over
* both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma`
* abstraction, which ProgramConfiguration is responsible for implementing. At runtime,
* it examines the attributes of a particular layer, combines this with fixed knowledge
* about how layers of the particular type are implemented, and determines which uniforms
* and vertex attributes will be required. It can then substitute the appropriate text
* into the shader source code, create and link a program, and bind the uniforms and
* vertex attributes in preparation for drawing.
*
* When a vector tile is parsed, this same configuration information is used to
* populate the attribute buffers needed for data-driven styling using the zoom
* level and feature property data.
*
* @private
*/
var ProgramConfiguration = function ProgramConfiguration() {
this.binders = {};
this.cacheKey = '';
this._buffers = [];
};
ProgramConfiguration.createDynamic = function createDynamic (layer , zoom , filterProperties ) {
var self = new ProgramConfiguration();
var keys = [];
for (var property in layer.paint._values) {
if (!filterProperties(property)) { continue; }
var value = layer.paint.get(property);
if (!(value instanceof PossiblyEvaluatedPropertyValue) || !value.property.specification['property-function']) {
continue;
}
var name = paintAttributeName(property, layer.type);
var type = value.property.specification.type;
var useIntegerZoom = value.property.useIntegerZoom;
if (value.value.kind === 'constant') {
self.binders[property] = new ConstantBinder(value.value, name, type);
keys.push(("/u_" + name));
} else if (value.value.kind === 'source') {
self.binders[property] = new SourceExpressionBinder(value.value, name, type);
keys.push(("/a_" + name));
} else {
self.binders[property] = new CompositeExpressionBinder(value.value, name, type, useIntegerZoom, zoom);
keys.push(("/z_" + name));
}
}
self.cacheKey = keys.sort().join('');
return self;
};
ProgramConfiguration.prototype.populatePaintArrays = function populatePaintArrays (length , feature ) {
var this$1 = this;
for (var property in this$1.binders) {
this$1.binders[property].populatePaintArray(length, feature);
}
};
ProgramConfiguration.prototype.defines = function defines () {
var this$1 = this;
var result = [];
for (var property in this$1.binders) {
result.push.apply(result, this$1.binders[property].defines());
}
return result;
};
ProgramConfiguration.prototype.setUniforms = function setUniforms (context , program , properties , globals ) {
var this$1 = this;
for (var property in this$1.binders) {
var binder = this$1.binders[property];
binder.setUniforms(context, program, globals, properties.get(property));
}
};
ProgramConfiguration.prototype.getPaintVertexBuffers = function getPaintVertexBuffers () {
return this._buffers;
};
ProgramConfiguration.prototype.upload = function upload (context ) {
var this$1 = this;
for (var property in this$1.binders) {
this$1.binders[property].upload(context);
}
var buffers = [];
for (var property$1 in this$1.binders) {
var binder = this$1.binders[property$1];
if ((binder instanceof SourceExpressionBinder ||
binder instanceof CompositeExpressionBinder) &&
binder.paintVertexBuffer
) {
buffers.push(binder.paintVertexBuffer);
}
}
this._buffers = buffers;
};
ProgramConfiguration.prototype.destroy = function destroy () {
var this$1 = this;
for (var property in this$1.binders) {
this$1.binders[property].destroy();
}
};
var ProgramConfigurationSet = function ProgramConfigurationSet(layoutAttributes , layers , zoom , filterProperties) {
var this$1 = this;
if ( filterProperties === void 0 ) filterProperties = function () { return true; };
this.programConfigurations = {};
for (var i = 0, list = layers; i < list.length; i += 1) {
var layer = list[i];
this$1.programConfigurations[layer.id] = ProgramConfiguration.createDynamic(layer, zoom, filterProperties);
this$1.programConfigurations[layer.id].layoutAttributes = layoutAttributes;
}
};
ProgramConfigurationSet.prototype.populatePaintArrays = function populatePaintArrays (length , feature ) {
var this$1 = this;
for (var key in this$1.programConfigurations) {
this$1.programConfigurations[key].populatePaintArrays(length, feature);
}
};
ProgramConfigurationSet.prototype.get = function get (layerId ) {
return this.programConfigurations[layerId];
};
ProgramConfigurationSet.prototype.upload = function upload (context ) {
var this$1 = this;
for (var layerId in this$1.programConfigurations) {
this$1.programConfigurations[layerId].upload(context);
}
};
ProgramConfigurationSet.prototype.destroy = function destroy () {
var this$1 = this;
for (var layerId in this$1.programConfigurations) {
this$1.programConfigurations[layerId].destroy();
}
};
// paint property arrays
function paintAttributeName(property, type) {
var attributeNameExceptions = {
'text-opacity': 'opacity',
'icon-opacity': 'opacity',
'text-color': 'fill_color',
'icon-color': 'fill_color',
'text-halo-color': 'halo_color',
'icon-halo-color': 'halo_color',
'text-halo-blur': 'halo_blur',
'icon-halo-blur': 'halo_blur',
'text-halo-width': 'halo_width',
'icon-halo-width': 'halo_width',
'line-gap-width': 'gapwidth'
};
return attributeNameExceptions[property] ||
property.replace((type + "-"), '').replace(/-/g, '_');
}
register('ConstantBinder', ConstantBinder);
register('SourceExpressionBinder', SourceExpressionBinder);
register('CompositeExpressionBinder', CompositeExpressionBinder);
register('ProgramConfiguration', ProgramConfiguration, {omit: ['_buffers']});
register('ProgramConfigurationSet', ProgramConfigurationSet);
module.exports = {
ProgramConfiguration: ProgramConfiguration,
ProgramConfigurationSet: ProgramConfigurationSet
};
},{"../shaders/encode_attribute":102,"../style-spec/util/color":159,"../style/properties":194,"../util/web_worker_transfer":286,"./array_types":44}],64:[function(require,module,exports){
'use strict';//
var ref = require('../util/struct_array');
var createLayout = ref.createLayout;
module.exports = createLayout([
{ name: 'a_pos', type: 'Int16', components: 2 },
{ name: 'a_texture_pos', type: 'Int16', components: 2 }
]);
},{"../util/struct_array":279}],65:[function(require,module,exports){
'use strict';//
var ref = require('../util/util');
var warnOnce = ref.warnOnce;
var ref$1 = require('../util/web_worker_transfer');
var register = ref$1.register;
var MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;
var SegmentVector = function SegmentVector(segments) {
if ( segments === void 0 ) segments = [];
this.segments = segments;
};
SegmentVector.prototype.prepareSegment = function prepareSegment (numVertices , layoutVertexArray , indexArray ) {
var segment = this.segments[this.segments.length - 1];
if (numVertices > MAX_VERTEX_ARRAY_LENGTH) { warnOnce(("Max vertices per segment is " + MAX_VERTEX_ARRAY_LENGTH + ": bucket requested " + numVertices)); }
if (!segment || segment.vertexLength + numVertices > module.exports.MAX_VERTEX_ARRAY_LENGTH) {
segment = ({
vertexOffset: layoutVertexArray.length,
primitiveOffset: indexArray.length,
vertexLength: 0,
primitiveLength: 0
} );
this.segments.push(segment);
}
return segment;
};
SegmentVector.prototype.get = function get () {
return this.segments;
};
SegmentVector.prototype.destroy = function destroy () {
var this$1 = this;
for (var i = 0, list = this$1.segments; i < list.length; i += 1) {
var segment = list[i];
for (var k in segment.vaos) {
segment.vaos[k].destroy();
}
}
};
register('SegmentVector', SegmentVector);
module.exports = {
SegmentVector: SegmentVector,
/**
* The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit
* addressing of vertex buffers.
* @private
* @readonly
*/
MAX_VERTEX_ARRAY_LENGTH: MAX_VERTEX_ARRAY_LENGTH
};
},{"../util/util":283,"../util/web_worker_transfer":286}],66:[function(require,module,exports){
'use strict';//
/**
* A coordinate is a column, row, zoom combination, often used
* as the data component of a tile.
*
* @param {number} column
* @param {number} row
* @param {number} zoom
* @private
*/
var Coordinate = function Coordinate(column , row , zoom ) {
this.column = column;
this.row = row;
this.zoom = zoom;
};
/**
* Create a clone of this coordinate that can be mutated without
* changing the original coordinate
*
* @returns {Coordinate} clone
* @private
* var coord = new Coordinate(0, 0, 0);
* var c2 = coord.clone();
* // since coord is cloned, modifying a property of c2 does
* // not modify it.
* c2.zoom = 2;
*/
Coordinate.prototype.clone = function clone () {
return new Coordinate(this.column, this.row, this.zoom);
};
/**
* Zoom this coordinate to a given zoom level. This returns a new
* coordinate object, not mutating the old one.
*
* @param {number} zoom
* @returns {Coordinate} zoomed coordinate
* @private
* @example
* var coord = new Coordinate(0, 0, 0);
* var c2 = coord.zoomTo(1);
* c2 // equals new Coordinate(0, 0, 1);
*/
Coordinate.prototype.zoomTo = function zoomTo (zoom ) { return this.clone()._zoomTo(zoom); };
/**
* Subtract the column and row values of this coordinate from those
* of another coordinate. The other coordinat will be zoomed to the
* same level as `this` before the subtraction occurs
*
* @param {Coordinate} c other coordinate
* @returns {Coordinate} result
* @private
*/
Coordinate.prototype.sub = function sub (c ) { return this.clone()._sub(c); };
Coordinate.prototype._zoomTo = function _zoomTo (zoom ) {
var scale = Math.pow(2, zoom - this.zoom);
this.column *= scale;
this.row *= scale;
this.zoom = zoom;
return this;
};
Coordinate.prototype._sub = function _sub (c ) {
c = c.zoomTo(this.zoom);
this.column -= c.column;
this.row -= c.row;
return this;
};
module.exports = Coordinate;
},{}],67:[function(require,module,exports){
'use strict';//
var wrap = require('../util/util').wrap;
/**
* A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.
*
* Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.
*
* Note that any Mapbox GL method that accepts a `LngLat` object as an argument or option
* can also accept an `Array` of two numbers and will perform an implicit conversion.
* This flexible type is documented as {@link LngLatLike}.
*
* @param {number} lng Longitude, measured in degrees.
* @param {number} lat Latitude, measured in degrees.
* @example
* var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
* @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)
* @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)
* @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
* @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)
*/
var LngLat = function LngLat(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
* var ll = new mapboxgl.LngLat(286.0251, 40.7736);
* var wrapped = ll.wrap();
* wrapped.lng; // = -73.9749
*/
LngLat.prototype.wrap = function wrap$1 () {
return new LngLat(wrap(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
* var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
* ll.toArray(); // = [-73.9749, 40.7736]
*/
LngLat.prototype.toArray = function 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
* var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
* ll.toString(); // = "LngLat(-73.9749, 40.7736)"
*/
LngLat.prototype.toString = function toString () {
return ("LngLat(" + (this.lng) + ", " + (this.lat) + ")");
};
/**
* Returns a `LngLatBounds` from the coordinates extended by a given `radius`.
*
* @param {number} radius Distance in meters from the coordinates to extend the bounds.
* @returns {LngLatBounds} A new `LngLatBounds` object representing the coordinates extended by the `radius`.
* @example
* var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
* ll.toBounds(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]
*/
LngLat.prototype.toBounds = function toBounds (radius ) {
var earthCircumferenceInMetersAtEquator = 40075017;
var latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator,
lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
var LngLatBounds = require('./lng_lat_bounds');
return new LngLatBounds(new LngLat(this.lng - lngAccuracy, this.lat - latAccuracy),
new LngLat(this.lng + lngAccuracy, this.lat + latAccuracy));
};
/**
* Converts an array of two numbers to a `LngLat` object.
*
* If a `LngLat` object is passed in, the function returns it unchanged.
*
* @param {LngLatLike} input An array of two numbers to convert, or a `LngLat` object to return.
* @returns {LngLat} A new `LngLat` object, if a conversion occurred, or the original `LngLat` object.
* @example
* var arr = [-73.9749, 40.7736];
* var ll = mapboxgl.LngLat.convert(arr);
* ll; // = LngLat {lng: -73.9749, lat: 40.7736}
*/
LngLat.convert = function 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(input.lng), Number(input.lat));
}
throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]");
};
/**
* A {@link LngLat} object, an array of two numbers representing longitude and latitude,
* or an object with `lng` and `lat` properties.
*
* @typedef {LngLat | {lng: number, lat: number} | [number, number]} LngLatLike
* @example
* var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
* var v2 = [-122.420679, 37.772537];
*/
module.exports = LngLat;
},{"../util/util":283,"./lng_lat_bounds":68}],68:[function(require,module,exports){
'use strict';//
var LngLat = require('./lng_lat');
/**
* A `LngLatBounds` object represents a geographical bounding box,
* defined by its southwest and northeast points in longitude and latitude.
*
* If no arguments are provided to the constructor, a `null` bounding box is created.
*
* Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option
* can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion.
* This flexible type is documented as {@link LngLatBoundsLike}.
*
* @param {LngLatLike} [sw] The southwest corner of the bounding box.
* @param {LngLatLike} [ne] The northeast corner of the bounding box.
* @example
* var sw = new mapboxgl.LngLat(-73.9876, 40.7661);
* var ne = new mapboxgl.LngLat(-73.9397, 40.8002);
* var llb = new mapboxgl.LngLatBounds(sw, ne);
*/
var LngLatBounds = function LngLatBounds(sw , ne ) {
if (!sw) {
return;
} else if (ne) {
this.setSouthWest(sw).setNorthEast(ne);
} else if (sw.length === 4) {
this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]);
} else {
this.setSouthWest(sw[0]).setNorthEast(sw[1]);
}
};
/**
* Set the northeast corner of the bounding box
*
* @param {LngLatLike} ne
* @returns {LngLatBounds} `this`
*/
LngLatBounds.prototype.setNorthEast = function 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
* @returns {LngLatBounds} `this`
*/
LngLatBounds.prototype.setSouthWest = function 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 LngLat or LngLatBounds.
*
* @param {LngLat|LngLatBounds} obj object to extend to
* @returns {LngLatBounds} `this`
*/
LngLatBounds.prototype.extend = function extend (obj) {
var sw = this._sw,
ne = this._ne;
var 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.every(Array.isArray)) {
return this.extend(LngLatBounds.convert(obj));
} else {
return this.extend(LngLat.convert(obj));
}
}
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
* var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
* llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}
*/
LngLatBounds.prototype.getCenter = function 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.
*/
LngLatBounds.prototype.getSouthWest = function getSouthWest () { return this._sw; };
/**
* Returns the northeast corner of the bounding box.
*
* @returns {LngLat} The northeast corner of the bounding box.
*/
LngLatBounds.prototype.getNorthEast = function getNorthEast () { return this._ne; };
/**
* Returns the northwest corner of the bounding box.
*
* @returns {LngLat} The northwest corner of the bounding box.
*/
LngLatBounds.prototype.getNorthWest = function 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.
*/
LngLatBounds.prototype.getSouthEast = function 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.
*/
LngLatBounds.prototype.getWest = function getWest () { return this._sw.lng; };
/**
* Returns the south edge of the bounding box.
*
* @returns {number} The south edge of the bounding box.
*/
LngLatBounds.prototype.getSouth = function getSouth () { return this._sw.lat; };
/**
* Returns the east edge of the bounding box.
*
* @returns {number} The east edge of the bounding box.
*/
LngLatBounds.prototype.getEast = function getEast () { return this._ne.lng; };
/**
* Returns the north edge of the bounding box.
*
* @returns {number} The north edge of the bounding box.
*/
LngLatBounds.prototype.getNorth = function 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
* var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
* llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]
*/
LngLatBounds.prototype.toArray = function 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
* var 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))"
*/
LngLatBounds.prototype.toString = function 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.
*/
LngLatBounds.prototype.isEmpty = function isEmpty () {
return !(this._sw && this._ne);
};
/**
* 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
* var arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
* var llb = mapboxgl.LngLatBounds.convert(arr);
* llb; // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}
*/
LngLatBounds.convert = function convert (input ) {
if (!input || input instanceof LngLatBounds) { return input; }
return new LngLatBounds(input);
};
/**
* A {@link LngLatBounds} object, an array of {@link LngLatLike} objects in [sw, ne] order,
* or an array of numbers in [west, south, east, north] order.
*
* @typedef {LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number]} LngLatBoundsLike
* @example
* var v1 = new mapboxgl.LngLatBounds(
* new mapboxgl.LngLat(-73.9876, 40.7661),
* new mapboxgl.LngLat(-73.9397, 40.8002)
* );
* var v2 = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])
* var v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
*/
module.exports = LngLatBounds;
},{"./lng_lat":67}],69:[function(require,module,exports){
'use strict';//
var LngLat = require('./lng_lat'),
Point = require('@mapbox/point-geometry'),
Coordinate = require('./coordinate'),
util = require('../util/util'),
interp = require('../style-spec/util/interpolate').number,
tileCover = require('../util/tile_cover');
var ref = require('../source/tile_id');
var CanonicalTileID = ref.CanonicalTileID;
var UnwrappedTileID = ref.UnwrappedTileID;
var EXTENT = require('../data/extent'),
glmatrix = require('@mapbox/gl-matrix');
var vec4 = glmatrix.vec4,
mat4 = glmatrix.mat4,
mat2 = glmatrix.mat2;
/**
* A single transform, generally used for a single tile to be
* scaled, rotated, and zoomed.
* @private
*/
var Transform = function Transform(minZoom , maxZoom , renderWorldCopies ) {
this.tileSize = 512; // constant
this._renderWorldCopies = renderWorldCopies === undefined ? true : renderWorldCopies;
this._minZoom = minZoom || 0;
this._maxZoom = maxZoom || 22;
this.latRange = [-85.05113, 85.05113];
this.width = 0;
this.height = 0;
this._center = new LngLat(0, 0);
this.zoom = 0;
this.angle = 0;
this._fov = 0.6435011087932844;
this._pitch = 0;
this._unmodified = true;
this._posMatrixCache = {};
this._alignedPosMatrixCache = {};
};
var prototypeAccessors = { minZoom: {},maxZoom: {},renderWorldCopies: {},worldSize: {},centerPoint: {},size: {},bearing: {},pitch: {},fov: {},zoom: {},center: {},unmodified: {},x: {},y: {},point: {} };
Transform.prototype.clone = function clone () {
var clone = new Transform(this._minZoom, this._maxZoom, this._renderWorldCopies);
clone.tileSize = this.tileSize;
clone.latRange = this.latRange;
clone.width = this.width;
clone.height = this.height;
clone._center = this._center;
clone.zoom = this.zoom;
clone.angle = this.angle;
clone._fov = this._fov;
clone._pitch = this._pitch;
clone._unmodified = this._unmodified;
clone._calcMatrices();
return clone;
};
prototypeAccessors.minZoom.get = function () { return this._minZoom; };
prototypeAccessors.minZoom.set = function (zoom ) {
if (this._minZoom === zoom) { return; }
this._minZoom = zoom;
this.zoom = Math.max(this.zoom, zoom);
};
prototypeAccessors.maxZoom.get = function () { return this._maxZoom; };
prototypeAccessors.maxZoom.set = function (zoom ) {
if (this._maxZoom === zoom) { return; }
this._maxZoom = zoom;
this.zoom = Math.min(this.zoom, zoom);
};
prototypeAccessors.renderWorldCopies.get = function () {
return this._renderWorldCopies;
};
prototypeAccessors.worldSize.get = function () {
return this.tileSize * this.scale;
};
prototypeAccessors.centerPoint.get = function () {
return this.size._div(2);
};
prototypeAccessors.size.get = function () {
return new Point(this.width, this.height);
};
prototypeAccessors.bearing.get = function () {
return -this.angle / Math.PI * 180;
};
prototypeAccessors.bearing.set = function (bearing ) {
var b = -util.wrap(bearing, -180, 180) * Math.PI / 180;
if (this.angle === b) { return; }
this._unmodified = false;
this.angle = b;
this._calcMatrices();
// 2x2 matrix for rotating points
this.rotationMatrix = mat2.create();
mat2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);
};
prototypeAccessors.pitch.get = function () {
return this._pitch / Math.PI * 180;
};
prototypeAccessors.pitch.set = function (pitch ) {
var p = util.clamp(pitch, 0, 60) / 180 * Math.PI;
if (this._pitch === p) { return; }
this._unmodified = false;
this._pitch = p;
this._calcMatrices();
};
prototypeAccessors.fov.get = function () {
return this._fov / Math.PI * 180;
};
prototypeAccessors.fov.set = function (fov ) {
fov = Math.max(0.01, Math.min(60, fov));
if (this._fov === fov) { return; }
this._unmodified = false;
this._fov = fov / 180 * Math.PI;
this._calcMatrices();
};
prototypeAccessors.zoom.get = function () { return this._zoom; };
prototypeAccessors.zoom.set = function (zoom ) {
var z = Math.min(Math.max(zoom, this.minZoom), this.maxZoom);
if (this._zoom === z) { return; }
this._unmodified = false;
this._zoom = z;
this.scale = this.zoomScale(z);
this.tileZoom = Math.floor(z);
this.zoomFraction = z - this.tileZoom;
this._constrain();
this._calcMatrices();
};
prototypeAccessors.center.get = function () { return this._center; };
prototypeAccessors.center.set = function (center ) {
if (center.lat === this._center.lat && center.lng === this._center.lng) { return; }
this._unmodified = false;
this._center = center;
this._constrain();
this._calcMatrices();
};
/**
* Return a zoom level that will cover all tiles the transform
* @param {Object} options
* @param {number} options.tileSize
* @param {boolean} options.roundZoom
* @returns {number} zoom level
*/
Transform.prototype.coveringZoomLevel = function coveringZoomLevel (options ) {
return (options.roundZoom ? Math.round : Math.floor)(
this.zoom + this.scaleZoom(this.tileSize / options.tileSize)
);
};
/**
* Return any "wrapped" copies of a given tile coordinate that are visible
* in the current view.
*
* @private
*/
Transform.prototype.getVisibleUnwrappedCoordinates = function getVisibleUnwrappedCoordinates (tileID ) {
var ul = this.pointCoordinate(new Point(0, 0), 0);
var ur = this.pointCoordinate(new Point(this.width, 0), 0);
var w0 = Math.floor(ul.column);
var w1 = Math.floor(ur.column);
var result = [new UnwrappedTileID(0, tileID)];
if (this._renderWorldCopies) {
for (var w = w0; w <= w1; w++) {
if (w === 0) { continue; }
result.push(new UnwrappedTileID(w, tileID));
}
}
return result;
};
/**
* 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
* @param {boolean} options.renderWorldCopies
* @returns {Array<Tile>} tiles
*/
Transform.prototype.coveringTiles = function coveringTiles (
options
) {
var z = this.coveringZoomLevel(options);
var actualZ = z;
if (options.minzoom !== undefined && z < options.minzoom) { return []; }
if (options.maxzoom !== undefined && z > options.maxzoom) { z = options.maxzoom; }
var centerCoord = this.pointCoordinate(this.centerPoint, z);
var centerPoint = new Point(centerCoord.column - 0.5, centerCoord.row - 0.5);
var cornerCoords = [
this.pointCoordinate(new Point(0, 0), z),
this.pointCoordinate(new Point(this.width, 0), z),
this.pointCoordinate(new Point(this.width, this.height), z),
this.pointCoordinate(new Point(0, this.height), z)
];
return tileCover(z, cornerCoords, options.reparseOverscaled ? actualZ : z, this._renderWorldCopies)
.sort(function (a, b) { return centerPoint.dist(a.canonical) - centerPoint.dist(b.canonical); });
};
Transform.prototype.resize = function resize (width , height ) {
this.width = width;
this.height = height;
this.pixelsToGLUnits = [2 / width, -2 / height];
this._constrain();
this._calcMatrices();
};
prototypeAccessors.unmodified.get = function () { return this._unmodified; };
Transform.prototype.zoomScale = function zoomScale (zoom ) { return Math.pow(2, zoom); };
Transform.prototype.scaleZoom = function scaleZoom (scale ) { return Math.log(scale) / Math.LN2; };
Transform.prototype.project = function project (lnglat ) {
return new Point(
this.lngX(lnglat.lng),
this.latY(lnglat.lat));
};
Transform.prototype.unproject = function unproject (point) {
return new LngLat(
this.xLng(point.x),
this.yLat(point.y));
};
prototypeAccessors.x.get = function () { return this.lngX(this.center.lng); };
prototypeAccessors.y.get = function () { return this.latY(this.center.lat); };
prototypeAccessors.point.get = function () { return new Point(this.x, this.y); };
/**
* latitude to absolute x coord
* @returns {number} pixel coordinate
*/
Transform.prototype.lngX = function lngX (lng ) {
return (180 + lng) * this.worldSize / 360;
};
/**
* latitude to absolute y coord
* @returns {number} pixel coordinate
*/
Transform.prototype.latY = function latY (lat ) {
var y = 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360));
return (180 - y) * this.worldSize / 360;
};
Transform.prototype.xLng = function xLng (x) {
return x * 360 / this.worldSize - 180;
};
Transform.prototype.yLat = function yLat (y) {
var y2 = 180 - y * 360 / this.worldSize;
return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;
};
Transform.prototype.setLocationAtPoint = function setLocationAtPoint (lnglat , point ) {
var translate = this.pointCoordinate(point)._sub(this.pointCoordinate(this.centerPoint));
this.center = this.coordinateLocation(this.locationCoordinate(lnglat)._sub(translate));
if (this._renderWorldCopies) {
this.center = this.center.wrap();
}
};
/**
* Given a location, return the screen point that corresponds to it
* @param {LngLat} lnglat location
* @returns {Point} screen point
*/
Transform.prototype.locationPoint = function locationPoint (lnglat ) {
return this.coordinatePoint(this.locationCoordinate(lnglat));
};
/**
* Given a point on screen, return its lnglat
* @param {Point} p screen point
* @returns {LngLat} lnglat location
*/
Transform.prototype.pointLocation = function pointLocation (p ) {
return this.coordinateLocation(this.pointCoordinate(p));
};
/**
* Given a geographical lnglat, return an unrounded
* coordinate that represents it at this transform's zoom level.
* @param {LngLat} lnglat
* @returns {Coordinate}
*/
Transform.prototype.locationCoordinate = function locationCoordinate (lnglat ) {
return new Coordinate(
this.lngX(lnglat.lng) / this.tileSize,
this.latY(lnglat.lat) / this.tileSize,
this.zoom).zoomTo(this.tileZoom);
};
/**
* Given a Coordinate, return its geographical position.
* @param {Coordinate} coord
* @returns {LngLat} lnglat
*/
Transform.prototype.coordinateLocation = function coordinateLocation (coord) {
var zoomedCoord = coord.zoomTo(this.zoom);
return new LngLat(
this.xLng(zoomedCoord.column * this.tileSize),
this.yLat(zoomedCoord.row * this.tileSize));
};
Transform.prototype.pointCoordinate = function pointCoordinate (p , zoom ) {
if (zoom === undefined) { zoom = this.tileZoom; }
var targetZ = 0;
// since we don't know the correct projected z value for the point,
// unproject two points to get a line and then find the point on that
// line with z=0
var coord0 = [p.x, p.y, 0, 1];
var coord1 = [p.x, p.y, 1, 1];
vec4.transformMat4(coord0, coord0, this.pixelMatrixInverse);
vec4.transformMat4(coord1, coord1, this.pixelMatrixInverse);
var w0 = coord0[3];
var w1 = coord1[3];
var x0 = coord0[0] / w0;
var x1 = coord1[0] / w1;
var y0 = coord0[1] / w0;
var y1 = coord1[1] / w1;
var z0 = coord0[2] / w0;
var z1 = coord1[2] / w1;
var t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);
return new Coordinate(
interp(x0, x1, t) / this.tileSize,
interp(y0, y1, t) / this.tileSize,
this.zoom)._zoomTo(zoom);
};
/**
* Given a coordinate, return the screen point that corresponds to it
* @param {Coordinate} coord
* @returns {Point} screen point
*/
Transform.prototype.coordinatePoint = function coordinatePoint (coord) {
var zoomedCoord = coord.zoomTo(this.zoom);
var p = [zoomedCoord.column * this.tileSize, zoomedCoord.row * this.tileSize, 0, 1];
vec4.transformMat4(p, p, this.pixelMatrix);
return new Point(p[0] / p[3], p[1] / p[3]);
};
/**
* Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map.
* @param {UnwrappedTileID} unwrappedTileID;
*/
Transform.prototype.calculatePosMatrix = function calculatePosMatrix (unwrappedTileID , aligned) {
if ( aligned === void 0 ) aligned = false;
var posMatrixKey = unwrappedTileID.key;
var cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;
if (cache[posMatrixKey]) {
return cache[posMatrixKey];
}
var canonical = unwrappedTileID.canonical;
var scale = this.worldSize / this.zoomScale(canonical.z);
var unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;
var posMatrix = mat4.identity(new Float64Array(16));
mat4.translate(posMatrix, posMatrix, [unwrappedX * scale, canonical.y * scale, 0]);
mat4.scale(posMatrix, posMatrix, [scale / EXTENT, scale / EXTENT, 1]);
mat4.multiply(posMatrix, aligned ? this.alignedProjMatrix : this.projMatrix, posMatrix);
cache[posMatrixKey] = new Float32Array(posMatrix);
return cache[posMatrixKey];
};
Transform.prototype._constrain = function _constrain () {
if (!this.center || !this.width || !this.height || this._constraining) { return; }
this._constraining = true;
var minY = -90;
var maxY = 90;
var minX = -180;
var maxX = 180;
var sy, sx, x2, y2;
var size = this.size,
unmodified = this._unmodified;
if (this.latRange) {
var latRange = this.latRange;
minY = this.latY(latRange[1]);
maxY = this.latY(latRange[0]);
sy = maxY - minY < size.y ? size.y / (maxY - minY) : 0;
}
if (this.lngRange) {
var lngRange = this.lngRange;
minX = this.lngX(lngRange[0]);
maxX = this.lngX(lngRange[1]);
sx = maxX - minX < size.x ? size.x / (maxX - minX) : 0;
}
// how much the map should scale to fit the screen into given latitude/longitude ranges
var s = Math.max(sx || 0, sy || 0);
if (s) {
this.center = this.unproject(new Point(
sx ? (maxX + minX) / 2 : this.x,
sy ? (maxY + minY) / 2 : this.y));
this.zoom += this.scaleZoom(s);
this._unmodified = unmodified;
this._constraining = false;
return;
}
if (this.latRange) {
var y = this.y,
h2 = size.y / 2;
if (y - h2 < minY) { y2 = minY + h2; }
if (y + h2 > maxY) { y2 = maxY - h2; }
}
if (this.lngRange) {
var x = this.x,
w2 = size.x / 2;
if (x - w2 < minX) { x2 = minX + w2; }
if (x + w2 > maxX) { x2 = maxX - w2; }
}
// pan the map if the screen goes off the range
if (x2 !== undefined || y2 !== undefined) {
this.center = this.unproject(new Point(
x2 !== undefined ? x2 : this.x,
y2 !== undefined ? y2 : this.y));
}
this._unmodified = unmodified;
this._constraining = false;
};
Transform.prototype._calcMatrices = function _calcMatrices () {
if (!this.height) { return; }
this.cameraToCenterDistance = 0.5 / Math.tan(this._fov / 2) * this.height;
// Find the distance from the center point [width/2, height/2] to the
// center top point [width/2, 0] in Z units, using the law of sines.
// 1 Z unit is equivalent to 1 horizontal px at the center of the map
// (the distance between[width/2, height/2] and [width/2 + 1, height/2])
var halfFov = this._fov / 2;
var groundAngle = Math.PI / 2 + this._pitch;
var topHalfSurfaceDistance = Math.sin(halfFov) * this.cameraToCenterDistance / Math.sin(Math.PI - groundAngle - halfFov);
var x = this.x, y = this.y;
// Calculate z distance of the farthest fragment that should be rendered.
var furthestDistance = Math.cos(Math.PI / 2 - this._pitch) * topHalfSurfaceDistance + this.cameraToCenterDistance;
// Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`
var farZ = furthestDistance * 1.01;
// matrix for conversion from location to GL coordinates (-1 .. 1)
var m = new Float64Array(16);
mat4.perspective(m, this._fov, this.width / this.height, 1, farZ);
mat4.scale(m, m, [1, -1, 1]);
mat4.translate(m, m, [0, 0, -this.cameraToCenterDistance]);
mat4.rotateX(m, m, this._pitch);
mat4.rotateZ(m, m, this.angle);
mat4.translate(m, m, [-x, -y, 0]);
// scale vertically to meters per pixel (inverse of ground resolution):
// worldSize / (circumferenceOfEarth * cos(lat * π / 180))
var verticalScale = this.worldSize / (2 * Math.PI * 6378137 * Math.abs(Math.cos(this.center.lat * (Math.PI / 180))));
mat4.scale(m, m, [1, 1, verticalScale, 1]);
this.projMatrix = m;
// Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles.
// We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional
// coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension
// is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle
// of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that
// it is always <= 0.5 pixels.
var 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;
var alignedM = new Float64Array(m);
mat4.translate(alignedM, alignedM, [ dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0 ]);
this.alignedProjMatrix = alignedM;
// matrix for conversion from location to screen coordinates
m = mat4.create();
mat4.scale(m, m, [this.width / 2, -this.height / 2, 1]);
mat4.translate(m, m, [1, -1, 0]);
this.pixelMatrix = mat4.multiply(new Float64Array(16), m, this.projMatrix);
// inverse matrix for conversion from screen coordinaes to location
m = mat4.invert(new Float64Array(16), this.pixelMatrix);
if (!m) { throw new Error("failed to invert matrix"); }
this.pixelMatrixInverse = m;
this._posMatrixCache = {};
this._alignedPosMatrixCache = {};
};
Object.defineProperties( Transform.prototype, prototypeAccessors );
module.exports = Transform;
},{"../data/extent":58,"../source/tile_id":120,"../style-spec/util/interpolate":164,"../util/tile_cover":281,"../util/util":283,"./coordinate":66,"./lng_lat":67,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],70:[function(require,module,exports){
'use strict';//
var Color = require('../style-spec/util/color');
var ZERO = 0x0000;
var ONE = 0x0001;
var ONE_MINUS_SRC_ALPHA = 0x0303;
var ColorMode = function ColorMode(blendFunction , blendColor , mask ) {
this.blendFunction = blendFunction;
this.blendColor = blendColor;
this.mask = mask;
};
ColorMode.Replace = [ONE, ZERO];
ColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]);
ColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]);
ColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]);
module.exports = ColorMode;
},{"../style-spec/util/color":159}],71:[function(require,module,exports){
'use strict';//
var IndexBuffer = require('./index_buffer');
var VertexBuffer = require('./vertex_buffer');
var Framebuffer = require('./framebuffer');
var DepthMode = require('./depth_mode');
var StencilMode = require('./stencil_mode');
var ColorMode = require('./color_mode');
var util = require('../util/util');
var ref = require('./value');
var ClearColor = ref.ClearColor;
var ClearDepth = ref.ClearDepth;
var ClearStencil = ref.ClearStencil;
var ColorMask = ref.ColorMask;
var DepthMask = ref.DepthMask;
var StencilMask = ref.StencilMask;
var StencilFunc = ref.StencilFunc;
var StencilOp = ref.StencilOp;
var StencilTest = ref.StencilTest;
var DepthRange = ref.DepthRange;
var DepthTest = ref.DepthTest;
var DepthFunc = ref.DepthFunc;
var Blend = ref.Blend;
var BlendFunc = ref.BlendFunc;
var BlendColor = ref.BlendColor;
var Program = ref.Program;
var LineWidth = ref.LineWidth;
var ActiveTextureUnit = ref.ActiveTextureUnit;
var Viewport = ref.Viewport;
var BindFramebuffer = ref.BindFramebuffer;
var BindRenderbuffer = ref.BindRenderbuffer;
var BindTexture = ref.BindTexture;
var BindVertexBuffer = ref.BindVertexBuffer;
var BindElementBuffer = ref.BindElementBuffer;
var BindVertexArrayOES = ref.BindVertexArrayOES;
var PixelStoreUnpack = ref.PixelStoreUnpack;
var PixelStoreUnpackPremultiplyAlpha = ref.PixelStoreUnpackPremultiplyAlpha;
var Context = function Context(gl ) {
this.gl = gl;
this.extVertexArrayObject = this.gl.getExtension('OES_vertex_array_object');
this.lineWidthRange = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE);
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.program = new Program(this);
this.lineWidth = new LineWidth(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 = this.extVertexArrayObject && new BindVertexArrayOES(this);
this.pixelStoreUnpack = new PixelStoreUnpack(this);
this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);
this.extTextureFilterAnisotropic = (
gl.getExtension('EXT_texture_filter_anisotropic') ||
gl.getExtension('MOZ_EXT_texture_filter_anisotropic') ||
gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')
);
if (this.extTextureFilterAnisotropic) {
this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
}
this.extTextureHalfFloat = gl.getExtension('OES_texture_half_float');
if (this.extTextureHalfFloat) {
gl.getExtension('OES_texture_half_float_linear');
}
};
Context.prototype.createIndexBuffer = function createIndexBuffer (array , dynamicDraw ) {
return new IndexBuffer(this, array, dynamicDraw);
};
Context.prototype.createVertexBuffer = function createVertexBuffer (array , attributes , dynamicDraw ) {
return new VertexBuffer(this, array, attributes, dynamicDraw);
};
Context.prototype.createRenderbuffer = function createRenderbuffer (storageFormat , width , height ) {
var gl = this.gl;
var rbo = gl.createRenderbuffer();
this.bindRenderbuffer.set(rbo);
gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height);
this.bindRenderbuffer.set(null);
return rbo;
};
Context.prototype.createFramebuffer = function createFramebuffer (width , height ) {
return new Framebuffer(this, width, height);
};
Context.prototype.clear = function clear (ref ) {
var color = ref.color;
var depth = ref.depth;
var gl = this.gl;
var mask = 0;
if (color) {
mask |= gl.COLOR_BUFFER_BIT;
this.clearColor.set(color);
this.colorMask.set([true, true, true, true]);
}
if (typeof depth !== 'undefined') {
mask |= gl.DEPTH_BUFFER_BIT;
this.clearDepth.set(depth);
this.depthMask.set(true);
}
// See note in Painter#clearStencil: implement this the easy way once GPU bug/workaround is fixed upstream
// if (typeof stencil !== 'undefined') {
// mask |= gl.STENCIL_BUFFER_BIT;
// this.clearStencil.set(stencil);
// this.stencilMask.set(0xFF);
// }
gl.clear(mask);
};
Context.prototype.setDepthMode = function 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);
}
};
Context.prototype.setStencilMode = function setStencilMode (stencilMode ) {
if (stencilMode.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
});
}
};
Context.prototype.setColorMode = function setColorMode (colorMode ) {
if (util.deepEqual(colorMode.blendFunction, ColorMode.Replace)) {
this.blend.set(false);
} else {
this.blend.set(true);
this.blendFunc.set(colorMode.blendFunction);
this.blendColor.set(colorMode.blendColor);
}
this.colorMask.set(colorMode.mask);
};
module.exports = Context;
},{"../util/util":283,"./color_mode":70,"./depth_mode":72,"./framebuffer":73,"./index_buffer":74,"./stencil_mode":75,"./value":76,"./vertex_buffer":77}],72:[function(require,module,exports){
'use strict';//
var ALWAYS = 0x0207;
var DepthMode = function DepthMode(depthFunc , depthMask , depthRange ) {
this.func = depthFunc;
this.mask = depthMask;
this.range = depthRange;
};
DepthMode.ReadOnly = false;
DepthMode.ReadWrite = true;
DepthMode.disabled = new DepthMode(ALWAYS, DepthMode.ReadOnly, [0, 1]);
module.exports = DepthMode;
},{}],73:[function(require,module,exports){
'use strict';//
var ref = requi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment