diff --git a/dist/tangram.debug.js b/dist/tangram.debug.js index cf2302cb3..621a95f2d 100644 --- a/dist/tangram.debug.js +++ b/dist/tangram.debug.js @@ -1,38 +1,38 @@ -(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= 0; - -// Save the old regeneratorRuntime in case it needs to be restored later. -var oldRuntime = hadRuntime && g.regeneratorRuntime; - -// Force reevalutation of runtime.js. -g.regeneratorRuntime = undefined; - -module.exports = _dereq_("./runtime"); - -if (hadRuntime) { - // Restore the original runtime. - g.regeneratorRuntime = oldRuntime; -} else { - // Remove the global property added by runtime.js. - try { - delete g.regeneratorRuntime; - } catch(e) { - g.regeneratorRuntime = undefined; - } -} - -module.exports = { "default": module.exports, __esModule: true }; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9iYWJlbC1ydW50aW1lL3JlZ2VuZXJhdG9yL2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiO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J0cyA9IHJlcXVpcmUoXCIuL3J1bnRpbWVcIik7XG5cbmlmIChoYWRSdW50aW1lKSB7XG4gIC8vIFJlc3RvcmUgdGhlIG9yaWdpbmFsIHJ1bnRpbWUuXG4gIGcucmVnZW5lcmF0b3JSdW50aW1lID0gb2xkUnVudGltZTtcbn0gZWxzZSB7XG4gIC8vIFJlbW92ZSB0aGUgZ2xvYmFsIHByb3BlcnR5IGFkZGVkIGJ5IHJ1bnRpbWUuanMuXG4gIHRyeSB7XG4gICAgZGVsZXRlIGcucmVnZW5lcmF0b3JSdW50aW1lO1xuICB9IGNhdGNoKGUpIHtcbiAgICBnLnJlZ2VuZXJhdG9yUnVudGltZSA9IHVuZGVmaW5lZDtcbiAgfVxufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHsgXCJkZWZhdWx0XCI6IG1vZHVsZS5leHBvcnRzLCBfX2VzTW9kdWxlOiB0cnVlIH07XG4iXX0= -},{"./runtime":27}],27:[function(_dereq_,module,exports){ -(function (process,global){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -"use strict"; - -var _Symbol = _dereq_("babel-runtime/core-js/symbol")["default"]; - -var _Symbol$iterator = _dereq_("babel-runtime/core-js/symbol/iterator")["default"]; - -var _Object$create = _dereq_("babel-runtime/core-js/object/create")["default"]; - -var _Promise = _dereq_("babel-runtime/core-js/promise")["default"]; - -!(function (global) { - "use strict"; - - var hasOwn = Object.prototype.hasOwnProperty; - var undefined; // More compressible than void 0. - var iteratorSymbol = typeof _Symbol === "function" && _Symbol$iterator || "@@iterator"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; +_dereq_('../../modules/es6.string.iterator'); +_dereq_('../../modules/es6.array.from'); +module.exports = _dereq_('../../modules/$.core').Array.from; +},{"../../modules/$.core":51,"../../modules/es6.array.from":103,"../../modules/es6.string.iterator":115}],27:[function(_dereq_,module,exports){ +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.string.iterator'); +module.exports = _dereq_('../modules/core.get-iterator'); +},{"../modules/core.get-iterator":101,"../modules/es6.string.iterator":115,"../modules/web.dom.iterable":119}],28:[function(_dereq_,module,exports){ +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.string.iterator'); +module.exports = _dereq_('../modules/core.is-iterable'); +},{"../modules/core.is-iterable":102,"../modules/es6.string.iterator":115,"../modules/web.dom.iterable":119}],29:[function(_dereq_,module,exports){ +_dereq_('../modules/es6.object.to-string'); +_dereq_('../modules/es6.string.iterator'); +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.map'); +_dereq_('../modules/es7.map.to-json'); +module.exports = _dereq_('../modules/$.core').Map; +},{"../modules/$.core":51,"../modules/es6.map":105,"../modules/es6.object.to-string":112,"../modules/es6.string.iterator":115,"../modules/es7.map.to-json":117,"../modules/web.dom.iterable":119}],30:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.math.log2'); +module.exports = _dereq_('../../modules/$.core').Math.log2; +},{"../../modules/$.core":51,"../../modules/es6.math.log2":106}],31:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.assign'); +module.exports = _dereq_('../../modules/$.core').Object.assign; +},{"../../modules/$.core":51,"../../modules/es6.object.assign":107}],32:[function(_dereq_,module,exports){ +var $ = _dereq_('../../modules/$'); +module.exports = function create(P, D){ + return $.create(P, D); +}; +},{"../../modules/$":76}],33:[function(_dereq_,module,exports){ +var $ = _dereq_('../../modules/$'); +module.exports = function defineProperties(T, D){ + return $.setDescs(T, D); +}; +},{"../../modules/$":76}],34:[function(_dereq_,module,exports){ +var $ = _dereq_('../../modules/$'); +module.exports = function defineProperty(it, key, desc){ + return $.setDesc(it, key, desc); +}; +},{"../../modules/$":76}],35:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.freeze'); +module.exports = _dereq_('../../modules/$.core').Object.freeze; +},{"../../modules/$.core":51,"../../modules/es6.object.freeze":108}],36:[function(_dereq_,module,exports){ +var $ = _dereq_('../../modules/$'); +_dereq_('../../modules/es6.object.get-own-property-descriptor'); +module.exports = function getOwnPropertyDescriptor(it, key){ + return $.getDesc(it, key); +}; +},{"../../modules/$":76,"../../modules/es6.object.get-own-property-descriptor":109}],37:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.keys'); +module.exports = _dereq_('../../modules/$.core').Object.keys; +},{"../../modules/$.core":51,"../../modules/es6.object.keys":110}],38:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.set-prototype-of'); +module.exports = _dereq_('../../modules/$.core').Object.setPrototypeOf; +},{"../../modules/$.core":51,"../../modules/es6.object.set-prototype-of":111}],39:[function(_dereq_,module,exports){ +_dereq_('../modules/es6.object.to-string'); +_dereq_('../modules/es6.string.iterator'); +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.promise'); +module.exports = _dereq_('../modules/$.core').Promise; +},{"../modules/$.core":51,"../modules/es6.object.to-string":112,"../modules/es6.promise":113,"../modules/es6.string.iterator":115,"../modules/web.dom.iterable":119}],40:[function(_dereq_,module,exports){ +_dereq_('../modules/es6.object.to-string'); +_dereq_('../modules/es6.string.iterator'); +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.set'); +_dereq_('../modules/es7.set.to-json'); +module.exports = _dereq_('../modules/$.core').Set; +},{"../modules/$.core":51,"../modules/es6.object.to-string":112,"../modules/es6.set":114,"../modules/es6.string.iterator":115,"../modules/es7.set.to-json":118,"../modules/web.dom.iterable":119}],41:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.symbol'); +_dereq_('../../modules/es6.object.to-string'); +module.exports = _dereq_('../../modules/$.core').Symbol; +},{"../../modules/$.core":51,"../../modules/es6.object.to-string":112,"../../modules/es6.symbol":116}],42:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.string.iterator'); +_dereq_('../../modules/web.dom.iterable'); +module.exports = _dereq_('../../modules/$.wks')('iterator'); +},{"../../modules/$.wks":99,"../../modules/es6.string.iterator":115,"../../modules/web.dom.iterable":119}],43:[function(_dereq_,module,exports){ +module.exports = function(it){ + if(typeof it != 'function')throw TypeError(it + ' is not a function!'); + return it; +}; +},{}],44:[function(_dereq_,module,exports){ +module.exports = function(){ /* empty */ }; +},{}],45:[function(_dereq_,module,exports){ +var isObject = _dereq_('./$.is-object'); +module.exports = function(it){ + if(!isObject(it))throw TypeError(it + ' is not an object!'); + return it; +}; +},{"./$.is-object":69}],46:[function(_dereq_,module,exports){ +// getting tag from 19.1.3.6 Object.prototype.toString() +var cof = _dereq_('./$.cof') + , TAG = _dereq_('./$.wks')('toStringTag') + // ES3 wrong here + , ARG = cof(function(){ return arguments; }()) == 'Arguments'; - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided, then outerFn.prototype instanceof Generator. - var generator = _Object$create((outerFn || Generator).prototype); +module.exports = function(it){ + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = (O = Object(it))[TAG]) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; +}; +},{"./$.cof":47,"./$.wks":99}],47:[function(_dereq_,module,exports){ +var toString = {}.toString; - generator._invoke = makeInvokeMethod(innerFn, self || null, new Context(tryLocsList || [])); +module.exports = function(it){ + return toString.call(it).slice(8, -1); +}; +},{}],48:[function(_dereq_,module,exports){ +'use strict'; +var $ = _dereq_('./$') + , hide = _dereq_('./$.hide') + , redefineAll = _dereq_('./$.redefine-all') + , ctx = _dereq_('./$.ctx') + , strictNew = _dereq_('./$.strict-new') + , defined = _dereq_('./$.defined') + , forOf = _dereq_('./$.for-of') + , $iterDefine = _dereq_('./$.iter-define') + , step = _dereq_('./$.iter-step') + , ID = _dereq_('./$.uid')('id') + , $has = _dereq_('./$.has') + , isObject = _dereq_('./$.is-object') + , setSpecies = _dereq_('./$.set-species') + , DESCRIPTORS = _dereq_('./$.descriptors') + , isExtensible = Object.isExtensible || isObject + , SIZE = DESCRIPTORS ? '_s' : 'size' + , id = 0; - return generator; - } - runtime.wrap = wrap; +var fastKey = function(it, create){ + // return primitive with prefix + if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if(!$has(it, ID)){ + // can't set id to frozen object + if(!isExtensible(it))return 'F'; + // not necessary to add id + if(!create)return 'E'; + // add missing object id + hide(it, ID, ++id); + // return object id with prefix + } return 'O' + it[ID]; +}; - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } +var getEntry = function(that, key){ + // fast case + var index = fastKey(key), entry; + if(index !== 'F')return that._i[index]; + // frozen object case + for(entry = that._f; entry; entry = entry.n){ + if(entry.k == key)return entry; } +}; - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - prototype[method] = function (arg) { - return this._invoke(method, arg); - }; +module.exports = { + getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ + var C = wrapper(function(that, iterable){ + strictNew(that, C, NAME); + that._i = $.create(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); - } - - runtime.isGeneratorFunction = function (genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" : false; - }; - - runtime.mark = function (genFun) { - genFun.__proto__ = GeneratorFunctionPrototype; - genFun.prototype = _Object$create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `value instanceof AwaitArgument` to determine if the yielded value is - // meant to be awaited. Some may consider the name of this method too - // cutesy, but they are curmudgeons. - runtime.awrap = function (arg) { - return new AwaitArgument(arg); - }; + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear(){ + for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ + entry.r = true; + if(entry.p)entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function(key){ + var that = this + , entry = getEntry(that, key); + if(entry){ + var next = entry.n + , prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if(prev)prev.n = next; + if(next)next.p = prev; + if(that._f == entry)that._f = next; + if(that._l == entry)that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /*, that = undefined */){ + var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) + , entry; + while(entry = entry ? entry.n : this._f){ + f(entry.v, entry.k, this); + // revert to the last existing entry + while(entry && entry.r)entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key){ + return !!getEntry(this, key); + } + }); + if(DESCRIPTORS)$.setDesc(C.prototype, 'size', { + get: function(){ + return defined(this[SIZE]); + } + }); + return C; + }, + def: function(that, key, value){ + var entry = getEntry(that, key) + , prev, index; + // change existing entry + if(entry){ + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if(!that._f)that._f = entry; + if(prev)prev.n = entry; + that[SIZE]++; + // add to index + if(index !== 'F')that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function(C, NAME, IS_MAP){ + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + $iterDefine(C, NAME, function(iterated, kind){ + this._t = iterated; // target + this._k = kind; // kind + this._l = undefined; // previous + }, function(){ + var that = this + , kind = that._k + , entry = that._l; + // revert to the last existing entry + while(entry && entry.r)entry = entry.p; + // get next entry + if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ + // or finish the iteration + that._t = undefined; + return step(1); + } + // return step by kind + if(kind == 'keys' )return step(0, entry.k); + if(kind == 'values')return step(0, entry.v); + return step(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); - function AwaitArgument(arg) { - this.arg = arg; + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(NAME); } +}; +},{"./$":76,"./$.ctx":52,"./$.defined":53,"./$.descriptors":54,"./$.for-of":59,"./$.has":62,"./$.hide":63,"./$.is-object":69,"./$.iter-define":72,"./$.iter-step":74,"./$.redefine-all":83,"./$.set-species":87,"./$.strict-new":91,"./$.uid":98}],49:[function(_dereq_,module,exports){ +// https://github.com/DavidBruant/Map-Set.prototype.toJSON +var forOf = _dereq_('./$.for-of') + , classof = _dereq_('./$.classof'); +module.exports = function(NAME){ + return function toJSON(){ + if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); + var arr = []; + forOf(this, false, arr.push, arr); + return arr; + }; +}; +},{"./$.classof":46,"./$.for-of":59}],50:[function(_dereq_,module,exports){ +'use strict'; +var $ = _dereq_('./$') + , global = _dereq_('./$.global') + , $export = _dereq_('./$.export') + , fails = _dereq_('./$.fails') + , hide = _dereq_('./$.hide') + , redefineAll = _dereq_('./$.redefine-all') + , forOf = _dereq_('./$.for-of') + , strictNew = _dereq_('./$.strict-new') + , isObject = _dereq_('./$.is-object') + , setToStringTag = _dereq_('./$.set-to-string-tag') + , DESCRIPTORS = _dereq_('./$.descriptors'); - function AsyncIterator(generator) { - // This invoke function is written in a style that assumes some - // calling function (or Promise) will handle exceptions. - function invoke(method, arg) { - var result = generator[method](arg); - var value = result.value; - return value instanceof AwaitArgument ? _Promise.resolve(value.arg).then(invokeNext, invokeThrow) : _Promise.resolve(value).then(function (unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - return result; +module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ + var Base = global[NAME] + , C = Base + , ADDER = IS_MAP ? 'set' : 'add' + , proto = C && C.prototype + , O = {}; + if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ + new C().entries().next(); + }))){ + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + redefineAll(C.prototype, methods); + } else { + C = wrapper(function(target, iterable){ + strictNew(target, C, NAME); + target._c = new Base; + if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target); + }); + $.each.call('add,clear,delete,forEach,get,has,set,keys,values,entries'.split(','),function(KEY){ + var IS_ADDER = KEY == 'add' || KEY == 'set'; + if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){ + if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false; + var result = this._c[KEY](a === 0 ? 0 : a, b); + return IS_ADDER ? this : result; }); - } - - if (typeof process === "object" && process.domain) { - invoke = process.domain.bind(invoke); - } + }); + if('size' in proto)$.setDesc(C.prototype, 'size', { + get: function(){ + return this._c.size; + } + }); + } - var invokeNext = invoke.bind(generator, "next"); - var invokeThrow = invoke.bind(generator, "throw"); - var invokeReturn = invoke.bind(generator, "return"); - var previousPromise; + setToStringTag(C, NAME); - function enqueue(method, arg) { - var enqueueResult = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then(function () { - return invoke(method, arg); - }) : new _Promise(function (resolve) { - resolve(invoke(method, arg)); - }); + O[NAME] = C; + $export($export.G + $export.W + $export.F, O); - // Avoid propagating enqueueResult failures to Promises returned by - // later invocations of the iterator. - previousPromise = enqueueResult["catch"](function (ignored) {}); + if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); - return enqueueResult; - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; + return C; +}; +},{"./$":76,"./$.descriptors":54,"./$.export":57,"./$.fails":58,"./$.for-of":59,"./$.global":61,"./$.hide":63,"./$.is-object":69,"./$.redefine-all":83,"./$.set-to-string-tag":88,"./$.strict-new":91}],51:[function(_dereq_,module,exports){ +var core = module.exports = {version: '1.2.6'}; +if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef +},{}],52:[function(_dereq_,module,exports){ +// optional / simple context binding +var aFunction = _dereq_('./$.a-function'); +module.exports = function(fn, that, length){ + aFunction(fn); + if(that === undefined)return fn; + switch(length){ + case 1: return function(a){ + return fn.call(that, a); + }; + case 2: return function(a, b){ + return fn.call(that, a, b); + }; + case 3: return function(a, b, c){ + return fn.call(that, a, b, c); + }; } - - defineIteratorMethods(AsyncIterator.prototype); - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function (innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); - - return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); + return function(/* ...args */){ + return fn.apply(that, arguments); }; +}; +},{"./$.a-function":43}],53:[function(_dereq_,module,exports){ +// 7.2.1 RequireObjectCoercible(argument) +module.exports = function(it){ + if(it == undefined)throw TypeError("Can't call method on " + it); + return it; +}; +},{}],54:[function(_dereq_,module,exports){ +// Thank's IE8 for his funny defineProperty +module.exports = !_dereq_('./$.fails')(function(){ + return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; +}); +},{"./$.fails":58}],55:[function(_dereq_,module,exports){ +var isObject = _dereq_('./$.is-object') + , document = _dereq_('./$.global').document + // in old IE typeof document.createElement is 'object' + , is = isObject(document) && isObject(document.createElement); +module.exports = function(it){ + return is ? document.createElement(it) : {}; +}; +},{"./$.global":61,"./$.is-object":69}],56:[function(_dereq_,module,exports){ +// all enumerable object keys, includes symbols +var $ = _dereq_('./$'); +module.exports = function(it){ + var keys = $.getKeys(it) + , getSymbols = $.getSymbols; + if(getSymbols){ + var symbols = getSymbols(it) + , isEnum = $.isEnum + , i = 0 + , key; + while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key); + } + return keys; +}; +},{"./$":76}],57:[function(_dereq_,module,exports){ +var global = _dereq_('./$.global') + , core = _dereq_('./$.core') + , ctx = _dereq_('./$.ctx') + , PROTOTYPE = 'prototype'; - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; +var $export = function(type, name, source){ + var IS_FORCED = type & $export.F + , IS_GLOBAL = type & $export.G + , IS_STATIC = type & $export.S + , IS_PROTO = type & $export.P + , IS_BIND = type & $export.B + , IS_WRAP = type & $export.W + , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) + , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] + , key, own, out; + if(IS_GLOBAL)source = name; + for(key in source){ + // contains in native + own = !IS_FORCED && target && key in target; + if(own && key in exports)continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? ctx(out, global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function(C){ + var F = function(param){ + return this instanceof C ? new C(param) : C(param); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +module.exports = $export; +},{"./$.core":51,"./$.ctx":52,"./$.global":61}],58:[function(_dereq_,module,exports){ +module.exports = function(exec){ + try { + return !!exec(); + } catch(e){ + return true; + } +}; +},{}],59:[function(_dereq_,module,exports){ +var ctx = _dereq_('./$.ctx') + , call = _dereq_('./$.iter-call') + , isArrayIter = _dereq_('./$.is-array-iter') + , anObject = _dereq_('./$.an-object') + , toLength = _dereq_('./$.to-length') + , getIterFn = _dereq_('./core.get-iterator-method'); +module.exports = function(iterable, entries, fn, that){ + var iterFn = getIterFn(iterable) + , f = ctx(fn, that, entries ? 2 : 1) + , index = 0 + , length, step, iterator; + if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ + entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ + call(iterator, f, step.value, entries); + } +}; +},{"./$.an-object":45,"./$.ctx":52,"./$.is-array-iter":67,"./$.iter-call":70,"./$.to-length":96,"./core.get-iterator-method":100}],60:[function(_dereq_,module,exports){ +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window +var toIObject = _dereq_('./$.to-iobject') + , getNames = _dereq_('./$').getNames + , toString = {}.toString; - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } +var windowNames = typeof window == 'object' && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } +var getWindowNames = function(it){ + try { + return getNames(it); + } catch(e){ + return windowNames.slice(); + } +}; - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } +module.exports.get = function getOwnPropertyNames(it){ + if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it); + return getNames(toIObject(it)); +}; +},{"./$":76,"./$.to-iobject":95}],61:[function(_dereq_,module,exports){ +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); +if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef +},{}],62:[function(_dereq_,module,exports){ +var hasOwnProperty = {}.hasOwnProperty; +module.exports = function(it, key){ + return hasOwnProperty.call(it, key); +}; +},{}],63:[function(_dereq_,module,exports){ +var $ = _dereq_('./$') + , createDesc = _dereq_('./$.property-desc'); +module.exports = _dereq_('./$.descriptors') ? function(object, key, value){ + return $.setDesc(object, key, createDesc(1, value)); +} : function(object, key, value){ + object[key] = value; + return object; +}; +},{"./$":76,"./$.descriptors":54,"./$.property-desc":82}],64:[function(_dereq_,module,exports){ +module.exports = _dereq_('./$.global').document && document.documentElement; +},{"./$.global":61}],65:[function(_dereq_,module,exports){ +// fast apply, http://jsperf.lnkit.com/fast-apply/5 +module.exports = function(fn, args, that){ + var un = that === undefined; + switch(args.length){ + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); +}; +},{}],66:[function(_dereq_,module,exports){ +// fallback for non-array-like ES3 and non-enumerable old V8 strings +var cof = _dereq_('./$.cof'); +module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ + return cof(it) == 'String' ? it.split('') : Object(it); +}; +},{"./$.cof":47}],67:[function(_dereq_,module,exports){ +// check on default Array iterator +var Iterators = _dereq_('./$.iterators') + , ITERATOR = _dereq_('./$.wks')('iterator') + , ArrayProto = Array.prototype; - while (true) { - var delegate = context.delegate; - if (delegate) { - if (method === "return" || method === "throw" && delegate.iterator[method] === undefined) { - // A return or throw (when the delegate iterator has no throw - // method) always terminates the yield* loop. - context.delegate = null; +module.exports = function(it){ + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); +}; +},{"./$.iterators":75,"./$.wks":99}],68:[function(_dereq_,module,exports){ +// 7.2.2 IsArray(argument) +var cof = _dereq_('./$.cof'); +module.exports = Array.isArray || function(arg){ + return cof(arg) == 'Array'; +}; +},{"./$.cof":47}],69:[function(_dereq_,module,exports){ +module.exports = function(it){ + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; +},{}],70:[function(_dereq_,module,exports){ +// call something on iterator step with safe closing on error +var anObject = _dereq_('./$.an-object'); +module.exports = function(iterator, fn, value, entries){ + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch(e){ + var ret = iterator['return']; + if(ret !== undefined)anObject(ret.call(iterator)); + throw e; + } +}; +},{"./$.an-object":45}],71:[function(_dereq_,module,exports){ +'use strict'; +var $ = _dereq_('./$') + , descriptor = _dereq_('./$.property-desc') + , setToStringTag = _dereq_('./$.set-to-string-tag') + , IteratorPrototype = {}; - // If the delegate iterator has a return method, give it a - // chance to clean up. - var returnMethod = delegate.iterator["return"]; - if (returnMethod) { - var record = tryCatch(returnMethod, delegate.iterator, arg); - if (record.type === "throw") { - // If the return method threw an exception, let that - // exception prevail over the original return or throw. - method = "throw"; - arg = record.arg; - continue; - } - } - - if (method === "return") { - // Continue with the outer return, now that the delegate - // iterator has been terminated. - continue; - } - } - - var record = tryCatch(delegate.iterator[method], delegate.iterator, arg); - - if (record.type === "throw") { - context.delegate = null; - - // Like returning generator.throw(uncaught), but without the - // overhead of an extra function call. - method = "throw"; - arg = record.arg; - continue; - } - - // Delegate generator ran and handled its own exceptions so - // regardless of what the method was, we continue as if it is - // "next" with an undefined arg. - method = "next"; - arg = undefined; - - var info = record.arg; - if (info.done) { - context[delegate.resultName] = info.value; - context.next = delegate.nextLoc; - } else { - state = GenStateSuspendedYield; - return info; - } - - context.delegate = null; - } - - if (method === "next") { - if (state === GenStateSuspendedYield) { - context.sent = arg; - } else { - context.sent = undefined; - } - } else if (method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw arg; - } - - if (context.dispatchException(arg)) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - method = "next"; - arg = undefined; - } - } else if (method === "return") { - context.abrupt("return", arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done ? GenStateCompleted : GenStateSuspendedYield; - - var info = { - value: record.arg, - done: context.done - }; - - if (record.arg === ContinueSentinel) { - if (context.delegate && method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - arg = undefined; - } - } else { - return info; - } - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(arg) call above. - method = "throw"; - arg = record.arg; - } - } - }; - } +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_dereq_('./$.hide')(IteratorPrototype, _dereq_('./$.wks')('iterator'), function(){ return this; }); - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); +module.exports = function(Constructor, NAME, next){ + Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)}); + setToStringTag(Constructor, NAME + ' Iterator'); +}; +},{"./$":76,"./$.hide":63,"./$.property-desc":82,"./$.set-to-string-tag":88,"./$.wks":99}],72:[function(_dereq_,module,exports){ +'use strict'; +var LIBRARY = _dereq_('./$.library') + , $export = _dereq_('./$.export') + , redefine = _dereq_('./$.redefine') + , hide = _dereq_('./$.hide') + , has = _dereq_('./$.has') + , Iterators = _dereq_('./$.iterators') + , $iterCreate = _dereq_('./$.iter-create') + , setToStringTag = _dereq_('./$.set-to-string-tag') + , getProto = _dereq_('./$').getProto + , ITERATOR = _dereq_('./$.wks')('iterator') + , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` + , FF_ITERATOR = '@@iterator' + , KEYS = 'keys' + , VALUES = 'values'; - Gp[iteratorSymbol] = function () { - return this; - }; +var returnThis = function(){ return this; }; - Gp.toString = function () { - return "[object Generator]"; +module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ + $iterCreate(Constructor, NAME, next); + var getMethod = function(kind){ + if(!BUGGY && kind in proto)return proto[kind]; + switch(kind){ + case KEYS: return function keys(){ return new Constructor(this, kind); }; + case VALUES: return function values(){ return new Constructor(this, kind); }; + } return function entries(){ return new Constructor(this, kind); }; }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; + var TAG = NAME + ' Iterator' + , DEF_VALUES = DEFAULT == VALUES + , VALUES_BUG = false + , proto = Base.prototype + , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] + , $default = $native || getMethod(DEFAULT) + , methods, key; + // Fix native + if($native){ + var IteratorPrototype = getProto($default.call(new Base)); + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // FF fix + if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); + // fix Array#{values, @@iterator}.name in V8 / FF + if(DEF_VALUES && $native.name !== VALUES){ + VALUES_BUG = true; + $default = function values(){ return $native.call(this); }; } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); + // Define iterator + if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ + hide(proto, ITERATOR, $default); } - - runtime.keys = function (object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if(DEFAULT){ + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: !DEF_VALUES ? $default : getMethod('entries') }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } + if(FORCED)for(key in methods){ + if(!(key in proto))redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; +},{"./$":76,"./$.export":57,"./$.has":62,"./$.hide":63,"./$.iter-create":71,"./$.iterators":75,"./$.library":78,"./$.redefine":84,"./$.set-to-string-tag":88,"./$.wks":99}],73:[function(_dereq_,module,exports){ +var ITERATOR = _dereq_('./$.wks')('iterator') + , SAFE_CLOSING = false; - next.value = undefined; - next.done = true; +try { + var riter = [7][ITERATOR](); + riter['return'] = function(){ SAFE_CLOSING = true; }; + Array.from(riter, function(){ throw 2; }); +} catch(e){ /* empty */ } - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; +module.exports = function(exec, skipClosing){ + if(!skipClosing && !SAFE_CLOSING)return false; + var safe = false; + try { + var arr = [7] + , iter = arr[ITERATOR](); + iter.next = function(){ safe = true; }; + arr[ITERATOR] = function(){ return iter; }; + exec(arr); + } catch(e){ /* empty */ } + return safe; +}; +},{"./$.wks":99}],74:[function(_dereq_,module,exports){ +module.exports = function(done, value){ + return {value: value, done: !!done}; +}; +},{}],75:[function(_dereq_,module,exports){ +module.exports = {}; +},{}],76:[function(_dereq_,module,exports){ +var $Object = Object; +module.exports = { + create: $Object.create, + getProto: $Object.getPrototypeOf, + isEnum: {}.propertyIsEnumerable, + getDesc: $Object.getOwnPropertyDescriptor, + setDesc: $Object.defineProperty, + setDescs: $Object.defineProperties, + getKeys: $Object.keys, + getNames: $Object.getOwnPropertyNames, + getSymbols: $Object.getOwnPropertySymbols, + each: [].forEach +}; +},{}],77:[function(_dereq_,module,exports){ +var $ = _dereq_('./$') + , toIObject = _dereq_('./$.to-iobject'); +module.exports = function(object, el){ + var O = toIObject(object) + , keys = $.getKeys(O) + , length = keys.length + , index = 0 + , key; + while(length > index)if(O[key = keys[index++]] === el)return key; +}; +},{"./$":76,"./$.to-iobject":95}],78:[function(_dereq_,module,exports){ +module.exports = true; +},{}],79:[function(_dereq_,module,exports){ +var global = _dereq_('./$.global') + , macrotask = _dereq_('./$.task').set + , Observer = global.MutationObserver || global.WebKitMutationObserver + , process = global.process + , Promise = global.Promise + , isNode = _dereq_('./$.cof')(process) == 'process' + , head, last, notify; - function doneResult() { - return { value: undefined, done: true }; +var flush = function(){ + var parent, domain, fn; + if(isNode && (parent = process.domain)){ + process.domain = null; + parent.exit(); } + while(head){ + domain = head.domain; + fn = head.fn; + if(domain)domain.enter(); + fn(); // <- currently we use it only for Promise - try / catch not required + if(domain)domain.exit(); + head = head.next; + } last = undefined; + if(parent)parent.enter(); +}; - Context.prototype = { - constructor: Context, - - reset: function reset(skipTempReset) { - this.prev = 0; - this.next = 0; - this.sent = undefined; - this.done = false; - this.delegate = null; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function stop() { - this.done = true; +// Node.js +if(isNode){ + notify = function(){ + process.nextTick(flush); + }; +// browsers with MutationObserver +} else if(Observer){ + var toggle = 1 + , node = document.createTextNode(''); + new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new + notify = function(){ + node.data = toggle = -toggle; + }; +// environments with maybe non-completely correct, but existent Promise +} else if(Promise && Promise.resolve){ + notify = function(){ + Promise.resolve().then(flush); + }; +// for other environments - macrotask based on: +// - setImmediate +// - MessageChannel +// - window.postMessag +// - onreadystatechange +// - setTimeout +} else { + notify = function(){ + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; +} - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } +module.exports = function asap(fn){ + var task = {fn: fn, next: undefined, domain: isNode && process.domain}; + if(last)last.next = task; + if(!head){ + head = task; + notify(); + } last = task; +}; +},{"./$.cof":47,"./$.global":61,"./$.task":93}],80:[function(_dereq_,module,exports){ +// 19.1.2.1 Object.assign(target, source, ...) +var $ = _dereq_('./$') + , toObject = _dereq_('./$.to-object') + , IObject = _dereq_('./$.iobject'); - return this.rval; - }, +// should work with symbols and should have deterministic property order (V8 bug) +module.exports = _dereq_('./$.fails')(function(){ + var a = Object.assign + , A = {} + , B = {} + , S = Symbol() + , K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function(k){ B[k] = k; }); + return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; +}) ? function assign(target, source){ // eslint-disable-line no-unused-vars + var T = toObject(target) + , $$ = arguments + , $$len = $$.length + , index = 1 + , getKeys = $.getKeys + , getSymbols = $.getSymbols + , isEnum = $.isEnum; + while($$len > index){ + var S = IObject($$[index++]) + , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) + , length = keys.length + , j = 0 + , key; + while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; + } + return T; +} : Object.assign; +},{"./$":76,"./$.fails":58,"./$.iobject":66,"./$.to-object":97}],81:[function(_dereq_,module,exports){ +// most Object methods by ES6 should accept primitives +var $export = _dereq_('./$.export') + , core = _dereq_('./$.core') + , fails = _dereq_('./$.fails'); +module.exports = function(KEY, exec){ + var fn = (core.Object || {})[KEY] || Object[KEY] + , exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); +}; +},{"./$.core":51,"./$.export":57,"./$.fails":58}],82:[function(_dereq_,module,exports){ +module.exports = function(bitmap, value){ + return { + enumerable : !(bitmap & 1), + configurable: !(bitmap & 2), + writable : !(bitmap & 4), + value : value + }; +}; +},{}],83:[function(_dereq_,module,exports){ +var redefine = _dereq_('./$.redefine'); +module.exports = function(target, src){ + for(var key in src)redefine(target, key, src[key]); + return target; +}; +},{"./$.redefine":84}],84:[function(_dereq_,module,exports){ +module.exports = _dereq_('./$.hide'); +},{"./$.hide":63}],85:[function(_dereq_,module,exports){ +// 7.2.9 SameValue(x, y) +module.exports = Object.is || function is(x, y){ + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; +}; +},{}],86:[function(_dereq_,module,exports){ +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ +var getDesc = _dereq_('./$').getDesc + , isObject = _dereq_('./$.is-object') + , anObject = _dereq_('./$.an-object'); +var check = function(O, proto){ + anObject(O); + if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); +}; +module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function(test, buggy, set){ + try { + set = _dereq_('./$.ctx')(Function.call, getDesc(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch(e){ buggy = true; } + return function setPrototypeOf(O, proto){ + check(O, proto); + if(buggy)O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check +}; +},{"./$":76,"./$.an-object":45,"./$.ctx":52,"./$.is-object":69}],87:[function(_dereq_,module,exports){ +'use strict'; +var core = _dereq_('./$.core') + , $ = _dereq_('./$') + , DESCRIPTORS = _dereq_('./$.descriptors') + , SPECIES = _dereq_('./$.wks')('species'); - dispatchException: function dispatchException(exception) { - if (this.done) { - throw exception; - } +module.exports = function(KEY){ + var C = core[KEY]; + if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, { + configurable: true, + get: function(){ return this; } + }); +}; +},{"./$":76,"./$.core":51,"./$.descriptors":54,"./$.wks":99}],88:[function(_dereq_,module,exports){ +var def = _dereq_('./$').setDesc + , has = _dereq_('./$.has') + , TAG = _dereq_('./$.wks')('toStringTag'); - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - return !!caught; +module.exports = function(it, tag, stat){ + if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); +}; +},{"./$":76,"./$.has":62,"./$.wks":99}],89:[function(_dereq_,module,exports){ +var global = _dereq_('./$.global') + , SHARED = '__core-js_shared__' + , store = global[SHARED] || (global[SHARED] = {}); +module.exports = function(key){ + return store[key] || (store[key] = {}); +}; +},{"./$.global":61}],90:[function(_dereq_,module,exports){ +// 7.3.20 SpeciesConstructor(O, defaultConstructor) +var anObject = _dereq_('./$.an-object') + , aFunction = _dereq_('./$.a-function') + , SPECIES = _dereq_('./$.wks')('species'); +module.exports = function(O, D){ + var C = anObject(O).constructor, S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); +}; +},{"./$.a-function":43,"./$.an-object":45,"./$.wks":99}],91:[function(_dereq_,module,exports){ +module.exports = function(it, Constructor, name){ + if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); + return it; +}; +},{}],92:[function(_dereq_,module,exports){ +var toInteger = _dereq_('./$.to-integer') + , defined = _dereq_('./$.defined'); +// true -> String#at +// false -> String#codePointAt +module.exports = function(TO_STRING){ + return function(that, pos){ + var s = String(defined(that)) + , i = toInteger(pos) + , l = s.length + , a, b; + if(i < 0 || i >= l)return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; +},{"./$.defined":53,"./$.to-integer":94}],93:[function(_dereq_,module,exports){ +var ctx = _dereq_('./$.ctx') + , invoke = _dereq_('./$.invoke') + , html = _dereq_('./$.html') + , cel = _dereq_('./$.dom-create') + , global = _dereq_('./$.global') + , process = global.process + , setTask = global.setImmediate + , clearTask = global.clearImmediate + , MessageChannel = global.MessageChannel + , counter = 0 + , queue = {} + , ONREADYSTATECHANGE = 'onreadystatechange' + , defer, channel, port; +var run = function(){ + var id = +this; + if(queue.hasOwnProperty(id)){ + var fn = queue[id]; + delete queue[id]; + fn(); + } +}; +var listner = function(event){ + run.call(event.data); +}; +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if(!setTask || !clearTask){ + setTask = function setImmediate(fn){ + var args = [], i = 1; + while(arguments.length > i)args.push(arguments[i++]); + queue[++counter] = function(){ + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id){ + delete queue[id]; + }; + // Node.js 0.8- + if(_dereq_('./$.cof')(process) == 'process'){ + defer = function(id){ + process.nextTick(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if(MessageChannel){ + channel = new MessageChannel; + port = channel.port2; + channel.port1.onmessage = listner; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ + defer = function(id){ + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listner, false); + // IE8- + } else if(ONREADYSTATECHANGE in cel('script')){ + defer = function(id){ + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function(id){ + setTimeout(ctx(run, id, 1), 0); + }; + } +} +module.exports = { + set: setTask, + clear: clearTask +}; +},{"./$.cof":47,"./$.ctx":52,"./$.dom-create":55,"./$.global":61,"./$.html":64,"./$.invoke":65}],94:[function(_dereq_,module,exports){ +// 7.1.4 ToInteger +var ceil = Math.ceil + , floor = Math.floor; +module.exports = function(it){ + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; +},{}],95:[function(_dereq_,module,exports){ +// to indexed object, toObject with fallback for non-array-like ES3 strings +var IObject = _dereq_('./$.iobject') + , defined = _dereq_('./$.defined'); +module.exports = function(it){ + return IObject(defined(it)); +}; +},{"./$.defined":53,"./$.iobject":66}],96:[function(_dereq_,module,exports){ +// 7.1.15 ToLength +var toInteger = _dereq_('./$.to-integer') + , min = Math.min; +module.exports = function(it){ + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; +},{"./$.to-integer":94}],97:[function(_dereq_,module,exports){ +// 7.1.13 ToObject(argument) +var defined = _dereq_('./$.defined'); +module.exports = function(it){ + return Object(defined(it)); +}; +},{"./$.defined":53}],98:[function(_dereq_,module,exports){ +var id = 0 + , px = Math.random(); +module.exports = function(key){ + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; +},{}],99:[function(_dereq_,module,exports){ +var store = _dereq_('./$.shared')('wks') + , uid = _dereq_('./$.uid') + , Symbol = _dereq_('./$.global').Symbol; +module.exports = function(name){ + return store[name] || (store[name] = + Symbol && Symbol[name] || (Symbol || uid)('Symbol.' + name)); +}; +},{"./$.global":61,"./$.shared":89,"./$.uid":98}],100:[function(_dereq_,module,exports){ +var classof = _dereq_('./$.classof') + , ITERATOR = _dereq_('./$.wks')('iterator') + , Iterators = _dereq_('./$.iterators'); +module.exports = _dereq_('./$.core').getIteratorMethod = function(it){ + if(it != undefined)return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; +}; +},{"./$.classof":46,"./$.core":51,"./$.iterators":75,"./$.wks":99}],101:[function(_dereq_,module,exports){ +var anObject = _dereq_('./$.an-object') + , get = _dereq_('./core.get-iterator-method'); +module.exports = _dereq_('./$.core').getIterator = function(it){ + var iterFn = get(it); + if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); + return anObject(iterFn.call(it)); +}; +},{"./$.an-object":45,"./$.core":51,"./core.get-iterator-method":100}],102:[function(_dereq_,module,exports){ +var classof = _dereq_('./$.classof') + , ITERATOR = _dereq_('./$.wks')('iterator') + , Iterators = _dereq_('./$.iterators'); +module.exports = _dereq_('./$.core').isIterable = function(it){ + var O = Object(it); + return O[ITERATOR] !== undefined + || '@@iterator' in O + || Iterators.hasOwnProperty(classof(O)); +}; +},{"./$.classof":46,"./$.core":51,"./$.iterators":75,"./$.wks":99}],103:[function(_dereq_,module,exports){ +'use strict'; +var ctx = _dereq_('./$.ctx') + , $export = _dereq_('./$.export') + , toObject = _dereq_('./$.to-object') + , call = _dereq_('./$.iter-call') + , isArrayIter = _dereq_('./$.is-array-iter') + , toLength = _dereq_('./$.to-length') + , getIterFn = _dereq_('./core.get-iterator-method'); +$export($export.S + $export.F * !_dereq_('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ + var O = toObject(arrayLike) + , C = typeof this == 'function' ? this : Array + , $$ = arguments + , $$len = $$.length + , mapfn = $$len > 1 ? $$[1] : undefined + , mapping = mapfn !== undefined + , index = 0 + , iterFn = getIterFn(O) + , length, result, step, iterator; + if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ + for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ + result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value; + } + } else { + length = toLength(O.length); + for(result = new C(length); length > index; index++){ + result[index] = mapping ? mapfn(O[index], index) : O[index]; } + } + result.length = index; + return result; + } +}); - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; +},{"./$.ctx":52,"./$.export":57,"./$.is-array-iter":67,"./$.iter-call":70,"./$.iter-detect":73,"./$.to-length":96,"./$.to-object":97,"./core.get-iterator-method":100}],104:[function(_dereq_,module,exports){ +'use strict'; +var addToUnscopables = _dereq_('./$.add-to-unscopables') + , step = _dereq_('./$.iter-step') + , Iterators = _dereq_('./$.iterators') + , toIObject = _dereq_('./$.to-iobject'); - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } +// 22.1.3.4 Array.prototype.entries() +// 22.1.3.13 Array.prototype.keys() +// 22.1.3.29 Array.prototype.values() +// 22.1.3.30 Array.prototype[@@iterator]() +module.exports = _dereq_('./$.iter-define')(Array, 'Array', function(iterated, kind){ + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function(){ + var O = this._t + , kind = this._k + , index = this._i++; + if(!O || index >= O.length){ + this._t = undefined; + return step(1); + } + if(kind == 'keys' )return step(0, index); + if(kind == 'values')return step(0, O[index]); + return step(0, [index, O[index]]); +}, 'values'); - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +Iterators.Arguments = Iterators.Array; - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function abrupt(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.next = finallyEntry.finallyLoc; - } else { - this.complete(record); - } - - return ContinueSentinel; - }, - - complete: function complete(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = record.arg; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - }, - - finish: function finish(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); +},{"./$.add-to-unscopables":44,"./$.iter-define":72,"./$.iter-step":74,"./$.iterators":75,"./$.to-iobject":95}],105:[function(_dereq_,module,exports){ +'use strict'; +var strong = _dereq_('./$.collection-strong'); - "catch": function _catch(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } +// 23.1 Map Objects +_dereq_('./$.collection')('Map', function(get){ + return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; +}, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key){ + var entry = strong.getEntry(this, key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value){ + return strong.def(this, key === 0 ? 0 : key, value); + } +}, strong, true); +},{"./$.collection":50,"./$.collection-strong":48}],106:[function(_dereq_,module,exports){ +// 20.2.2.22 Math.log2(x) +var $export = _dereq_('./$.export'); - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, +$export($export.S, 'Math', { + log2: function log2(x){ + return Math.log(x) / Math.LN2; + } +}); +},{"./$.export":57}],107:[function(_dereq_,module,exports){ +// 19.1.3.1 Object.assign(target, source) +var $export = _dereq_('./$.export'); - delegateYield: function delegateYield(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; +$export($export.S + $export.F, 'Object', {assign: _dereq_('./$.object-assign')}); +},{"./$.export":57,"./$.object-assign":80}],108:[function(_dereq_,module,exports){ +// 19.1.2.5 Object.freeze(O) +var isObject = _dereq_('./$.is-object'); - return ContinueSentinel; - } +_dereq_('./$.object-sap')('freeze', function($freeze){ + return function freeze(it){ + return $freeze && isObject(it) ? $freeze(it) : it; }; -})( -// Among the various tricks for obtaining a reference to the global -// object, this seems to be the most reliable technique that does not -// use indirect eval (which violates Content Security Policy). -typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : undefined); -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9iYWJlbC1ydW50aW1lL3JlZ2VuZXJhdG9yL3J1bnRpbWUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QU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pbmVkKSB7XG4gICAgICAgICAgICAvLyBBIHJldHVybiBvciB0aHJvdyAod2hlbiB0aGUgZGVsZWdhdGUgaXRlcmF0b3IgaGFzIG5vIHRocm93XG4gICAgICAgICAgICAvLyBtZXRob2QpIGFsd2F5cyB0ZXJtaW5hdGVzIHRoZSB5aWVsZCogbG9vcC5cbiAgICAgICAgICAgIGNvbnRleHQuZGVsZWdhdGUgPSBudWxsO1xuXG4gICAgICAgICAgICAvLyBJZiB0aGUgZGVsZWdhdGUgaXRlcmF0b3IgaGFzIGEgcmV0dXJuIG1ldGhvZCwgZ2l2ZSBpdCBhXG4gICAgICAgICAgICAvLyBjaGFuY2UgdG8gY2xlYW4gdXAuXG4gICAgICAgICAgICB2YXIgcmV0dXJuTWV0aG9kID0gZGVsZWdhdGUuaXRlcmF0b3JbXCJyZXR1cm5cIl07XG4gICAgICAgICAgICBpZiAocmV0dXJuTWV0aG9kKSB7XG4gICAgICAgICAgICAgIHZhciByZWNvcmQgPSB0cnlDYXRjaChyZXR1cm5NZXRob2QsIGRlbGVnYXRlLml0ZXJhdG9yLCBhcmcpO1xuICAgICAgICAgICAgICBpZiAocmVjb3JkLnR5cGUgPT09IFwidGhyb3dcIikge1xuICAgICAgICAgICAgICAgIC8vIElmIHRoZSByZXR1cm4gbWV0aG9kIHRocmV3IGFuIGV4Y2VwdGlvbiwgbGV0IHRoYXRcbiAgICAgICAgICAgICAgICAvLyBleGNlcHRpb24gcHJldmFpbCBvdmVyIHRoZSBvcmlnaW5hbCByZXR1cm4gb3IgdGhyb3cuXG4gICAgICAgICAgICAgICAgbWV0aG9kID0gXCJ0aHJvd1wiO1xuICAgICAgICAgICAgICAgIGFyZyA9IHJlY29yZC5hcmc7XG4gICAgICAgICAgICAgICAgY29udGludWU7XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgaWYgKG1ldGhvZCA9PT0gXCJyZXR1cm5cIikge1xuICAgICAgICAgICAgICAvLyBDb250aW51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bGx5LlxuICAgICAgICAgICAgbWV0aG9kID0gXCJuZXh0XCI7XG4gICAgICAgICAgICBhcmcgPSB1bmRlZmluZWQ7XG4gICAgICAgICAgfVxuICAgICAgICB9IGVsc2UgaWYgKG1ldGhvZCA9PT0gXCJyZXR1cm5cIikge1xuICAgICAgICAgIGNvbnRleHQuYWJydXB0KFwicmV0dXJuXCIsIGFyZyk7XG4gICAgICAgIH1cblxuICAgICAgICBzdGF0ZSA9IEdlblN0YXRlRXhlY3V0aW5nO1xuXG4gICAgICAgIHZhciByZWNvcmQgPSB0cnlDYXRjaChpbm5lckZuLCBzZWxmLCBjb250ZXh0KTtcbiAgICAgICAgaWYgKHJlY29yZC50eXBlID09PSBcIm5vcm1hbFwiKSB7XG4gICAgICAgICAgLy8gSWYgYW4gZXhjZXB0aW9uIGlzIHRocm93biBmcm9tIGlubmVyRm4sIHdlIGxlYXZlIHN0YXRlID09PVxuICAgICAgICAgIC8vIEdlblN0YXRlRXhlY3V0aW5nIGFuZCBsb29wIGJhY2sgZm9yIGFub3RoZXIgaW52b2NhdGlvbi5cbiAgICAgICAgICBzdGF0ZSA9IGNvbnRleHQuZG9uZSA/IEdlblN0YXRlQ29tcGxldGVkIDogR2VuU3RhdGVTdXNwZW5kZWRZaWVsZDtcblxuICAgICAgICAgIHZhciBpbmZvID0ge1xuICAgICAgICAgICAgdmFsdWU6IHJlY29yZC5hcmcsXG4gICAgICAgICAgICBkb25lOiBjb250ZXh0LmRvbmVcbiAgICAgICAgICB9O1xuXG4gICAgICAgICAgaWYgKHJlY29yZC5hcmcgPT09IENvbnRpbnVlU2VudGluZWwpIHtcbiAgICAgICAgICAgIGlmIChjb250ZXh0LmRlbGVnYXRlICYmIG1ldGhvZCA9PT0gXCJuZXh0XCIpIHtcbiAgICAgICAgICAgICAgLy8gRGVsaWJlcmF0ZWx5IGZvcmdldCB0aGUgbGFzdCBzZW50IHZhbHVlIHNvIHRoYXQgd2UgZG9uJ3RcbiAgICAgICAgICAgICAgLy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ogZnVuY3Rpb24gY29tcGxldGUocmVjb3JkLCBhZnRlckxvYykge1xuICAgICAgaWYgKHJlY29yZC50eXBlID09PSBcInRocm93XCIpIHtcbiAgICAgICAgdGhyb3cgcmVjb3JkLmFyZztcbiAgICAgIH1cblxuICAgICAgaWYgKHJlY29yZC50eXBlID09PSBcImJyZWFrXCIgfHwgcmVjb3JkLnR5cGUgPT09IFwiY29udGludWVcIikge1xuICAgICAgICB0aGlzLm5leHQgPSByZWNvcmQuYXJnO1xuICAgICAgfSBlbHNlIGlmIChyZWNvcmQudHlwZSA9PT0gXCJyZXR1cm5cIikge1xuICAgICAgICB0aGlzLnJ2YWwgPSByZWNvcmQuYXJnO1xuICAgICAgICB0aGlzLm5leHQgPSBcImVuZFwiO1xuICAgICAgfSBlbHNlIGlmIChyZWNvcmQudHlwZSA9PT0gXCJub3JtYWxcIiAmJiBhZnRlckxvYykge1xuICAgICAgICB0aGlzLm5leHQgPSBhZnRlckxvYztcbiAgICAgIH1cbiAgICB9LFxuXG4gICAgZmluaXNoOiBmdW5jdGlvbiBmaW5pc2goZmluYWxseUxvYykge1xuICAgICAgZm9yICh2YXIgaSA9IHRoaXMudHJ5RW50cmllcy5sZW5ndGggLSAxOyBpID49IDA7IC0taSkge1xuICAgICAgICB2YXIgZW50cnkgPSB0aGlzLnRyeUVudHJpZXNbaV07XG4gICAgICAgIGlmIChlbnRyeS5maW5hbGx5TG9jID09PSBmaW5hbGx5TG9jKSB7XG4gICAgICAgICAgdGhpcy5jb21wbGV0ZShlbnRyeS5jb21wbGV0aW9uLCBlbnRyeS5hZnRlckxvYyk7XG4gICAgICAgICAgcmVzZXRUcnlFbnRyeShlbnRyeSk7XG4gICAgICAgICAgcmV0dXJuIENvbnRpbnVlU2VudGluZWw7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICB9LFxuXG4gICAgXCJjYXRjaFwiOiBmdW5jdGlvbiBfY2F0Y2godHJ5TG9jKSB7XG4gICAgICBmb3IgKHZhciBpID0gdG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EgcmVmZXJlbmNlIHRvIHRoZSBnbG9iYWxcbi8vIG9iamVjdCwgdGhpcyBzZWVtcyB0byBiZSB0aGUgbW9zdCByZWxpYWJsZSB0ZWNobmlxdWUgdGhhdCBkb2VzIG5vdFxuLy8gdXNlIGluZGlyZWN0IGV2YWwgKHdoaWNoIHZpb2xhdGVzIENvbnRlbnQgU2VjdXJpdHkgUG9saWN5KS5cbnR5cGVvZiBnbG9iYWwgPT09IFwib2JqZWN0XCIgPyBnbG9iYWwgOiB0eXBlb2Ygd2luZG93ID09PSBcIm9iamVjdFwiID8gd2luZG93IDogdHlwZW9mIHNlbGYgPT09IFwib2JqZWN0XCIgPyBzZWxmIDogdW5kZWZpbmVkKTsiXX0= -},{"_process":188,"babel-runtime/core-js/object/create":7,"babel-runtime/core-js/promise":14,"babel-runtime/core-js/symbol":16,"babel-runtime/core-js/symbol/iterator":17}],28:[function(_dereq_,module,exports){ -var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -;(function (exports) { - 'use strict'; - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS) - return 62 // '+' - if (code === SLASH) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } - - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +}); +},{"./$.is-object":69,"./$.object-sap":81}],109:[function(_dereq_,module,exports){ +// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) +var toIObject = _dereq_('./$.to-iobject'); - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 +_dereq_('./$.object-sap')('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){ + return function getOwnPropertyDescriptor(it, key){ + return $getOwnPropertyDescriptor(toIObject(it), key); + }; +}); +},{"./$.object-sap":81,"./$.to-iobject":95}],110:[function(_dereq_,module,exports){ +// 19.1.2.14 Object.keys(O) +var toObject = _dereq_('./$.to-object'); - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) +_dereq_('./$.object-sap')('keys', function($keys){ + return function keys(it){ + return $keys(toObject(it)); + }; +}); +},{"./$.object-sap":81,"./$.to-object":97}],111:[function(_dereq_,module,exports){ +// 19.1.3.19 Object.setPrototypeOf(O, proto) +var $export = _dereq_('./$.export'); +$export($export.S, 'Object', {setPrototypeOf: _dereq_('./$.set-proto').set}); +},{"./$.export":57,"./$.set-proto":86}],112:[function(_dereq_,module,exports){ - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length +},{}],113:[function(_dereq_,module,exports){ +'use strict'; +var $ = _dereq_('./$') + , LIBRARY = _dereq_('./$.library') + , global = _dereq_('./$.global') + , ctx = _dereq_('./$.ctx') + , classof = _dereq_('./$.classof') + , $export = _dereq_('./$.export') + , isObject = _dereq_('./$.is-object') + , anObject = _dereq_('./$.an-object') + , aFunction = _dereq_('./$.a-function') + , strictNew = _dereq_('./$.strict-new') + , forOf = _dereq_('./$.for-of') + , setProto = _dereq_('./$.set-proto').set + , same = _dereq_('./$.same-value') + , SPECIES = _dereq_('./$.wks')('species') + , speciesConstructor = _dereq_('./$.species-constructor') + , asap = _dereq_('./$.microtask') + , PROMISE = 'Promise' + , process = global.process + , isNode = classof(process) == 'process' + , P = global[PROMISE] + , Wrapper; - var L = 0 +var testResolve = function(sub){ + var test = new P(function(){}); + if(sub)test.constructor = Object; + return P.resolve(test) === test; +}; - function push (v) { - arr[L++] = v - } +var USE_NATIVE = function(){ + var works = false; + function P2(x){ + var self = new P(x); + setProto(self, P2.prototype); + return self; + } + try { + works = P && P.resolve && testResolve(); + setProto(P2, P); + P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); + // actual Firefox has broken subclass support, test that + if(!(P2.resolve(5).then(function(){}) instanceof P2)){ + works = false; + } + // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 + if(works && _dereq_('./$.descriptors')){ + var thenableThenGotten = false; + P.resolve($.setDesc({}, 'then', { + get: function(){ thenableThenGotten = true; } + })); + works = thenableThenGotten; + } + } catch(e){ works = false; } + return works; +}(); - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) - push((tmp & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) - } +// helpers +var sameConstructor = function(a, b){ + // library wrapper special case + if(LIBRARY && a === P && b === Wrapper)return true; + return same(a, b); +}; +var getConstructor = function(C){ + var S = anObject(C)[SPECIES]; + return S != undefined ? S : C; +}; +var isThenable = function(it){ + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; +var PromiseCapability = function(C){ + var resolve, reject; + this.promise = new C(function($$resolve, $$reject){ + if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve), + this.reject = aFunction(reject) +}; +var perform = function(exec){ + try { + exec(); + } catch(e){ + return {error: e}; + } +}; +var notify = function(record, isReject){ + if(record.n)return; + record.n = true; + var chain = record.c; + asap(function(){ + var value = record.v + , ok = record.s == 1 + , i = 0; + var run = function(reaction){ + var handler = ok ? reaction.ok : reaction.fail + , resolve = reaction.resolve + , reject = reaction.reject + , result, then; + try { + if(handler){ + if(!ok)record.h = true; + result = handler === true ? value : handler(value); + if(result === reaction.promise){ + reject(TypeError('Promise-chain cycle')); + } else if(then = isThenable(result)){ + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch(e){ + reject(e); + } + }; + while(chain.length > i)run(chain[i++]); // variable length - can't use forEach + chain.length = 0; + record.n = false; + if(isReject)setTimeout(function(){ + var promise = record.p + , handler, console; + if(isUnhandled(promise)){ + if(isNode){ + process.emit('unhandledRejection', value, promise); + } else if(handler = global.onunhandledrejection){ + handler({promise: promise, reason: value}); + } else if((console = global.console) && console.error){ + console.error('Unhandled promise rejection', value); + } + } record.a = undefined; + }, 1); + }); +}; +var isUnhandled = function(promise){ + var record = promise._d + , chain = record.a || record.c + , i = 0 + , reaction; + if(record.h)return false; + while(chain.length > i){ + reaction = chain[i++]; + if(reaction.fail || !isUnhandled(reaction.promise))return false; + } return true; +}; +var $reject = function(value){ + var record = this; + if(record.d)return; + record.d = true; + record = record.r || record; // unwrap + record.v = value; + record.s = 2; + record.a = record.c.slice(); + notify(record, true); +}; +var $resolve = function(value){ + var record = this + , then; + if(record.d)return; + record.d = true; + record = record.r || record; // unwrap + try { + if(record.p === value)throw TypeError("Promise can't be resolved itself"); + if(then = isThenable(value)){ + asap(function(){ + var wrapper = {r: record, d: false}; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch(e){ + $reject.call(wrapper, e); + } + }); + } else { + record.v = value; + record.s = 1; + notify(record, false); + } + } catch(e){ + $reject.call({r: record, d: false}, e); // wrap + } +}; + +// constructor polyfill +if(!USE_NATIVE){ + // 25.4.3.1 Promise(executor) + P = function Promise(executor){ + aFunction(executor); + var record = this._d = { + p: strictNew(this, P, PROMISE), // <- promise + c: [], // <- awaiting reactions + a: undefined, // <- checked in isUnhandled reactions + s: 0, // <- state + d: false, // <- done + v: undefined, // <- value + h: false, // <- handled rejection + n: false // <- notify + }; + try { + executor(ctx($resolve, record, 1), ctx($reject, record, 1)); + } catch(err){ + $reject.call(record, err); + } + }; + _dereq_('./$.redefine-all')(P.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected){ + var reaction = new PromiseCapability(speciesConstructor(this, P)) + , promise = reaction.promise + , record = this._d; + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + record.c.push(reaction); + if(record.a)record.a.push(reaction); + if(record.s)notify(record, false); + return promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function(onRejected){ + return this.then(undefined, onRejected); + } + }); +} + +$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P}); +_dereq_('./$.set-to-string-tag')(P, PROMISE); +_dereq_('./$.set-species')(PROMISE); +Wrapper = _dereq_('./$.core')[PROMISE]; + +// statics +$export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r){ + var capability = new PromiseCapability(this) + , $$reject = capability.reject; + $$reject(r); + return capability.promise; + } +}); +$export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x){ + // instanceof instead of internal slot check because we should fix it without replacement native Promise core + if(x instanceof P && sameConstructor(x.constructor, this))return x; + var capability = new PromiseCapability(this) + , $$resolve = capability.resolve; + $$resolve(x); + return capability.promise; + } +}); +$export($export.S + $export.F * !(USE_NATIVE && _dereq_('./$.iter-detect')(function(iter){ + P.all(iter)['catch'](function(){}); +})), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable){ + var C = getConstructor(this) + , capability = new PromiseCapability(C) + , resolve = capability.resolve + , reject = capability.reject + , values = []; + var abrupt = perform(function(){ + forOf(iterable, false, values.push, values); + var remaining = values.length + , results = Array(remaining); + if(remaining)$.each.call(values, function(promise, index){ + var alreadyCalled = false; + C.resolve(promise).then(function(value){ + if(alreadyCalled)return; + alreadyCalled = true; + results[index] = value; + --remaining || resolve(results); + }, reject); + }); + else resolve(results); + }); + if(abrupt)reject(abrupt.error); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable){ + var C = getConstructor(this) + , capability = new PromiseCapability(C) + , reject = capability.reject; + var abrupt = perform(function(){ + forOf(iterable, false, function(promise){ + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if(abrupt)reject(abrupt.error); + return capability.promise; + } +}); +},{"./$":76,"./$.a-function":43,"./$.an-object":45,"./$.classof":46,"./$.core":51,"./$.ctx":52,"./$.descriptors":54,"./$.export":57,"./$.for-of":59,"./$.global":61,"./$.is-object":69,"./$.iter-detect":73,"./$.library":78,"./$.microtask":79,"./$.redefine-all":83,"./$.same-value":85,"./$.set-proto":86,"./$.set-species":87,"./$.set-to-string-tag":88,"./$.species-constructor":90,"./$.strict-new":91,"./$.wks":99}],114:[function(_dereq_,module,exports){ +'use strict'; +var strong = _dereq_('./$.collection-strong'); + +// 23.2 Set Objects +_dereq_('./$.collection')('Set', function(get){ + return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; +}, { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value){ + return strong.def(this, value = value === 0 ? 0 : value, value); + } +}, strong); +},{"./$.collection":50,"./$.collection-strong":48}],115:[function(_dereq_,module,exports){ +'use strict'; +var $at = _dereq_('./$.string-at')(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_dereq_('./$.iter-define')(String, 'String', function(iterated){ + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function(){ + var O = this._t + , index = this._i + , point; + if(index >= O.length)return {value: undefined, done: true}; + point = $at(O, index); + this._i += point.length; + return {value: point, done: false}; +}); +},{"./$.iter-define":72,"./$.string-at":92}],116:[function(_dereq_,module,exports){ +'use strict'; +// ECMAScript 6 symbols shim +var $ = _dereq_('./$') + , global = _dereq_('./$.global') + , has = _dereq_('./$.has') + , DESCRIPTORS = _dereq_('./$.descriptors') + , $export = _dereq_('./$.export') + , redefine = _dereq_('./$.redefine') + , $fails = _dereq_('./$.fails') + , shared = _dereq_('./$.shared') + , setToStringTag = _dereq_('./$.set-to-string-tag') + , uid = _dereq_('./$.uid') + , wks = _dereq_('./$.wks') + , keyOf = _dereq_('./$.keyof') + , $names = _dereq_('./$.get-names') + , enumKeys = _dereq_('./$.enum-keys') + , isArray = _dereq_('./$.is-array') + , anObject = _dereq_('./$.an-object') + , toIObject = _dereq_('./$.to-iobject') + , createDesc = _dereq_('./$.property-desc') + , getDesc = $.getDesc + , setDesc = $.setDesc + , _create = $.create + , getNames = $names.get + , $Symbol = global.Symbol + , $JSON = global.JSON + , _stringify = $JSON && $JSON.stringify + , setter = false + , HIDDEN = wks('_hidden') + , isEnum = $.isEnum + , SymbolRegistry = shared('symbol-registry') + , AllSymbols = shared('symbols') + , useNative = typeof $Symbol == 'function' + , ObjectProto = Object.prototype; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = DESCRIPTORS && $fails(function(){ + return _create(setDesc({}, 'a', { + get: function(){ return setDesc(this, 'a', {value: 7}).a; } + })).a != 7; +}) ? function(it, key, D){ + var protoDesc = getDesc(ObjectProto, key); + if(protoDesc)delete ObjectProto[key]; + setDesc(it, key, D); + if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc); +} : setDesc; + +var wrap = function(tag){ + var sym = AllSymbols[tag] = _create($Symbol.prototype); + sym._k = tag; + DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, { + configurable: true, + set: function(value){ + if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + } + }); + return sym; +}; + +var isSymbol = function(it){ + return typeof it == 'symbol'; +}; + +var $defineProperty = function defineProperty(it, key, D){ + if(D && has(AllSymbols, key)){ + if(!D.enumerable){ + if(!has(it, HIDDEN))setDesc(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; + D = _create(D, {enumerable: createDesc(0, false)}); + } return setSymbolDesc(it, key, D); + } return setDesc(it, key, D); +}; +var $defineProperties = function defineProperties(it, P){ + anObject(it); + var keys = enumKeys(P = toIObject(P)) + , i = 0 + , l = keys.length + , key; + while(l > i)$defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P){ + return P === undefined ? _create(it) : $defineProperties(_create(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key){ + var E = isEnum.call(this, key); + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] + ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ + var D = getDesc(it = toIObject(it), key); + if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it){ + var names = getNames(toIObject(it)) + , result = [] + , i = 0 + , key; + while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); + return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ + var names = getNames(toIObject(it)) + , result = [] + , i = 0 + , key; + while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); + return result; +}; +var $stringify = function stringify(it){ + if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined + var args = [it] + , i = 1 + , $$ = arguments + , replacer, $replacer; + while($$.length > i)args.push($$[i++]); + replacer = args[1]; + if(typeof replacer == 'function')$replacer = replacer; + if($replacer || !isArray(replacer))replacer = function(key, value){ + if($replacer)value = $replacer.call(this, key, value); + if(!isSymbol(value))return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); +}; +var buggyJSON = $fails(function(){ + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; +}); + +// 19.4.1.1 Symbol([description]) +if(!useNative){ + $Symbol = function Symbol(){ + if(isSymbol(this))throw TypeError('Symbol is not a constructor'); + return wrap(uid(arguments.length > 0 ? arguments[0] : undefined)); + }; + redefine($Symbol.prototype, 'toString', function toString(){ + return this._k; + }); + + isSymbol = function(it){ + return it instanceof $Symbol; + }; + + $.create = $create; + $.isEnum = $propertyIsEnumerable; + $.getDesc = $getOwnPropertyDescriptor; + $.setDesc = $defineProperty; + $.setDescs = $defineProperties; + $.getNames = $names.get = $getOwnPropertyNames; + $.getSymbols = $getOwnPropertySymbols; + + if(DESCRIPTORS && !_dereq_('./$.library')){ + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } +} + +var symbolStatics = { + // 19.4.2.1 Symbol.for(key) + 'for': function(key){ + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(key){ + return keyOf(SymbolRegistry, key); + }, + useSetter: function(){ setter = true; }, + useSimple: function(){ setter = false; } +}; +// 19.4.2.2 Symbol.hasInstance +// 19.4.2.3 Symbol.isConcatSpreadable +// 19.4.2.4 Symbol.iterator +// 19.4.2.6 Symbol.match +// 19.4.2.8 Symbol.replace +// 19.4.2.9 Symbol.search +// 19.4.2.10 Symbol.species +// 19.4.2.11 Symbol.split +// 19.4.2.12 Symbol.toPrimitive +// 19.4.2.13 Symbol.toStringTag +// 19.4.2.14 Symbol.unscopables +$.each.call(( + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + + 'species,split,toPrimitive,toStringTag,unscopables' +).split(','), function(it){ + var sym = wks(it); + symbolStatics[it] = useNative ? sym : wrap(sym); +}); + +setter = true; + +$export($export.G + $export.W, {Symbol: $Symbol}); + +$export($export.S, 'Symbol', symbolStatics); + +$export($export.S + $export.F * !useNative, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && $export($export.S + $export.F * (!useNative || buggyJSON), 'JSON', {stringify: $stringify}); + +// 19.4.3.5 Symbol.prototype[@@toStringTag] +setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +setToStringTag(global.JSON, 'JSON', true); +},{"./$":76,"./$.an-object":45,"./$.descriptors":54,"./$.enum-keys":56,"./$.export":57,"./$.fails":58,"./$.get-names":60,"./$.global":61,"./$.has":62,"./$.is-array":68,"./$.keyof":77,"./$.library":78,"./$.property-desc":82,"./$.redefine":84,"./$.set-to-string-tag":88,"./$.shared":89,"./$.to-iobject":95,"./$.uid":98,"./$.wks":99}],117:[function(_dereq_,module,exports){ +// https://github.com/DavidBruant/Map-Set.prototype.toJSON +var $export = _dereq_('./$.export'); + +$export($export.P, 'Map', {toJSON: _dereq_('./$.collection-to-json')('Map')}); +},{"./$.collection-to-json":49,"./$.export":57}],118:[function(_dereq_,module,exports){ +// https://github.com/DavidBruant/Map-Set.prototype.toJSON +var $export = _dereq_('./$.export'); + +$export($export.P, 'Set', {toJSON: _dereq_('./$.collection-to-json')('Set')}); +},{"./$.collection-to-json":49,"./$.export":57}],119:[function(_dereq_,module,exports){ +_dereq_('./es6.array.iterator'); +var Iterators = _dereq_('./$.iterators'); +Iterators.NodeList = Iterators.HTMLCollection = Iterators.Array; +},{"./$.iterators":75,"./es6.array.iterator":104}],120:[function(_dereq_,module,exports){ +(function (global){ +// This method of obtaining a reference to the global object needs to be +// kept identical to the way it is obtained in runtime.js +var g = + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this; + +// Use `getOwnPropertyNames` because not all browsers support calling +// `hasOwnProperty` on the global `self` object in a worker. See #183. +var hadRuntime = g.regeneratorRuntime && + Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; + +// Save the old regeneratorRuntime in case it needs to be restored later. +var oldRuntime = hadRuntime && g.regeneratorRuntime; + +// Force reevalutation of runtime.js. +g.regeneratorRuntime = undefined; + +module.exports = _dereq_("./runtime"); + +if (hadRuntime) { + // Restore the original runtime. + g.regeneratorRuntime = oldRuntime; +} else { + // Remove the global property added by runtime.js. + try { + delete g.regeneratorRuntime; + } catch(e) { + g.regeneratorRuntime = undefined; + } +} + +module.exports = { "default": module.exports, __esModule: true }; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./runtime":121}],121:[function(_dereq_,module,exports){ +(function (process,global){ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + +"use strict"; + +var _Symbol = _dereq_("babel-runtime/core-js/symbol")["default"]; + +var _Symbol$iterator = _dereq_("babel-runtime/core-js/symbol/iterator")["default"]; + +var _Object$create = _dereq_("babel-runtime/core-js/object/create")["default"]; + +var _Promise = _dereq_("babel-runtime/core-js/promise")["default"]; + +!(function (global) { + "use strict"; + + var hasOwn = Object.prototype.hasOwnProperty; + var undefined; // More compressible than void 0. + var iteratorSymbol = typeof _Symbol === "function" && _Symbol$iterator || "@@iterator"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided, then outerFn.prototype instanceof Generator. + var generator = _Object$create((outerFn || Generator).prototype); + + generator._invoke = makeInvokeMethod(innerFn, self || null, new Context(tryLocsList || [])); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + prototype[method] = function (arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function (genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" : false; + }; + + runtime.mark = function (genFun) { + genFun.__proto__ = GeneratorFunctionPrototype; + genFun.prototype = _Object$create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `value instanceof AwaitArgument` to determine if the yielded value is + // meant to be awaited. Some may consider the name of this method too + // cutesy, but they are curmudgeons. + runtime.awrap = function (arg) { + return new AwaitArgument(arg); + }; + + function AwaitArgument(arg) { + this.arg = arg; + } + + function AsyncIterator(generator) { + // This invoke function is written in a style that assumes some + // calling function (or Promise) will handle exceptions. + function invoke(method, arg) { + var result = generator[method](arg); + var value = result.value; + return value instanceof AwaitArgument ? _Promise.resolve(value.arg).then(invokeNext, invokeThrow) : _Promise.resolve(value).then(function (unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + return result; + }); + } + + if (typeof process === "object" && process.domain) { + invoke = process.domain.bind(invoke); + } + + var invokeNext = invoke.bind(generator, "next"); + var invokeThrow = invoke.bind(generator, "throw"); + var invokeReturn = invoke.bind(generator, "return"); + var previousPromise; + + function enqueue(method, arg) { + var enqueueResult = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then(function () { + return invoke(method, arg); + }) : new _Promise(function (resolve) { + resolve(invoke(method, arg)); + }); + + // Avoid propagating enqueueResult failures to Promises returned by + // later invocations of the iterator. + previousPromise = enqueueResult["catch"](function (ignored) {}); + + return enqueueResult; + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function (innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); + + return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + while (true) { + var delegate = context.delegate; + if (delegate) { + if (method === "return" || method === "throw" && delegate.iterator[method] === undefined) { + // A return or throw (when the delegate iterator has no throw + // method) always terminates the yield* loop. + context.delegate = null; + + // If the delegate iterator has a return method, give it a + // chance to clean up. + var returnMethod = delegate.iterator["return"]; + if (returnMethod) { + var record = tryCatch(returnMethod, delegate.iterator, arg); + if (record.type === "throw") { + // If the return method threw an exception, let that + // exception prevail over the original return or throw. + method = "throw"; + arg = record.arg; + continue; + } + } + + if (method === "return") { + // Continue with the outer return, now that the delegate + // iterator has been terminated. + continue; + } + } + + var record = tryCatch(delegate.iterator[method], delegate.iterator, arg); + + if (record.type === "throw") { + context.delegate = null; + + // Like returning generator.throw(uncaught), but without the + // overhead of an extra function call. + method = "throw"; + arg = record.arg; + continue; + } + + // Delegate generator ran and handled its own exceptions so + // regardless of what the method was, we continue as if it is + // "next" with an undefined arg. + method = "next"; + arg = undefined; + + var info = record.arg; + if (info.done) { + context[delegate.resultName] = info.value; + context.next = delegate.nextLoc; + } else { + state = GenStateSuspendedYield; + return info; + } + + context.delegate = null; + } + + if (method === "next") { + if (state === GenStateSuspendedYield) { + context.sent = arg; + } else { + context.sent = undefined; + } + } else if (method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw arg; + } + + if (context.dispatchException(arg)) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + method = "next"; + arg = undefined; + } + } else if (method === "return") { + context.abrupt("return", arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done ? GenStateCompleted : GenStateSuspendedYield; + + var info = { + value: record.arg, + done: context.done + }; + + if (record.arg === ContinueSentinel) { + if (context.delegate && method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + arg = undefined; + } + } else { + return info; + } + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(arg) call above. + method = "throw"; + arg = record.arg; + } + } + }; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[iteratorSymbol] = function () { + return this; + }; + + Gp.toString = function () { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function (object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function reset(skipTempReset) { + this.prev = 0; + this.next = 0; + this.sent = undefined; + this.done = false; + this.delegate = null; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function stop() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function dispatchException(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + return !!caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function abrupt(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.next = finallyEntry.finallyLoc; + } else { + this.complete(record); + } + + return ContinueSentinel; + }, + + complete: function complete(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = record.arg; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + }, + + finish: function finish(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function _catch(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function delegateYield(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + return ContinueSentinel; + } + }; +})( +// Among the various tricks for obtaining a reference to the global +// object, this seems to be the most reliable technique that does not +// use indirect eval (which violates Content Security Policy). +typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : undefined); +}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":137,"babel-runtime/core-js/object/create":7,"babel-runtime/core-js/promise":14,"babel-runtime/core-js/symbol":16,"babel-runtime/core-js/symbol/iterator":17}],122:[function(_dereq_,module,exports){ +'use strict' + +module.exports = boxIntersectWrapper + +var pool = _dereq_('typedarray-pool') +var sweep = _dereq_('./lib/sweep') +var boxIntersectIter = _dereq_('./lib/intersect') + +function boxEmpty(d, box) { + for(var j=0; j>>1 + if(d <= 0) { + return + } + + var retval + + //Convert red boxes + var redList = pool.mallocDouble(2*d*n) + var redIds = pool.mallocInt32(n) + n = convertBoxes(red, d, redList, redIds) + + if(n > 0) { + if(d === 1 && full) { + //Special case: 1d complete + sweep.init(n) + retval = sweep.sweepComplete( + d, visit, + 0, n, redList, redIds, + 0, n, redList, redIds) + } else { + + //Convert blue boxes + var blueList = pool.mallocDouble(2*d*m) + var blueIds = pool.mallocInt32(m) + m = convertBoxes(blue, d, blueList, blueIds) + + if(m > 0) { + sweep.init(n+m) + + if(d === 1) { + //Special case: 1d bipartite + retval = sweep.sweepBipartite( + d, visit, + 0, n, redList, redIds, + 0, m, blueList, blueIds) + } else { + //General case: d>1 + retval = boxIntersectIter( + d, visit, full, + n, redList, redIds, + m, blueList, blueIds) + } + + pool.free(blueList) + pool.free(blueIds) + } + } + + pool.free(redList) + pool.free(redIds) + } + + return retval +} + +//User-friendly wrapper, handle full input and no-visitor cases +function boxIntersectWrapper(arg0, arg1, arg2) { + var result + switch(arguments.length) { + case 1: + result = [] + boxIntersect(arg0, arg0, function(i,j) { + result.push([i, j]) + }, true) + return result + case 2: + if(typeof arg1 === 'function') { + var visit = arg1 + return boxIntersect(arg0, arg0, visit, true) + } else { + result = [] + boxIntersect(arg0, arg1, function(i,j) { + result.push([i, j]) + }, false) + return result + } + case 3: + return boxIntersect(arg0, arg1, arg2, false) + default: + throw new Error('box-intersect: Invalid arguments') + } +} +},{"./lib/intersect":124,"./lib/sweep":128,"typedarray-pool":131}],123:[function(_dereq_,module,exports){ +'use strict' - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } else if (placeHolders === 1) { - tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) - push((tmp >> 8) & 0xFF) - push(tmp & 0xFF) - } +var DIMENSION = 'd' +var AXIS = 'ax' +var VISIT = 'vv' +var FLIP = 'fp' - return arr - } +var ELEM_SIZE = 'es' - function uint8ToBase64 (uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length +var RED_START = 'rs' +var RED_END = 're' +var RED_BOXES = 'rb' +var RED_INDEX = 'ri' +var RED_PTR = 'rp' - function encode (num) { - return lookup.charAt(num) - } +var BLUE_START = 'bs' +var BLUE_END = 'be' +var BLUE_BOXES = 'bb' +var BLUE_INDEX = 'bi' +var BLUE_PTR = 'bp' - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } +var RETVAL = 'rv' - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output += tripletToBase64(temp) - } +var INNER_LABEL = 'Q' - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - } +var ARGS = [ + DIMENSION, + AXIS, + VISIT, + RED_START, + RED_END, + RED_BOXES, + RED_INDEX, + BLUE_START, + BLUE_END, + BLUE_BOXES, + BLUE_INDEX +] - return output - } +function generateBruteForce(redMajor, flip, full) { + var funcName = 'bruteForce' + + (redMajor ? 'Red' : 'Blue') + + (flip ? 'Flip' : '') + + (full ? 'Full' : '') + + var code = ['function ', funcName, '(', ARGS.join(), '){', + 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] + + var redLoop = + 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + + 'i<' + RED_END +';' + + '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + + 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + + 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + + 'xi=' + RED_INDEX + '[i];' + + var blueLoop = + 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + + 'j<' + BLUE_END + ';' + + '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + + 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + + (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + + 'yi=' + BLUE_INDEX + '[j];' + + if(redMajor) { + code.push(redLoop, INNER_LABEL, ':', blueLoop) + } else { + code.push(blueLoop, INNER_LABEL, ':', redLoop) + } + + if(full) { + code.push('if(y1' + + BLUE_END + '-' + BLUE_START + '){') + + if(full) { + invoke(true, false) + code.push('}else{') + invoke(false, false) + } else { + code.push('if(' + FLIP + '){') + invoke(true, true) + code.push('}else{') + invoke(true, false) + code.push('}}else{if(' + FLIP + '){') + invoke(false, true) + code.push('}else{') + invoke(false, false) + code.push('}') + } + code.push('}}return ' + funcName) + + var codeStr = prefix.join('') + code.join('') + var proc = new Function(codeStr) + return proc() +} + + +exports.partial = bruteForcePlanner(false) +exports.full = bruteForcePlanner(true) +},{}],124:[function(_dereq_,module,exports){ +'use strict' + +module.exports = boxIntersectIter + +var pool = _dereq_('typedarray-pool') +var bits = _dereq_('bit-twiddle') +var bruteForce = _dereq_('./brute') +var bruteForcePartial = bruteForce.partial +var bruteForceFull = bruteForce.full +var sweep = _dereq_('./sweep') +var findMedian = _dereq_('./median') +var genPartition = _dereq_('./partition') + +//Twiddle parameters +var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search +var SCAN_CUTOFF = (1<<22) //Cut off for two way scan +var SCAN_COMPLETE_CUTOFF = (1<<22) + +//Partition functions +var partitionInteriorContainsInterval = genPartition( + '!(lo>=p0)&&!(p1>=hi)', + ['p0', 'p1']) + +var partitionStartEqual = genPartition( + 'lo===p0', + ['p0']) + +var partitionStartLessThan = genPartition( + 'lo 0) - (v < 0); +red_loop: + for(var i=redStart, redPtr=redStart*elemSize; i> (INT_BITS-1); - return (v ^ mask) - mask; -} +//Special case: Intersect one point with list of intervals +function onePointFull( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueOffset, blue, blueId) { -//Computes minimum of integers x and y -exports.min = function(x, y) { - return y ^ ((x ^ y) & -(x < y)); -} + var elemSize = 2 * d + var bluePtr = blueOffset * elemSize + var blueX = blue[bluePtr + axis] -//Computes maximum of integers x and y -exports.max = function(x, y) { - return x ^ ((x ^ y) & -(x < y)); +red_loop: + for(var i=redStart, redPtr=redStart*elemSize; i 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); -} + //Reserve memory for stack + iterInit(d, xSize + ySize) -//Computes log base 10 of v -exports.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} + var top = 0 + var elemSize = 2 * d + var retval -//Counts number of bits -exports.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; -} + iterPush(top++, + 0, + 0, xSize, + 0, ySize, + initFull ? 16 : 0, + -Infinity, Infinity) + if(!initFull) { + iterPush(top++, + 0, + 0, ySize, + 0, xSize, + 1, + -Infinity, Infinity) + } -//Counts number of trailing zeros -function countTrailingZeros(v) { - var c = 32; - v &= -v; - if (v) c--; - if (v & 0x0000FFFF) c -= 16; - if (v & 0x00FF00FF) c -= 8; - if (v & 0x0F0F0F0F) c -= 4; - if (v & 0x33333333) c -= 2; - if (v & 0x55555555) c -= 1; - return c; -} -exports.countTrailingZeros = countTrailingZeros; + while(top > 0) { + top -= 1 -//Rounds to next power of 2 -exports.nextPow2 = function(v) { - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; -} + var iptr = top * IFRAME_SIZE + var axis = BOX_ISTACK[iptr] + var redStart = BOX_ISTACK[iptr+1] + var redEnd = BOX_ISTACK[iptr+2] + var blueStart = BOX_ISTACK[iptr+3] + var blueEnd = BOX_ISTACK[iptr+4] + var state = BOX_ISTACK[iptr+5] -//Rounds down to previous power of 2 -exports.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); -} + var dptr = top * DFRAME_SIZE + var lo = BOX_DSTACK[dptr] + var hi = BOX_DSTACK[dptr+1] -//Computes parity of word -exports.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; -} + //Unpack state info + var flip = (state & 1) + var full = !!(state & 16) -var REVERSE_TABLE = new Array(256); + //Unpack indices + var red = xBoxes + var redIndex = xIndex + var blue = yBoxes + var blueIndex = yIndex + if(flip) { + red = yBoxes + redIndex = yIndex + blue = xBoxes + blueIndex = xIndex + } -(function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; + if(state & 2) { + redEnd = partitionStartLessThan( + d, axis, + redStart, redEnd, red, redIndex, + hi) + if(redStart >= redEnd) { + continue + } } - tab[i] = (r << s) & 0xff; - } -})(REVERSE_TABLE); - -//Reverse bits in a 32 bit word -exports.reverse = function(v) { - return (REVERSE_TABLE[ v & 0xff] << 24) | - (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; -} + if(state & 4) { + redStart = partitionEndLessThanEqual( + d, axis, + redStart, redEnd, red, redIndex, + lo) + if(redStart >= redEnd) { + continue + } + } + + var redCount = redEnd - redStart + var blueCount = blueEnd - blueStart -//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -exports.interleave2 = function(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; + if(full) { + if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { + retval = sweep.scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } + } else { + if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { + //If input small, then use brute force + retval = bruteForcePartial( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } else if(d * redCount * blueCount < SCAN_CUTOFF) { + //If input medium sized, then use sweep and prune + retval = sweep.scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } + } + + //First, find all red intervals whose interior contains (lo,hi) + var red0 = partitionInteriorContainsInterval( + d, axis, + redStart, redEnd, red, redIndex, + lo, hi) - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; + //Lower dimensional case + if(redStart < red0) { - return x | (y << 1); -} + if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { + //Special case for small inputs: use brute force + retval = bruteForceFull( + d, axis+1, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } else if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blueStart, blueEnd, blue, blueIndex, + redStart, red0, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + } + if(retval !== void 0) { + return retval + } + } else { + iterPush(top++, + axis+1, + redStart, red0, + blueStart, blueEnd, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blueStart, blueEnd, + redStart, red0, + flip^1, + -Infinity, Infinity) + } + } -//Extracts the nth interleaved component -exports.deinterleave2 = function(v, n) { - v = (v >>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; -} + //Divide and conquer phase + if(red0 < redEnd) { + //Cut blue into 3 parts: + // + // Points < mid point + // Points = mid point + // Points > mid point + // + var blue0 = findMedian( + d, axis, + blueStart, blueEnd, blue, blueIndex) + var mid = blue[elemSize * blue0 + axis] + var blue1 = partitionStartEqual( + d, axis, + blue0, blueEnd, blue, blueIndex, + mid) -//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -exports.interleave3 = function(x, y, z) { - x &= 0x3FF; - x = (x | (x<<16)) & 4278190335; - x = (x | (x<<8)) & 251719695; - x = (x | (x<<4)) & 3272356035; - x = (x | (x<<2)) & 1227133513; + //Right case + if(blue1 < blueEnd) { + iterPush(top++, + axis, + red0, redEnd, + blue1, blueEnd, + (flip|4) + (full ? 16 : 0), + mid, hi) + } - y &= 0x3FF; - y = (y | (y<<16)) & 4278190335; - y = (y | (y<<8)) & 251719695; - y = (y | (y<<4)) & 3272356035; - y = (y | (y<<2)) & 1227133513; - x |= (y << 1); - - z &= 0x3FF; - z = (z | (z<<16)) & 4278190335; - z = (z | (z<<8)) & 251719695; - z = (z | (z<<4)) & 3272356035; - z = (z | (z<<2)) & 1227133513; - - return x | (z << 2); -} + //Left case + if(blueStart < blue0) { + iterPush(top++, + axis, + red0, redEnd, + blueStart, blue0, + (flip|2) + (full ? 16 : 0), + lo, mid) + } -//Extracts nth interleaved component of a 3-tuple -exports.deinterleave3 = function(v, n) { - v = (v >>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; -} + //Center case (the hard part) + if(blue0 + 1 === blue1) { + //Optimization: Range with exactly 1 point, use a brute force scan + if(full) { + retval = onePointFull( + d, axis, visit, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) + } else { + retval = onePointPartial( + d, axis, visit, flip, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) + } + if(retval !== void 0) { + return retval + } + } else if(blue0 < blue1) { + var red1 + if(full) { + //If full intersection, need to handle special case + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + if(red0 < red1) { + var redX = partitionStartEqual( + d, axis, + red0, red1, red, redIndex, + mid) + if(axis === d-2) { + //Degenerate sweep intersection: + // [red0, redX] with [blue0, blue1] + if(red0 < redX) { + retval = sweep.sweepComplete( + d, visit, + red0, redX, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -exports.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); + //Normal sweep intersection: + // [redX, red1] with [blue0, blue1] + if(redX < red1) { + retval = sweep.sweepBipartite( + d, visit, + redX, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } + } else { + if(red0 < redX) { + iterPush(top++, + axis+1, + red0, redX, + blue0, blue1, + 16, + -Infinity, Infinity) + } + if(redX < red1) { + iterPush(top++, + axis+1, + redX, red1, + blue0, blue1, + 0, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + redX, red1, + 1, + -Infinity, Infinity) + } + } + } + } else { + if(flip) { + red1 = partitionContainsPointProper( + d, axis, + red0, redEnd, red, redIndex, + mid) + } else { + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + } + if(red0 < red1) { + if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blue0, blue1, blue, blueIndex, + red0, red1, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + red0, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + } + } else { + iterPush(top++, + axis+1, + red0, red1, + blue0, blue1, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + red0, red1, + flip^1, + -Infinity, Infinity) + } + } + } + } + } + } } - - -},{}],30:[function(_dereq_,module,exports){ +},{"./brute":123,"./median":125,"./partition":126,"./sweep":128,"bit-twiddle":129,"typedarray-pool":131}],125:[function(_dereq_,module,exports){ 'use strict' -module.exports = boxIntersectWrapper +module.exports = findMedian -var pool = _dereq_('typedarray-pool') -var sweep = _dereq_('./lib/sweep') -var boxIntersectIter = _dereq_('./lib/intersect') +var genPartition = _dereq_('./partition') -function boxEmpty(d, box) { - for(var j=0; jstart && boxes[ptr+axis] > x; + --j, ptr-=elemSize) { + //Swap + var aPtr = ptr + var bPtr = ptr+elemSize + for(var k=0; k>>1 - if(d <= 0) { - return +//Find median using quick select algorithm +// takes O(n) time with high probability +function findMedian(d, axis, start, end, boxes, ids) { + if(end <= start+1) { + return start } - var retval - - //Convert red boxes - var redList = pool.mallocDouble(2*d*n) - var redIds = pool.mallocInt32(n) - n = convertBoxes(red, d, redList, redIds) - - if(n > 0) { - if(d === 1 && full) { - //Special case: 1d complete - sweep.init(n) - retval = sweep.sweepComplete( - d, visit, - 0, n, redList, redIds, - 0, n, redList, redIds) + var lo = start + var hi = end + var mid = ((end + start) >>> 1) + var elemSize = 2*d + var pivot = mid + var value = boxes[elemSize*mid+axis] + + while(lo < hi) { + if(hi - lo < PARTITION_THRESHOLD) { + insertionSort(d, axis, lo, hi, boxes, ids) + value = boxes[elemSize*mid+axis] + break + } + + //Select pivot using median-of-3 + var count = hi - lo + var pivot0 = (Math.random()*count+lo)|0 + var value0 = boxes[elemSize*pivot0 + axis] + var pivot1 = (Math.random()*count+lo)|0 + var value1 = boxes[elemSize*pivot1 + axis] + var pivot2 = (Math.random()*count+lo)|0 + var value2 = boxes[elemSize*pivot2 + axis] + if(value0 <= value1) { + if(value2 >= value1) { + pivot = pivot1 + value = value1 + } else if(value0 >= value2) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } } else { + if(value1 >= value2) { + pivot = pivot1 + value = value1 + } else if(value2 >= value0) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } + } - //Convert blue boxes - var blueList = pool.mallocDouble(2*d*m) - var blueIds = pool.mallocInt32(m) - m = convertBoxes(blue, d, blueList, blueIds) + //Swap pivot to end of array + var aPtr = elemSize * (hi-1) + var bPtr = elemSize * pivot + for(var i=0; i 0) { - sweep.init(n+m) + //Partition using pivot + pivot = partitionStartLessThan( + d, axis, + lo, hi-1, boxes, ids, + value) - if(d === 1) { - //Special case: 1d bipartite - retval = sweep.sweepBipartite( - d, visit, - 0, n, redList, redIds, - 0, m, blueList, blueIds) - } else { - //General case: d>1 - retval = boxIntersectIter( - d, visit, full, - n, redList, redIds, - m, blueList, blueIds) - } + //Swap pivot back + var aPtr = elemSize * (hi-1) + var bPtr = elemSize * pivot + for(var i=0; i= 0) { + reads.push('lo=e[k+n]') + } + if(predicate.indexOf('hi') >= 0) { + reads.push('hi=e[k+o]') } + fargs.push( + code.replace('_', reads.join()) + .replace('$', predicate)) + return Function.apply(void 0, fargs) } -},{"./lib/intersect":32,"./lib/sweep":36,"typedarray-pool":191}],31:[function(_dereq_,module,exports){ -'use strict' +},{}],127:[function(_dereq_,module,exports){ +'use strict'; -var DIMENSION = 'd' -var AXIS = 'ax' -var VISIT = 'vv' -var FLIP = 'fp' +//This code is extracted from ndarray-sort +//It is inlined here as a temporary workaround -var ELEM_SIZE = 'es' +module.exports = wrapper; -var RED_START = 'rs' -var RED_END = 're' -var RED_BOXES = 'rb' -var RED_INDEX = 'ri' -var RED_PTR = 'rp' +var INSERT_SORT_CUTOFF = 32 -var BLUE_START = 'bs' -var BLUE_END = 'be' -var BLUE_BOXES = 'bb' -var BLUE_INDEX = 'bi' -var BLUE_PTR = 'bp' +function wrapper(data, n0) { + if (n0 <= 4*INSERT_SORT_CUTOFF) { + insertionSort(0, n0 - 1, data); + } else { + quickSort(0, n0 - 1, data); + } +} -var RETVAL = 'rv' +function insertionSort(left, right, data) { + var ptr = 2*(left+1) + for(var i=left+1; i<=right; ++i) { + var a = data[ptr++] + var b = data[ptr++] + var j = i + var jptr = ptr-2 + while(j-- > left) { + var x = data[jptr-2] + var y = data[jptr-1] + if(x < a) { + break + } else if(x === a && y < b) { + break + } + data[jptr] = x + data[jptr+1] = y + jptr -= 2 + } + data[jptr] = a + data[jptr+1] = b + } +} -var INNER_LABEL = 'Q' +function swap(i, j, data) { + i *= 2 + j *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = x + data[j+1] = y +} -var ARGS = [ - DIMENSION, - AXIS, - VISIT, - RED_START, - RED_END, - RED_BOXES, - RED_INDEX, - BLUE_START, - BLUE_END, - BLUE_BOXES, - BLUE_INDEX -] +function move(i, j, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[i+1] = data[j+1] +} -function generateBruteForce(redMajor, flip, full) { - var funcName = 'bruteForce' + - (redMajor ? 'Red' : 'Blue') + - (flip ? 'Flip' : '') + - (full ? 'Full' : '') +function rotate(i, j, k, data) { + i *= 2 + j *= 2 + k *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = data[k] + data[j+1] = data[k+1] + data[k] = x + data[k+1] = y +} - var code = ['function ', funcName, '(', ARGS.join(), '){', - 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] +function shufflePivot(i, j, px, py, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[j] = px + data[i+1] = data[j+1] + data[j+1] = py +} - var redLoop = - 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + - 'i<' + RED_END +';' + - '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + - 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + - 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + - 'xi=' + RED_INDEX + '[i];' +function compare(i, j, data) { + i *= 2 + j *= 2 + var x = data[i], + y = data[j] + if(x < y) { + return false + } else if(x === y) { + return data[i+1] > data[j+1] + } + return true +} - var blueLoop = - 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + - 'j<' + BLUE_END + ';' + - '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + - 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + - (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + - 'yi=' + BLUE_INDEX + '[j];' +function comparePivot(i, y, b, data) { + i *= 2 + var x = data[i] + if(x < y) { + return true + } else if(x === y) { + return data[i+1] < b + } + return false +} - if(redMajor) { - code.push(redLoop, INNER_LABEL, ':', blueLoop) - } else { - code.push(blueLoop, INNER_LABEL, ':', redLoop) +function quickSort(left, right, data) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, + tmp = 0 + if(compare(el1, el2, data)) { + tmp = el1 + el1 = el2 + el2 = tmp + } + if(compare(el4, el5, data)) { + tmp = el4 + el4 = el5 + el5 = tmp + } + if(compare(el1, el3, data)) { + tmp = el1 + el1 = el3 + el3 = tmp + } + if(compare(el2, el3, data)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el1, el4, data)) { + tmp = el1 + el1 = el4 + el4 = tmp + } + if(compare(el3, el4, data)) { + tmp = el3 + el3 = el4 + el4 = tmp + } + if(compare(el2, el5, data)) { + tmp = el2 + el2 = el5 + el5 = tmp + } + if(compare(el2, el3, data)) { + tmp = el2 + el2 = el3 + el3 = tmp } - - if(full) { - code.push('if(y1' + - BLUE_END + '-' + BLUE_START + '){') - - if(full) { - invoke(true, false) - code.push('}else{') - invoke(false, false) + if (great - less <= INSERT_SORT_CUTOFF) { + insertionSort(less, great, data); } else { - code.push('if(' + FLIP + '){') - invoke(true, true) - code.push('}else{') - invoke(true, false) - code.push('}}else{if(' + FLIP + '){') - invoke(false, true) - code.push('}else{') - invoke(false, false) - code.push('}') + quickSort(less, great, data); } - code.push('}}return ' + funcName) - - var codeStr = prefix.join('') + code.join('') - var proc = new Function(codeStr) - return proc() } - - -exports.partial = bruteForcePlanner(false) -exports.full = bruteForcePlanner(true) -},{}],32:[function(_dereq_,module,exports){ +},{}],128:[function(_dereq_,module,exports){ 'use strict' -module.exports = boxIntersectIter - -var pool = _dereq_('typedarray-pool') -var bits = _dereq_('bit-twiddle') -var bruteForce = _dereq_('./brute') -var bruteForcePartial = bruteForce.partial -var bruteForceFull = bruteForce.full -var sweep = _dereq_('./sweep') -var findMedian = _dereq_('./median') -var genPartition = _dereq_('./partition') - -//Twiddle parameters -var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search -var SCAN_CUTOFF = (1<<22) //Cut off for two way scan -var SCAN_COMPLETE_CUTOFF = (1<<22) - -//Partition functions -var partitionInteriorContainsInterval = genPartition( - '!(lo>=p0)&&!(p1>=hi)', - ['p0', 'p1']) - -var partitionStartEqual = genPartition( - 'lo===p0', - ['p0']) - -var partitionStartLessThan = genPartition( - 'loright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + for(var i=0; i= BLUE_FLAG) { + //blue destroy event + e = (e-BLUE_FLAG)|0 + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) + } else if(e >= 0) { + //red destroy event + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) + } else if(e <= -BLUE_FLAG) { + //blue create event + e = (-e-BLUE_FLAG)|0 + for(var j=0; j 0) { - top -= 1 - - var iptr = top * IFRAME_SIZE - var axis = BOX_ISTACK[iptr] - var redStart = BOX_ISTACK[iptr+1] - var redEnd = BOX_ISTACK[iptr+2] - var blueStart = BOX_ISTACK[iptr+3] - var blueEnd = BOX_ISTACK[iptr+4] - var state = BOX_ISTACK[iptr+5] - - var dptr = top * DFRAME_SIZE - var lo = BOX_DSTACK[dptr] - var hi = BOX_DSTACK[dptr+1] - - //Unpack state info - var flip = (state & 1) - var full = !!(state & 16) - - //Unpack indices - var red = xBoxes - var redIndex = xIndex - var blue = yBoxes - var blueIndex = yIndex - if(flip) { - red = yBoxes - redIndex = yIndex - blue = xBoxes - blueIndex = xIndex - } + for(var i=blueStart; i= redEnd) { - continue - } - } - if(state & 4) { - redStart = partitionEndLessThanEqual( - d, axis, - redStart, redEnd, red, redIndex, - lo) - if(redStart >= redEnd) { - continue - } + //process events from left->right + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + var commonActive = 0 + for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { + color = 2 + i += 1 } - var redCount = redEnd - redStart - var blueCount = blueEnd - blueStart + if(e < 0) { + //Create event + var id = -(e>>1) - 1 - if(full) { - if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { - retval = sweep.scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) + //Intersect with common + for(var j=0; j>1) - 1 + if(color === 0) { + //Red + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) + } else if(color === 1) { + //Blue + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) + } else if(color === 2) { + //Both + sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) } } + } +} - //Divide and conquer phase - if(red0 < redEnd) { +//Sweep and prune/scanline algorithm: +// Scan along axis, detect intersections +// Brute force all boxes along axis +function scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = axis + var iend = axis+d - //Cut blue into 3 parts: - // - // Points < mid point - // Points = mid point - // Points > mid point - // - var blue0 = findMedian( - d, axis, - blueStart, blueEnd, blue, blueIndex) - var mid = blue[elemSize * blue0 + axis] - var blue1 = partitionStartEqual( - d, axis, - blue0, blueEnd, blue, blueIndex, - mid) + var redShift = 1 + var blueShift = 1 + if(flip) { + blueShift = BLUE_FLAG + } else { + redShift = BLUE_FLAG + } - //Right case - if(blue1 < blueEnd) { - iterPush(top++, - axis, - red0, redEnd, - blue1, blueEnd, - (flip|4) + (full ? 16 : 0), - mid, hi) - } + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + isRed = !flip + idx -= BLUE_FLAG + } else { + isRed = !!flip + idx -= 1 } + if(isRed) { + sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) + } else { + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] - //Center case (the hard part) - if(blue0 + 1 === blue1) { - //Optimization: Range with exactly 1 point, use a brute force scan - if(full) { - retval = onePointFull( - d, axis, visit, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) - } else { - retval = onePointPartial( - d, axis, visit, flip, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) - } - if(retval !== void 0) { - return retval - } - } else if(blue0 < blue1) { - var red1 - if(full) { - //If full intersection, need to handle special case - red1 = partitionContainsPoint( - d, axis, - red0, redEnd, red, redIndex, - mid) - if(red0 < red1) { - var redX = partitionStartEqual( - d, axis, - red0, red1, red, redIndex, - mid) - if(axis === d-2) { - //Degenerate sweep intersection: - // [red0, redX] with [blue0, blue1] - if(red0 < redX) { - retval = sweep.sweepComplete( - d, visit, - red0, redX, red, redIndex, - blue0, blue1, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } +red_loop: + for(var j=0; jstart && boxes[ptr+axis] > x; - --j, ptr-=elemSize) { - //Swap - var aPtr = ptr - var bPtr = ptr+elemSize - for(var k=0; k>> 1) - var elemSize = 2*d - var pivot = mid - var value = boxes[elemSize*mid+axis] + //process events from left->right + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) - while(lo < hi) { - if(hi - lo < PARTITION_THRESHOLD) { - insertionSort(d, axis, lo, hi, boxes, ids) - value = boxes[elemSize*mid+axis] - break - } - - //Select pivot using median-of-3 - var count = hi - lo - var pivot0 = (Math.random()*count+lo)|0 - var value0 = boxes[elemSize*pivot0 + axis] - var pivot1 = (Math.random()*count+lo)|0 - var value1 = boxes[elemSize*pivot1 + axis] - var pivot2 = (Math.random()*count+lo)|0 - var value2 = boxes[elemSize*pivot2 + axis] - if(value0 <= value1) { - if(value2 >= value1) { - pivot = pivot1 - value = value1 - } else if(value0 >= value2) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } - } else { - if(value1 >= value2) { - pivot = pivot1 - value = value1 - } else if(value2 >= value0) { - pivot = pivot0 - value = value0 + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG } else { - pivot = pivot2 - value = value2 - } - } + idx -= 1 + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx - //Swap pivot to end of array - var aPtr = elemSize * (hi-1) - var bPtr = elemSize * pivot - for(var i=0; i=0; --j) { + if(RED_SWEEP_QUEUE[j] === idx) { + for(var k=j+1; k= 0) { - reads.push('lo=e[k+n]') - } - if(predicate.indexOf('hi') >= 0) { - reads.push('hi=e[k+o]') - } - fargs.push( - code.replace('_', reads.join()) - .replace('$', predicate)) - return Function.apply(void 0, fargs) -} -},{}],35:[function(_dereq_,module,exports){ -'use strict'; +"use strict"; "use restrict"; -//This code is extracted from ndarray-sort -//It is inlined here as a temporary workaround +//Number of bits in an integer +var INT_BITS = 32; -module.exports = wrapper; +//Constants +exports.INT_BITS = INT_BITS; +exports.INT_MAX = 0x7fffffff; +exports.INT_MIN = -1<<(INT_BITS-1); -var INSERT_SORT_CUTOFF = 32 +//Returns -1, 0, +1 depending on sign of x +exports.sign = function(v) { + return (v > 0) - (v < 0); +} -function wrapper(data, n0) { - if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data); - } else { - quickSort(0, n0 - 1, data); - } +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; } -function insertionSort(left, right, data) { - var ptr = 2*(left+1) - for(var i=left+1; i<=right; ++i) { - var a = data[ptr++] - var b = data[ptr++] - var j = i - var jptr = ptr-2 - while(j-- > left) { - var x = data[jptr-2] - var y = data[jptr-1] - if(x < a) { - break - } else if(x === a && y < b) { - break - } - data[jptr] = x - data[jptr+1] = y - jptr -= 2 - } - data[jptr] = a - data[jptr+1] = b - } +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); } -function swap(i, j, data) { - i *= 2 - j *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = x - data[j+1] = y +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); } -function move(i, j, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[i+1] = data[j+1] +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); } -function rotate(i, j, k, data) { - i *= 2 - j *= 2 - k *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = data[k] - data[j+1] = data[k+1] - data[k] = x - data[k+1] = y +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); } -function shufflePivot(i, j, px, py, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[j] = px - data[i+1] = data[j+1] - data[j+1] = py +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } -function compare(i, j, data) { - i *= 2 - j *= 2 - var x = data[i], - y = data[j] - if(x < y) { - return false - } else if(x === y) { - return data[i+1] > data[j+1] - } - return true +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; } -function comparePivot(i, y, b, data) { - i *= 2 - var x = data[i] - if(x < y) { - return true - } else if(x === y) { - return data[i+1] < b - } - return false +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; } +exports.countTrailingZeros = countTrailingZeros; -function quickSort(left, right, data) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, - tmp = 0 - if(compare(el1, el2, data)) { - tmp = el1 - el1 = el2 - el2 = tmp - } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - if(compare(el1, el3, data)) { - tmp = el1 - el1 = el3 - el3 = tmp - } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(compare(el1, el4, data)) { - tmp = el1 - el1 = el4 - el4 = tmp - } - if(compare(el3, el4, data)) { - tmp = el3 - el3 = el4 - el4 = tmp - } - if(compare(el2, el5, data)) { - tmp = el2 - el2 = el5 - el5 = tmp - } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp - } +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} - var pivot1X = data[2*el2] - var pivot1Y = data[2*el2+1] - var pivot2X = data[2*el4] - var pivot2Y = data[2*el4+1] +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} - var ptr0 = 2 * el1; - var ptr2 = 2 * el3; - var ptr4 = 2 * el5; - var ptr5 = 2 * index1; - var ptr6 = 2 * index3; - var ptr7 = 2 * index5; - for (var i1 = 0; i1 < 2; ++i1) { - var x = data[ptr0+i1]; - var y = data[ptr2+i1]; - var z = data[ptr4+i1]; - data[ptr5+i1] = x; - data[ptr6+i1] = y; - data[ptr7+i1] = z; - } +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} - move(index2, left, data) - move(index4, right, data) - for (var k = less; k <= great; ++k) { - if (comparePivot(k, pivot1X, pivot1Y, data)) { - if (k !== less) { - swap(k, less, data) - } - ++less; - } else { - if (!comparePivot(k, pivot2X, pivot2Y, data)) { - while (true) { - if (!comparePivot(great, pivot2X, pivot2Y, data)) { - if (--great < k) { - break; - } - continue; - } else { - if (comparePivot(great, pivot1X, pivot1Y, data)) { - rotate(k, less, great, data) - ++less; - --great; - } else { - swap(k, great, data) - --great; - } - break; - } - } - } +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; } + tab[i] = (r << s) & 0xff; } - shufflePivot(left, less-1, pivot1X, pivot1Y, data) - shufflePivot(right, great+1, pivot2X, pivot2Y, data) - if (less - 2 - left <= INSERT_SORT_CUTOFF) { - insertionSort(left, less - 2, data); - } else { - quickSort(left, less - 2, data); - } - if (right - (great + 2) <= INSERT_SORT_CUTOFF) { - insertionSort(great + 2, right, data); - } else { - quickSort(great + 2, right, data); - } - if (great - less <= INSERT_SORT_CUTOFF) { - insertionSort(less, great, data); - } else { - quickSort(less, great, data); - } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; } -},{}],36:[function(_dereq_,module,exports){ -'use strict' -module.exports = { - init: sqInit, - sweepBipartite: sweepBipartite, - sweepComplete: sweepComplete, - scanBipartite: scanBipartite, - scanComplete: scanComplete +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); } -var pool = _dereq_('typedarray-pool') -var bits = _dereq_('bit-twiddle') -var isort = _dereq_('./sort') +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} -//Flag for blue -var BLUE_FLAG = (1<<28) -//1D sweep event queue stuff (use pool to save space) -var INIT_CAPACITY = 1024 -var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; -//Reserves memory for the 1D sweep data structures -function sqInit(count) { - var rcount = bits.nextPow2(count) - if(RED_SWEEP_QUEUE.length < rcount) { - pool.free(RED_SWEEP_QUEUE) - RED_SWEEP_QUEUE = pool.mallocInt32(rcount) - } - if(RED_SWEEP_INDEX.length < rcount) { - pool.free(RED_SWEEP_INDEX) - RED_SWEEP_INDEX = pool.mallocInt32(rcount) - } - if(BLUE_SWEEP_QUEUE.length < rcount) { - pool.free(BLUE_SWEEP_QUEUE) - BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) - } - if(BLUE_SWEEP_INDEX.length < rcount) { - pool.free(BLUE_SWEEP_INDEX) - BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) - } - if(COMMON_SWEEP_QUEUE.length < rcount) { - pool.free(COMMON_SWEEP_QUEUE) - COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) - } - if(COMMON_SWEEP_INDEX.length < rcount) { - pool.free(COMMON_SWEEP_INDEX) - COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) - } - var eventLength = 8 * rcount - if(SWEEP_EVENTS.length < eventLength) { - pool.free(SWEEP_EVENTS) - SWEEP_EVENTS = pool.mallocDouble(eventLength) - } + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); } -//Remove an item from the active queue in O(1) -function sqPop(queue, index, count, item) { - var idx = index[item] - var top = queue[count-1] - queue[idx] = top - index[top] = idx +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; } -//Insert an item into the active queue in O(1) -function sqPush(queue, index, count, item) { - queue[count] = item - index[item] = count +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } -//Recursion base case: use 1D sweep algorithm -function sweepBipartite( - d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - //store events as pairs [coordinate, idx] - // - // red create: -(idx+1) - // red destroy: idx - // blue create: -(idx+BLUE_FLAG) - // blue destroy: idx+BLUE_FLAG - // - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 +},{}],130:[function(_dereq_,module,exports){ +"use strict" - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - for(var i=0; i= BLUE_FLAG) { - //blue destroy event - e = (e-BLUE_FLAG)|0 - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) - } else if(e >= 0) { - //red destroy event - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) - } else if(e <= -BLUE_FLAG) { - //blue create event - e = (-e-BLUE_FLAG)|0 - for(var j=0; j 0) { + return dupe_number(count|0, value) } - sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, e) - } else { - //red create event - e = (-e-1)|0 - for(var j=0; jright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - var commonActive = 0 - for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { - color = 2 - i += 1 +//Upgrade pool +if(!POOL.UINT8C) { + POOL.UINT8C = dup([32, 0]) +} +if(!POOL.BUFFER) { + POOL.BUFFER = dup([32, 0]) +} + +//New technique: Only allocate from ArrayBufferView and Buffer +var DATA = POOL.DATA + , BUFFER = POOL.BUFFER + +exports.free = function free(array) { + if(Buffer.isBuffer(array)) { + BUFFER[bits.log2(array.length)].push(array) + } else { + if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { + array = array.buffer } - - if(e < 0) { - //Create event - var id = -(e>>1) - 1 + if(!array) { + return + } + var n = array.length || array.byteLength + var log_n = bits.log2(n)|0 + DATA[log_n].push(array) + } +} - //Intersect with common - for(var j=0; j>1) - 1 - if(color === 0) { - //Red - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) - } else if(color === 1) { - //Blue - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) - } else if(color === 2) { - //Both - sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) - } +exports.freeArrayBuffer = freeArrayBuffer + +exports.freeBuffer = function freeBuffer(array) { + BUFFER[bits.log2(array.length)].push(array) +} + +exports.malloc = function malloc(n, dtype) { + if(dtype === undefined || dtype === 'arraybuffer') { + return mallocArrayBuffer(n) + } else { + switch(dtype) { + case 'uint8': + return mallocUint8(n) + case 'uint16': + return mallocUint16(n) + case 'uint32': + return mallocUint32(n) + case 'int8': + return mallocInt8(n) + case 'int16': + return mallocInt16(n) + case 'int32': + return mallocInt32(n) + case 'float': + case 'float32': + return mallocFloat(n) + case 'double': + case 'float64': + return mallocDouble(n) + case 'uint8_clamped': + return mallocUint8Clamped(n) + case 'buffer': + return mallocBuffer(n) + case 'data': + case 'dataview': + return mallocDataView(n) + + default: + return null } } + return null } -//Sweep and prune/scanline algorithm: -// Scan along axis, detect intersections -// Brute force all boxes along axis -function scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d - - var redShift = 1 - var blueShift = 1 - if(flip) { - blueShift = BLUE_FLAG - } else { - redShift = BLUE_FLAG +function mallocArrayBuffer(n) { + var n = bits.nextPow2(n) + var log_n = bits.log2(n) + var d = DATA[log_n] + if(d.length > 0) { + return d.pop() } + return new ArrayBuffer(n) +} +exports.mallocArrayBuffer = mallocArrayBuffer - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - isRed = !flip - idx -= BLUE_FLAG - } else { - isRed = !!flip - idx -= 1 - } - if(isRed) { - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) - } else { - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocUint16 = mallocUint16 -red_loop: - for(var j=0; jright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG - } else { - idx -= 1 - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] - -red_loop: - for(var j=0; j=0; --j) { - if(RED_SWEEP_QUEUE[j] === idx) { - for(var k=j+1; k 0) { + return cache.pop() } + return new Buffer(n) } -},{"./sort":35,"bit-twiddle":29,"typedarray-pool":191}],37:[function(_dereq_,module,exports){ +exports.mallocBuffer = mallocBuffer -},{}],38:[function(_dereq_,module,exports){ +exports.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer) +},{"bit-twiddle":129,"buffer":133,"dup":130}],132:[function(_dereq_,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"dup":112}],133:[function(_dereq_,module,exports){ +(function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ +/* eslint-disable no-proto */ + +'use strict' var base64 = _dereq_('base64-js') var ieee754 = _dereq_('ieee754') -var isArray = _dereq_('is-array') +var isArray = _dereq_('isarray') exports.Buffer = Buffer -exports.SlowBuffer = Buffer +exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation -var kMaxLength = 0x3fffffff +var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -2859,32 +4777,49 @@ var kMaxLength = 0x3fffffff * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * * Note: * - * - Implementation must support adding new properties to `Uint8Array` instances. - * Firefox 4-29 lacked support, fixed in Firefox 30+. - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property + * on objects. * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will - * get the Object implementation, which is slower but will work correctly. + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. */ -Buffer.TYPED_ARRAY_SUPPORT = (function () { +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +function typedArraySupport () { + function Bar () {} try { - var buf = new ArrayBuffer(0) - var arr = new Uint8Array(buf) + var arr = new Uint8Array(1) arr.foo = function () { return 42 } - return 42 === arr.foo() && // typed array instances can be augmented + arr.constructor = Bar + return arr.foo() === 42 && // typed array instances can be augmented + arr.constructor === Bar && // constructor can be set typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } -})() +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} /** * Class: Buffer @@ -2898,2766 +4833,1784 @@ Buffer.TYPED_ARRAY_SUPPORT = (function () { * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ -function Buffer (subject, encoding, noZero) { - if (!(this instanceof Buffer)) - return new Buffer(subject, encoding, noZero) - - var type = typeof subject - - // Find the length - var length - if (type === 'number') - length = subject > 0 ? subject >>> 0 : 0 - else if (type === 'string') { - if (encoding === 'base64') - subject = base64clean(subject) - length = Buffer.byteLength(subject, encoding) - } else if (type === 'object' && subject !== null) { // assume object is array-like - if (subject.type === 'Buffer' && isArray(subject.data)) - subject = subject.data - length = +subject.length > 0 ? Math.floor(+subject.length) : 0 - } else - throw new TypeError('must start with number, buffer, array or string') - - if (this.length > kMaxLength) - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength.toString(16) + ' bytes') - - var buf - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Preferred: Return an augmented `Uint8Array` instance for best performance - buf = Buffer._augment(new Uint8Array(length)) - } else { - // Fallback: Return THIS instance of Buffer (created by `new`) - buf = this - buf.length = length - buf._isBuffer = true - } - - var i - if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { - // Speed optimization -- use set if we're copying from a typed array - buf._set(subject) - } else if (isArrayish(subject)) { - // Treat array-ish objects as a byte array - if (Buffer.isBuffer(subject)) { - for (i = 0; i < length; i++) - buf[i] = subject.readUInt8(i) - } else { - for (i = 0; i < length; i++) - buf[i] = ((subject[i] % 256) + 256) % 256 - } - } else if (type === 'string') { - buf.write(subject, 0, encoding) - } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { - for (i = 0; i < length; i++) { - buf[i] = 0 - } - } - - return buf -} - -Buffer.isBuffer = function (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) - throw new TypeError('Arguments must be Buffers') - - var x = a.length - var y = b.length - for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} - if (i !== len) { - x = a[i] - y = b[i] - } - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'raw': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function (list, totalLength) { - if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') - - if (list.length === 0) { - return new Buffer(0) - } else if (list.length === 1) { - return list[0] - } - - var i - if (totalLength === undefined) { - totalLength = 0 - for (i = 0; i < list.length; i++) { - totalLength += list[i].length - } - } - - var buf = new Buffer(totalLength) - var pos = 0 - for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length - } - return buf -} - -Buffer.byteLength = function (str, encoding) { - var ret - str = str + '' - switch (encoding || 'utf8') { - case 'ascii': - case 'binary': - case 'raw': - ret = str.length - break - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - ret = str.length * 2 - break - case 'hex': - ret = str.length >>> 1 - break - case 'utf8': - case 'utf-8': - ret = utf8ToBytes(str).length - break - case 'base64': - ret = base64ToBytes(str).length - break - default: - ret = str.length - } - return ret -} - -// pre-set for values that may exist in the future -Buffer.prototype.length = undefined -Buffer.prototype.parent = undefined - -// toString(encoding, start=0, end=buffer.length) -Buffer.prototype.toString = function (encoding, start, end) { - var loweredCase = false - - start = start >>> 0 - end = end === undefined || end === Infinity ? this.length : end >>> 0 - - if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'binary': - return binarySlice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) - throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.equals = function (b) { - if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) - str += ' ... ' - } - return '' -} - -Buffer.prototype.compare = function (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - return Buffer.compare(this, b) -} - -// `get` will be removed in Node 0.13+ -Buffer.prototype.get = function (offset) { - console.log('.get() is deprecated. Access using array indexes instead.') - return this.readUInt8(offset) -} - -// `set` will be removed in Node 0.13+ -Buffer.prototype.set = function (v, offset) { - console.log('.set() is deprecated. Access using array indexes instead.') - return this.writeUInt8(v, offset) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var byte = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(byte)) throw new Error('Invalid hex string') - buf[offset + i] = byte - } - return i -} - -function utf8Write (buf, string, offset, length) { - var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) - return charsWritten -} - -function asciiWrite (buf, string, offset, length) { - var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) - return charsWritten -} - -function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) - return charsWritten -} - -function utf16leWrite (buf, string, offset, length) { - var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length, 2) - return charsWritten -} - -Buffer.prototype.write = function (string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length - length = undefined - } - } else { // legacy - var swap = encoding - encoding = offset - offset = length - length = swap - } - - offset = Number(offset) || 0 - var remaining = this.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - encoding = String(encoding || 'utf8').toLowerCase() - - var ret - switch (encoding) { - case 'hex': - ret = hexWrite(this, string, offset, length) - break - case 'utf8': - case 'utf-8': - ret = utf8Write(this, string, offset, length) - break - case 'ascii': - ret = asciiWrite(this, string, offset, length) - break - case 'binary': - ret = binaryWrite(this, string, offset, length) - break - case 'base64': - ret = base64Write(this, string, offset, length) - break - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - ret = utf16leWrite(this, string, offset, length) - break - default: - throw new TypeError('Unknown encoding: ' + encoding) +function Buffer (arg) { + if (!(this instanceof Buffer)) { + // Avoid going through an ArgumentsAdaptorTrampoline in the common case. + if (arguments.length > 1) return new Buffer(arg, arguments[1]) + return new Buffer(arg) } - return ret -} -Buffer.prototype.toJSON = function () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + this.length = 0 + this.parent = undefined } -} -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) + // Common case. + if (typeof arg === 'number') { + return fromNumber(this, arg) } -} - -function utf8Slice (buf, start, end) { - var res = '' - var tmp = '' - end = Math.min(buf.length, end) - for (var i = start; i < end; i++) { - if (buf[i] <= 0x7F) { - res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) - tmp = '' - } else { - tmp += '%' + buf[i].toString(16) - } + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } - return res + decodeUtf8Char(tmp) + // Unusual. + return fromObject(this, arg) } -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) +function fromNumber (that, length) { + that = allocate(that, length < 0 ? 0 : checked(length) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < length; i++) { + that[i] = 0 + } } - return ret + return that } -function binarySlice (buf, start, end) { - return asciiSlice(buf, start, end) +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) + + that.write(string, encoding) + return that } -function hexSlice (buf, start, end) { - var len = buf.length +function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len + if (isArray(object)) return fromArray(that, object) - var out = '' - for (var i = start; i < end; i++) { - out += toHex(buf[i]) + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') } - return out -} -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + if (typeof ArrayBuffer !== 'undefined') { + if (object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) + } + if (object instanceof ArrayBuffer) { + return fromArrayBuffer(that, object) + } } - return res + + if (object.length) return fromArrayLike(that, object) + + return fromJsonObject(that, object) } -Buffer.prototype.slice = function (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end +function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that +} - if (start < 0) { - start += len; - if (start < 0) - start = 0 - } else if (start > len) { - start = len +function fromArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } + return that +} - if (end < 0) { - end += len - if (end < 0) - end = 0 - } else if (end > len) { - end = len +// Duplicate of fromArray() to keep fromArray() monomorphic. +function fromTypedArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + // Truncating the elements is probably not what people expect from typed + // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior + // of the old Buffer constructor. + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } + return that +} - if (end < start) - end = start - +function fromArrayBuffer (that, array) { if (Buffer.TYPED_ARRAY_SUPPORT) { - return Buffer._augment(this.subarray(start, end)) + // Return an augmented `Uint8Array` instance, for best performance + array.byteLength + that = Buffer._augment(new Uint8Array(array)) } else { - var sliceLen = end - start - var newBuf = new Buffer(sliceLen, undefined, true) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - return newBuf + // Fallback: Return an object instance of the Buffer class + that = fromTypedArray(that, new Uint8Array(array)) } + return that } -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) - throw new RangeError('offset is not uint') - if (offset + ext > length) - throw new RangeError('Trying to access beyond buffer length') +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that } -Buffer.prototype.readUInt8 = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 1, this.length) - return this[offset] -} +// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. +// Returns a zero-length buffer for inputs that don't conform to the spec. +function fromJsonObject (that, object) { + var array + var length = 0 -Buffer.prototype.readUInt16LE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} + if (object.type === 'Buffer' && isArray(object.data)) { + array = object.data + length = checked(array.length) | 0 + } + that = allocate(that, length) -Buffer.prototype.readUInt16BE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that } -Buffer.prototype.readUInt32LE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array +} else { + // pre-set for values that may exist in the future + Buffer.prototype.length = undefined + Buffer.prototype.parent = undefined } -Buffer.prototype.readUInt32BE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 4, this.length) +function allocate (that, length) { + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = Buffer._augment(new Uint8Array(length)) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that.length = length + that._isBuffer = true + } + + var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 + if (fromPool) that.parent = rootParent - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) + return that } -Buffer.prototype.readInt8 = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) - return (this[offset]) - return ((0xff - this[offset] + 1) * -1) +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 } -Buffer.prototype.readInt16LE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val +function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf } -Buffer.prototype.readInt16BE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) } -Buffer.prototype.readInt32LE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 4, this.length) +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} + if (a === b) return 0 -Buffer.prototype.readInt32BE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 4, this.length) + var x = a.length + var y = b.length - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} + var i = 0 + var len = Math.min(x, y) + while (i < len) { + if (a[i] !== b[i]) break -Buffer.prototype.readFloatLE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} + ++i + } -Buffer.prototype.readFloatBE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} + if (i !== len) { + x = a[i] + y = b[i] + } -Buffer.prototype.readDoubleLE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) + if (x < y) return -1 + if (y < x) return 1 + return 0 } -Buffer.prototype.readDoubleBE = function (offset, noAssert) { - if (!noAssert) - checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } } -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new TypeError('value is out of bounds') - if (offset + ext > buf.length) throw new TypeError('index out of range') -} +Buffer.concat = function concat (list, length) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') -Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = value - return offset + 1 -} + if (list.length === 0) { + return new Buffer(0) + } -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length + } } -} -Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value - this[offset + 1] = (value >>> 8) - } else objectWriteUInt16(this, value, offset, true) - return offset + 2 + var buf = new Buffer(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf } -Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = value - } else objectWriteUInt16(this, value, offset, false) - return offset + 2 -} +function byteLength (string, encoding) { + if (typeof string !== 'string') string = '' + string -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } } +Buffer.byteLength = byteLength -Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = value - } else objectWriteUInt32(this, value, offset, true) - return offset + 4 -} +function slowToString (encoding, start, end) { + var loweredCase = false -Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = value - } else objectWriteUInt32(this, value, offset, false) - return offset + 4 -} + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 -Buffer.prototype.writeInt8 = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = value - return offset + 1 -} + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' -Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value - this[offset + 1] = (value >>> 8) - } else objectWriteUInt16(this, value, offset, true) - return offset + 2 -} + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) -Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = value - } else objectWriteUInt16(this, value, offset, false) - return offset + 2 -} + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) -Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else objectWriteUInt32(this, value, offset, true) - return offset + 4 -} + case 'ascii': + return asciiSlice(this, start, end) -Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) - checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = value - } else objectWriteUInt32(this, value, offset, false) - return offset + 4 -} + case 'binary': + return binarySlice(this, start, end) -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (value > max || value < min) throw new TypeError('value is out of bounds') - if (offset + ext > buf.length) throw new TypeError('index out of range') -} + case 'base64': + return base64Slice(this, start, end) -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) -Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } } -Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) } -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 } -Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' } -Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) +Buffer.prototype.compare = function compare (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return 0 + return Buffer.compare(this, b) } -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function (target, target_start, start, end) { - var source = this - - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (!target_start) target_start = 0 - - // Copy 0 bytes; we're done - if (end === start) return - if (target.length === 0 || source.length === 0) return - - // Fatal error conditions - if (end < start) throw new TypeError('sourceEnd < sourceStart') - if (target_start < 0 || target_start >= target.length) - throw new TypeError('targetStart out of bounds') - if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds') - if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds') +Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 - // Are we oob? - if (end > this.length) - end = this.length - if (target.length - target_start < end - start) - end = target.length - target_start + start + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 - var len = end - start + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < len; i++) { - target[i + target_start] = this[i + start] + if (typeof val === 'string') { + if (val.length === 0) return -1 // special case: looking for empty string always fails + return String.prototype.indexOf.call(this, val, byteOffset) + } + if (Buffer.isBuffer(val)) { + return arrayIndexOf(this, val, byteOffset) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } - } else { - target._set(this.subarray(start, start + len), target_start) + return arrayIndexOf(this, [ val ], byteOffset) } -} -// fill(value, start=0, end=buffer.length) -Buffer.prototype.fill = function (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length + function arrayIndexOf (arr, val, byteOffset) { + var foundIndex = -1 + for (var i = 0; byteOffset + i < arr.length; i++) { + if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + } else { + foundIndex = -1 + } + } + return -1 + } - if (end < start) throw new TypeError('end < start') + throw new TypeError('val must be string, number or Buffer') +} - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return +// `get` is deprecated +Buffer.prototype.get = function get (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} - if (start < 0 || start >= this.length) throw new TypeError('start out of bounds') - if (end < 0 || end > this.length) throw new TypeError('end out of bounds') +// `set` is deprecated +Buffer.prototype.set = function set (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} - var i - if (typeof value === 'number') { - for (i = start; i < end; i++) { - this[i] = value - } +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining } else { - var bytes = utf8ToBytes(value.toString()) - var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] + length = Number(length) + if (length > remaining) { + length = remaining } } - return this -} + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') -/** - * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. - * Added in Node 0.12. Only available in browsers that support ArrayBuffer. - */ -Buffer.prototype.toArrayBuffer = function () { - if (typeof Uint8Array !== 'undefined') { - if (Buffer.TYPED_ARRAY_SUPPORT) { - return (new Buffer(this)).buffer - } else { - var buf = new Uint8Array(this.length) - for (var i = 0, len = buf.length; i < len; i += 1) { - buf[i] = this[i] - } - return buf.buffer - } - } else { - throw new TypeError('Buffer.toArrayBuffer not supported in this browser') + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) throw new Error('Invalid hex string') + buf[offset + i] = parsed } + return i } -// HELPER FUNCTIONS -// ================ - -var BP = Buffer.prototype - -/** - * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods - */ -Buffer._augment = function (arr) { - arr.constructor = Buffer - arr._isBuffer = true - - // save reference to original Uint8Array get/set methods before overwriting - arr._get = arr.get - arr._set = arr.set - - // deprecated, will be removed in node 0.13+ - arr.get = BP.get - arr.set = BP.set - - arr.write = BP.write - arr.toString = BP.toString - arr.toLocaleString = BP.toString - arr.toJSON = BP.toJSON - arr.equals = BP.equals - arr.compare = BP.compare - arr.copy = BP.copy - arr.slice = BP.slice - arr.readUInt8 = BP.readUInt8 - arr.readUInt16LE = BP.readUInt16LE - arr.readUInt16BE = BP.readUInt16BE - arr.readUInt32LE = BP.readUInt32LE - arr.readUInt32BE = BP.readUInt32BE - arr.readInt8 = BP.readInt8 - arr.readInt16LE = BP.readInt16LE - arr.readInt16BE = BP.readInt16BE - arr.readInt32LE = BP.readInt32LE - arr.readInt32BE = BP.readInt32BE - arr.readFloatLE = BP.readFloatLE - arr.readFloatBE = BP.readFloatBE - arr.readDoubleLE = BP.readDoubleLE - arr.readDoubleBE = BP.readDoubleBE - arr.writeUInt8 = BP.writeUInt8 - arr.writeUInt16LE = BP.writeUInt16LE - arr.writeUInt16BE = BP.writeUInt16BE - arr.writeUInt32LE = BP.writeUInt32LE - arr.writeUInt32BE = BP.writeUInt32BE - arr.writeInt8 = BP.writeInt8 - arr.writeInt16LE = BP.writeInt16LE - arr.writeInt16BE = BP.writeInt16BE - arr.writeInt32LE = BP.writeInt32LE - arr.writeInt32BE = BP.writeInt32BE - arr.writeFloatLE = BP.writeFloatLE - arr.writeFloatBE = BP.writeFloatBE - arr.writeDoubleLE = BP.writeDoubleLE - arr.writeDoubleBE = BP.writeDoubleBE - arr.fill = BP.fill - arr.inspect = BP.inspect - arr.toArrayBuffer = BP.toArrayBuffer - - return arr +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } -var INVALID_BASE64_RE = /[^+\/0-9A-z]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) } -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } -function isArrayish (subject) { - return isArray(subject) || Buffer.isBuffer(subject) || - subject && typeof subject === 'object' && - typeof subject.length === 'number' +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } -function utf8ToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - var b = str.charCodeAt(i) - if (b <= 0x7F) { - byteArray.push(b) +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' } else { - var start = i - if (b >= 0xD800 && b <= 0xDFFF) i++ - var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') - for (var j = 0; j < h.length; j++) { - byteArray.push(parseInt(h[j], 16)) - } + encoding = length + length = undefined } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + var swap = encoding + encoding = offset + offset = length | 0 + length = swap } - return byteArray -} -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining -function utf16leToBytes (str) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') } - return byteArray + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'binary': + return binaryWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } } -function base64ToBytes (str) { - return base64.toByteArray(str) +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } } -function blitBuffer (src, dst, offset, length, unitSize) { - if (unitSize) length -= length % unitSize; - for (var i = 0; i < length; i++) { - if ((i + offset >= dst.length) || (i >= src.length)) - break - dst[i + offset] = src[i] +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) } - return i } -function decodeUtf8Char (str) { - try { - return decodeURIComponent(str) - } catch (err) { - return String.fromCharCode(0xFFFD) // UTF 8 invalid char +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence } + + return decodeCodePointsArray(res) } -},{"base64-js":28,"ieee754":152,"is-array":153}],39:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.string.iterator'); -_dereq_('../../modules/es6.array.from'); -module.exports = _dereq_('../../modules/$.core').Array.from; -},{"../../modules/$.core":64,"../../modules/es6.array.from":116,"../../modules/es6.string.iterator":128}],40:[function(_dereq_,module,exports){ -_dereq_('../modules/web.dom.iterable'); -_dereq_('../modules/es6.string.iterator'); -module.exports = _dereq_('../modules/core.get-iterator'); -},{"../modules/core.get-iterator":114,"../modules/es6.string.iterator":128,"../modules/web.dom.iterable":132}],41:[function(_dereq_,module,exports){ -_dereq_('../modules/web.dom.iterable'); -_dereq_('../modules/es6.string.iterator'); -module.exports = _dereq_('../modules/core.is-iterable'); -},{"../modules/core.is-iterable":115,"../modules/es6.string.iterator":128,"../modules/web.dom.iterable":132}],42:[function(_dereq_,module,exports){ -_dereq_('../modules/es6.object.to-string'); -_dereq_('../modules/es6.string.iterator'); -_dereq_('../modules/web.dom.iterable'); -_dereq_('../modules/es6.map'); -_dereq_('../modules/es7.map.to-json'); -module.exports = _dereq_('../modules/$.core').Map; -},{"../modules/$.core":64,"../modules/es6.map":118,"../modules/es6.object.to-string":125,"../modules/es6.string.iterator":128,"../modules/es7.map.to-json":130,"../modules/web.dom.iterable":132}],43:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.math.log2'); -module.exports = _dereq_('../../modules/$.core').Math.log2; -},{"../../modules/$.core":64,"../../modules/es6.math.log2":119}],44:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.object.assign'); -module.exports = _dereq_('../../modules/$.core').Object.assign; -},{"../../modules/$.core":64,"../../modules/es6.object.assign":120}],45:[function(_dereq_,module,exports){ -var $ = _dereq_('../../modules/$'); -module.exports = function create(P, D){ - return $.create(P, D); -}; -},{"../../modules/$":89}],46:[function(_dereq_,module,exports){ -var $ = _dereq_('../../modules/$'); -module.exports = function defineProperties(T, D){ - return $.setDescs(T, D); -}; -},{"../../modules/$":89}],47:[function(_dereq_,module,exports){ -var $ = _dereq_('../../modules/$'); -module.exports = function defineProperty(it, key, desc){ - return $.setDesc(it, key, desc); -}; -},{"../../modules/$":89}],48:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.object.freeze'); -module.exports = _dereq_('../../modules/$.core').Object.freeze; -},{"../../modules/$.core":64,"../../modules/es6.object.freeze":121}],49:[function(_dereq_,module,exports){ -var $ = _dereq_('../../modules/$'); -_dereq_('../../modules/es6.object.get-own-property-descriptor'); -module.exports = function getOwnPropertyDescriptor(it, key){ - return $.getDesc(it, key); -}; -},{"../../modules/$":89,"../../modules/es6.object.get-own-property-descriptor":122}],50:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.object.keys'); -module.exports = _dereq_('../../modules/$.core').Object.keys; -},{"../../modules/$.core":64,"../../modules/es6.object.keys":123}],51:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.object.set-prototype-of'); -module.exports = _dereq_('../../modules/$.core').Object.setPrototypeOf; -},{"../../modules/$.core":64,"../../modules/es6.object.set-prototype-of":124}],52:[function(_dereq_,module,exports){ -_dereq_('../modules/es6.object.to-string'); -_dereq_('../modules/es6.string.iterator'); -_dereq_('../modules/web.dom.iterable'); -_dereq_('../modules/es6.promise'); -module.exports = _dereq_('../modules/$.core').Promise; -},{"../modules/$.core":64,"../modules/es6.object.to-string":125,"../modules/es6.promise":126,"../modules/es6.string.iterator":128,"../modules/web.dom.iterable":132}],53:[function(_dereq_,module,exports){ -_dereq_('../modules/es6.object.to-string'); -_dereq_('../modules/es6.string.iterator'); -_dereq_('../modules/web.dom.iterable'); -_dereq_('../modules/es6.set'); -_dereq_('../modules/es7.set.to-json'); -module.exports = _dereq_('../modules/$.core').Set; -},{"../modules/$.core":64,"../modules/es6.object.to-string":125,"../modules/es6.set":127,"../modules/es6.string.iterator":128,"../modules/es7.set.to-json":131,"../modules/web.dom.iterable":132}],54:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.symbol'); -_dereq_('../../modules/es6.object.to-string'); -module.exports = _dereq_('../../modules/$.core').Symbol; -},{"../../modules/$.core":64,"../../modules/es6.object.to-string":125,"../../modules/es6.symbol":129}],55:[function(_dereq_,module,exports){ -_dereq_('../../modules/es6.string.iterator'); -_dereq_('../../modules/web.dom.iterable'); -module.exports = _dereq_('../../modules/$.wks')('iterator'); -},{"../../modules/$.wks":112,"../../modules/es6.string.iterator":128,"../../modules/web.dom.iterable":132}],56:[function(_dereq_,module,exports){ -module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; -}; -},{}],57:[function(_dereq_,module,exports){ -module.exports = function(){ /* empty */ }; -},{}],58:[function(_dereq_,module,exports){ -var isObject = _dereq_('./$.is-object'); -module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; -}; -},{"./$.is-object":82}],59:[function(_dereq_,module,exports){ -// getting tag from 19.1.3.6 Object.prototype.toString() -var cof = _dereq_('./$.cof') - , TAG = _dereq_('./$.wks')('toStringTag') - // ES3 wrong here - , ARG = cof(function(){ return arguments; }()) == 'Arguments'; +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 -module.exports = function(it){ - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = (O = Object(it))[TAG]) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; -}; -},{"./$.cof":60,"./$.wks":112}],60:[function(_dereq_,module,exports){ -var toString = {}.toString; +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } -module.exports = function(it){ - return toString.call(it).slice(8, -1); -}; -},{}],61:[function(_dereq_,module,exports){ -'use strict'; -var $ = _dereq_('./$') - , hide = _dereq_('./$.hide') - , redefineAll = _dereq_('./$.redefine-all') - , ctx = _dereq_('./$.ctx') - , strictNew = _dereq_('./$.strict-new') - , defined = _dereq_('./$.defined') - , forOf = _dereq_('./$.for-of') - , $iterDefine = _dereq_('./$.iter-define') - , step = _dereq_('./$.iter-step') - , ID = _dereq_('./$.uid')('id') - , $has = _dereq_('./$.has') - , isObject = _dereq_('./$.is-object') - , setSpecies = _dereq_('./$.set-species') - , DESCRIPTORS = _dereq_('./$.descriptors') - , isExtensible = Object.isExtensible || isObject - , SIZE = DESCRIPTORS ? '_s' : 'size' - , id = 0; + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} -var fastKey = function(it, create){ - // return primitive with prefix - if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if(!$has(it, ID)){ - // can't set id to frozen object - if(!isExtensible(it))return 'F'; - // not necessary to add id - if(!create)return 'E'; - // add missing object id - hide(it, ID, ++id); - // return object id with prefix - } return 'O' + it[ID]; -}; +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) -var getEntry = function(that, key){ - // fast case - var index = fastKey(key), entry; - if(index !== 'F')return that._i[index]; - // frozen object case - for(entry = that._f; entry; entry = entry.n){ - if(entry.k == key)return entry; + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) } -}; + return ret +} -module.exports = { - getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ - var C = wrapper(function(that, iterable){ - strictNew(that, C, NAME); - that._i = $.create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear(){ - for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ - entry.r = true; - if(entry.p)entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function(key){ - var that = this - , entry = getEntry(that, key); - if(entry){ - var next = entry.n - , prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if(prev)prev.n = next; - if(next)next.p = prev; - if(that._f == entry)that._f = next; - if(that._l == entry)that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /*, that = undefined */){ - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) - , entry; - while(entry = entry ? entry.n : this._f){ - f(entry.v, entry.k, this); - // revert to the last existing entry - while(entry && entry.r)entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key){ - return !!getEntry(this, key); - } - }); - if(DESCRIPTORS)$.setDesc(C.prototype, 'size', { - get: function(){ - return defined(this[SIZE]); - } - }); - return C; - }, - def: function(that, key, value){ - var entry = getEntry(that, key) - , prev, index; - // change existing entry - if(entry){ - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if(!that._f)that._f = entry; - if(prev)prev.n = entry; - that[SIZE]++; - // add to index - if(index !== 'F')that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function(C, NAME, IS_MAP){ - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function(iterated, kind){ - this._t = iterated; // target - this._k = kind; // kind - this._l = undefined; // previous - }, function(){ - var that = this - , kind = that._k - , entry = that._l; - // revert to the last existing entry - while(entry && entry.r)entry = entry.p; - // get next entry - if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if(kind == 'keys' )return step(0, entry.k); - if(kind == 'values')return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) } -}; -},{"./$":89,"./$.ctx":65,"./$.defined":66,"./$.descriptors":67,"./$.for-of":72,"./$.has":75,"./$.hide":76,"./$.is-object":82,"./$.iter-define":85,"./$.iter-step":87,"./$.redefine-all":96,"./$.set-species":100,"./$.strict-new":104,"./$.uid":111}],62:[function(_dereq_,module,exports){ -// https://github.com/DavidBruant/Map-Set.prototype.toJSON -var forOf = _dereq_('./$.for-of') - , classof = _dereq_('./$.classof'); -module.exports = function(NAME){ - return function toJSON(){ - if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); - var arr = []; - forOf(this, false, arr.push, arr); - return arr; - }; -}; -},{"./$.classof":59,"./$.for-of":72}],63:[function(_dereq_,module,exports){ -'use strict'; -var $ = _dereq_('./$') - , global = _dereq_('./$.global') - , $export = _dereq_('./$.export') - , fails = _dereq_('./$.fails') - , hide = _dereq_('./$.hide') - , redefineAll = _dereq_('./$.redefine-all') - , forOf = _dereq_('./$.for-of') - , strictNew = _dereq_('./$.strict-new') - , isObject = _dereq_('./$.is-object') - , setToStringTag = _dereq_('./$.set-to-string-tag') - , DESCRIPTORS = _dereq_('./$.descriptors'); + return out +} -module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ - var Base = global[NAME] - , C = Base - , ADDER = IS_MAP ? 'set' : 'add' - , proto = C && C.prototype - , O = {}; - if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ - new C().entries().next(); - }))){ - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = Buffer._augment(this.subarray(start, end)) } else { - C = wrapper(function(target, iterable){ - strictNew(target, C, NAME); - target._c = new Base; - if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target); - }); - $.each.call('add,clear,delete,forEach,get,has,set,keys,values,entries'.split(','),function(KEY){ - var IS_ADDER = KEY == 'add' || KEY == 'set'; - if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){ - if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false; - var result = this._c[KEY](a === 0 ? 0 : a, b); - return IS_ADDER ? this : result; - }); - }); - if('size' in proto)$.setDesc(C.prototype, 'size', { - get: function(){ - return this._c.size; - } - }); + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } } - setToStringTag(C, NAME); + if (newBuf.length) newBuf.parent = this.parent || this - O[NAME] = C; - $export($export.G + $export.W + $export.F, O); + return newBuf +} - if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} - return C; -}; -},{"./$":89,"./$.descriptors":67,"./$.export":70,"./$.fails":71,"./$.for-of":72,"./$.global":74,"./$.hide":76,"./$.is-object":82,"./$.redefine-all":96,"./$.set-to-string-tag":101,"./$.strict-new":104}],64:[function(_dereq_,module,exports){ -var core = module.exports = {version: '1.2.6'}; -if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef -},{}],65:[function(_dereq_,module,exports){ -// optional / simple context binding -var aFunction = _dereq_('./$.a-function'); -module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; -}; -},{"./$.a-function":56}],66:[function(_dereq_,module,exports){ -// 7.2.1 RequireObjectCoercible(argument) -module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; -}; -},{}],67:[function(_dereq_,module,exports){ -// Thank's IE8 for his funny defineProperty -module.exports = !_dereq_('./$.fails')(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; -}); -},{"./$.fails":71}],68:[function(_dereq_,module,exports){ -var isObject = _dereq_('./$.is-object') - , document = _dereq_('./$.global').document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); -module.exports = function(it){ - return is ? document.createElement(it) : {}; -}; -},{"./$.global":74,"./$.is-object":82}],69:[function(_dereq_,module,exports){ -// all enumerable object keys, includes symbols -var $ = _dereq_('./$'); -module.exports = function(it){ - var keys = $.getKeys(it) - , getSymbols = $.getSymbols; - if(getSymbols){ - var symbols = getSymbols(it) - , isEnum = $.isEnum - , i = 0 - , key; - while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key); + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) } - return keys; -}; -},{"./$":89}],70:[function(_dereq_,module,exports){ -var global = _dereq_('./$.global') - , core = _dereq_('./$.core') - , ctx = _dereq_('./$.ctx') - , PROTOTYPE = 'prototype'; -var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , IS_WRAP = type & $export.W - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] - , key, own, out; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && key in target; - if(own && key in exports)continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function(C){ - var F = function(param){ - return this instanceof C ? new C(param) : C(param); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF } -}; -// type bitmap -$export.F = 1; // forced -$export.G = 2; // global -$export.S = 4; // static -$export.P = 8; // proto -$export.B = 16; // bind -$export.W = 32; // wrap -module.exports = $export; -},{"./$.core":64,"./$.ctx":65,"./$.global":74}],71:[function(_dereq_,module,exports){ -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF } -}; -},{}],72:[function(_dereq_,module,exports){ -var ctx = _dereq_('./$.ctx') - , call = _dereq_('./$.iter-call') - , isArrayIter = _dereq_('./$.is-array-iter') - , anObject = _dereq_('./$.an-object') - , toLength = _dereq_('./$.to-length') - , getIterFn = _dereq_('./core.get-iterator-method'); -module.exports = function(iterable, entries, fn, that){ - var iterFn = getIterFn(iterable) - , f = ctx(fn, that, entries ? 2 : 1) - , index = 0 - , length, step, iterator; - if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ - entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ - call(iterator, f, step.value, entries); + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 } -}; -},{"./$.an-object":58,"./$.ctx":65,"./$.is-array-iter":80,"./$.iter-call":83,"./$.to-length":109,"./core.get-iterator-method":113}],73:[function(_dereq_,module,exports){ -// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window -var toIObject = _dereq_('./$.to-iobject') - , getNames = _dereq_('./$').getNames - , toString = {}.toString; +} -var windowNames = typeof window == 'object' && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} -var getWindowNames = function(it){ - try { - return getNames(it); - } catch(e){ - return windowNames.slice(); +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) } -}; + return offset + 2 +} -module.exports.get = function getOwnPropertyNames(it){ - if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it); - return getNames(toIObject(it)); -}; -},{"./$":89,"./$.to-iobject":108}],74:[function(_dereq_,module,exports){ -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); -if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef -},{}],75:[function(_dereq_,module,exports){ -var hasOwnProperty = {}.hasOwnProperty; -module.exports = function(it, key){ - return hasOwnProperty.call(it, key); -}; -},{}],76:[function(_dereq_,module,exports){ -var $ = _dereq_('./$') - , createDesc = _dereq_('./$.property-desc'); -module.exports = _dereq_('./$.descriptors') ? function(object, key, value){ - return $.setDesc(object, key, createDesc(1, value)); -} : function(object, key, value){ - object[key] = value; - return object; -}; -},{"./$":89,"./$.descriptors":67,"./$.property-desc":95}],77:[function(_dereq_,module,exports){ -module.exports = _dereq_('./$.global').document && document.documentElement; -},{"./$.global":74}],78:[function(_dereq_,module,exports){ -// fast apply, http://jsperf.lnkit.com/fast-apply/5 -module.exports = function(fn, args, that){ - var un = that === undefined; - switch(args.length){ - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); -}; -},{}],79:[function(_dereq_,module,exports){ -// fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = _dereq_('./$.cof'); -module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ - return cof(it) == 'String' ? it.split('') : Object(it); -}; -},{"./$.cof":60}],80:[function(_dereq_,module,exports){ -// check on default Array iterator -var Iterators = _dereq_('./$.iterators') - , ITERATOR = _dereq_('./$.wks')('iterator') - , ArrayProto = Array.prototype; +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} -module.exports = function(it){ - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); -}; -},{"./$.iterators":88,"./$.wks":112}],81:[function(_dereq_,module,exports){ -// 7.2.2 IsArray(argument) -var cof = _dereq_('./$.cof'); -module.exports = Array.isArray || function(arg){ - return cof(arg) == 'Array'; -}; -},{"./$.cof":60}],82:[function(_dereq_,module,exports){ -module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; -}; -},{}],83:[function(_dereq_,module,exports){ -// call something on iterator step with safe closing on error -var anObject = _dereq_('./$.an-object'); -module.exports = function(iterator, fn, value, entries){ - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch(e){ - var ret = iterator['return']; - if(ret !== undefined)anObject(ret.call(iterator)); - throw e; +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) } -}; -},{"./$.an-object":58}],84:[function(_dereq_,module,exports){ -'use strict'; -var $ = _dereq_('./$') - , descriptor = _dereq_('./$.property-desc') - , setToStringTag = _dereq_('./$.set-to-string-tag') - , IteratorPrototype = {}; + return offset + 4 +} -// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -_dereq_('./$.hide')(IteratorPrototype, _dereq_('./$.wks')('iterator'), function(){ return this; }); +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} -module.exports = function(Constructor, NAME, next){ - Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)}); - setToStringTag(Constructor, NAME + ' Iterator'); -}; -},{"./$":89,"./$.hide":76,"./$.property-desc":95,"./$.set-to-string-tag":101,"./$.wks":112}],85:[function(_dereq_,module,exports){ -'use strict'; -var LIBRARY = _dereq_('./$.library') - , $export = _dereq_('./$.export') - , redefine = _dereq_('./$.redefine') - , hide = _dereq_('./$.hide') - , has = _dereq_('./$.has') - , Iterators = _dereq_('./$.iterators') - , $iterCreate = _dereq_('./$.iter-create') - , setToStringTag = _dereq_('./$.set-to-string-tag') - , getProto = _dereq_('./$').getProto - , ITERATOR = _dereq_('./$.wks')('iterator') - , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` - , FF_ITERATOR = '@@iterator' - , KEYS = 'keys' - , VALUES = 'values'; +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) -var returnThis = function(){ return this; }; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } -module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ - $iterCreate(Constructor, NAME, next); - var getMethod = function(kind){ - if(!BUGGY && kind in proto)return proto[kind]; - switch(kind){ - case KEYS: return function keys(){ return new Constructor(this, kind); }; - case VALUES: return function values(){ return new Constructor(this, kind); }; - } return function entries(){ return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator' - , DEF_VALUES = DEFAULT == VALUES - , VALUES_BUG = false - , proto = Base.prototype - , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] - , $default = $native || getMethod(DEFAULT) - , methods, key; - // Fix native - if($native){ - var IteratorPrototype = getProto($default.call(new Base)); - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // FF fix - if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); - // fix Array#{values, @@iterator}.name in V8 / FF - if(DEF_VALUES && $native.name !== VALUES){ - VALUES_BUG = true; - $default = function values(){ return $native.call(this); }; - } + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } - // Define iterator - if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ - hide(proto, ITERATOR, $default); + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if(DEFAULT){ - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: !DEF_VALUES ? $default : getMethod('entries') - }; - if(FORCED)for(key in methods){ - if(!(key in proto))redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } - return methods; -}; -},{"./$":89,"./$.export":70,"./$.has":75,"./$.hide":76,"./$.iter-create":84,"./$.iterators":88,"./$.library":91,"./$.redefine":97,"./$.set-to-string-tag":101,"./$.wks":112}],86:[function(_dereq_,module,exports){ -var ITERATOR = _dereq_('./$.wks')('iterator') - , SAFE_CLOSING = false; -try { - var riter = [7][ITERATOR](); - riter['return'] = function(){ SAFE_CLOSING = true; }; - Array.from(riter, function(){ throw 2; }); -} catch(e){ /* empty */ } + return offset + byteLength +} -module.exports = function(exec, skipClosing){ - if(!skipClosing && !SAFE_CLOSING)return false; - var safe = false; - try { - var arr = [7] - , iter = arr[ITERATOR](); - iter.next = function(){ safe = true; }; - arr[ITERATOR] = function(){ return iter; }; - exec(arr); - } catch(e){ /* empty */ } - return safe; -}; -},{"./$.wks":112}],87:[function(_dereq_,module,exports){ -module.exports = function(done, value){ - return {value: value, done: !!done}; -}; -},{}],88:[function(_dereq_,module,exports){ -module.exports = {}; -},{}],89:[function(_dereq_,module,exports){ -var $Object = Object; -module.exports = { - create: $Object.create, - getProto: $Object.getPrototypeOf, - isEnum: {}.propertyIsEnumerable, - getDesc: $Object.getOwnPropertyDescriptor, - setDesc: $Object.defineProperty, - setDescs: $Object.defineProperties, - getKeys: $Object.keys, - getNames: $Object.getOwnPropertyNames, - getSymbols: $Object.getOwnPropertySymbols, - each: [].forEach -}; -},{}],90:[function(_dereq_,module,exports){ -var $ = _dereq_('./$') - , toIObject = _dereq_('./$.to-iobject'); -module.exports = function(object, el){ - var O = toIObject(object) - , keys = $.getKeys(O) - , length = keys.length - , index = 0 - , key; - while(length > index)if(O[key = keys[index++]] === el)return key; -}; -},{"./$":89,"./$.to-iobject":108}],91:[function(_dereq_,module,exports){ -module.exports = true; -},{}],92:[function(_dereq_,module,exports){ -var global = _dereq_('./$.global') - , macrotask = _dereq_('./$.task').set - , Observer = global.MutationObserver || global.WebKitMutationObserver - , process = global.process - , Promise = global.Promise - , isNode = _dereq_('./$.cof')(process) == 'process' - , head, last, notify; +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} -var flush = function(){ - var parent, domain, fn; - if(isNode && (parent = process.domain)){ - process.domain = null; - parent.exit(); +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) } - while(head){ - domain = head.domain; - fn = head.fn; - if(domain)domain.enter(); - fn(); // <- currently we use it only for Promise - try / catch not required - if(domain)domain.exit(); - head = head.next; - } last = undefined; - if(parent)parent.enter(); -}; + return offset + 2 +} -// Node.js -if(isNode){ - notify = function(){ - process.nextTick(flush); - }; -// browsers with MutationObserver -} else if(Observer){ - var toggle = 1 - , node = document.createTextNode(''); - new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new - notify = function(){ - node.data = toggle = -toggle; - }; -// environments with maybe non-completely correct, but existent Promise -} else if(Promise && Promise.resolve){ - notify = function(){ - Promise.resolve().then(flush); - }; -// for other environments - macrotask based on: -// - setImmediate -// - MessageChannel -// - window.postMessag -// - onreadystatechange -// - setTimeout -} else { - notify = function(){ - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 } -module.exports = function asap(fn){ - var task = {fn: fn, next: undefined, domain: isNode && process.domain}; - if(last)last.next = task; - if(!head){ - head = task; - notify(); - } last = task; -}; -},{"./$.cof":60,"./$.global":74,"./$.task":106}],93:[function(_dereq_,module,exports){ -// 19.1.2.1 Object.assign(target, source, ...) -var $ = _dereq_('./$') - , toObject = _dereq_('./$.to-object') - , IObject = _dereq_('./$.iobject'); +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} -// should work with symbols and should have deterministic property order (V8 bug) -module.exports = _dereq_('./$.fails')(function(){ - var a = Object.assign - , A = {} - , B = {} - , S = Symbol() - , K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function(k){ B[k] = k; }); - return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; -}) ? function assign(target, source){ // eslint-disable-line no-unused-vars - var T = toObject(target) - , $$ = arguments - , $$len = $$.length - , index = 1 - , getKeys = $.getKeys - , getSymbols = $.getSymbols - , isEnum = $.isEnum; - while($$len > index){ - var S = IObject($$[index++]) - , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) - , length = keys.length - , j = 0 - , key; - while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) } - return T; -} : Object.assign; -},{"./$":89,"./$.fails":71,"./$.iobject":79,"./$.to-object":110}],94:[function(_dereq_,module,exports){ -// most Object methods by ES6 should accept primitives -var $export = _dereq_('./$.export') - , core = _dereq_('./$.core') - , fails = _dereq_('./$.fails'); -module.exports = function(KEY, exec){ - var fn = (core.Object || {})[KEY] || Object[KEY] - , exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); -}; -},{"./$.core":64,"./$.export":70,"./$.fails":71}],95:[function(_dereq_,module,exports){ -module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; -}; -},{}],96:[function(_dereq_,module,exports){ -var redefine = _dereq_('./$.redefine'); -module.exports = function(target, src){ - for(var key in src)redefine(target, key, src[key]); - return target; -}; -},{"./$.redefine":97}],97:[function(_dereq_,module,exports){ -module.exports = _dereq_('./$.hide'); -},{"./$.hide":76}],98:[function(_dereq_,module,exports){ -// 7.2.9 SameValue(x, y) -module.exports = Object.is || function is(x, y){ - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; -}; -},{}],99:[function(_dereq_,module,exports){ -// Works with __proto__ only. Old v8 can't work with null proto objects. -/* eslint-disable no-proto */ -var getDesc = _dereq_('./$').getDesc - , isObject = _dereq_('./$.is-object') - , anObject = _dereq_('./$.an-object'); -var check = function(O, proto){ - anObject(O); - if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); -}; -module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function(test, buggy, set){ - try { - set = _dereq_('./$.ctx')(Function.call, getDesc(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch(e){ buggy = true; } - return function setPrototypeOf(O, proto){ - check(O, proto); - if(buggy)O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check -}; -},{"./$":89,"./$.an-object":58,"./$.ctx":65,"./$.is-object":82}],100:[function(_dereq_,module,exports){ -'use strict'; -var core = _dereq_('./$.core') - , $ = _dereq_('./$') - , DESCRIPTORS = _dereq_('./$.descriptors') - , SPECIES = _dereq_('./$.wks')('species'); + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} -module.exports = function(KEY){ - var C = core[KEY]; - if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, { - configurable: true, - get: function(){ return this; } - }); -}; -},{"./$":89,"./$.core":64,"./$.descriptors":67,"./$.wks":112}],101:[function(_dereq_,module,exports){ -var def = _dereq_('./$').setDesc - , has = _dereq_('./$.has') - , TAG = _dereq_('./$.wks')('toStringTag'); +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} -module.exports = function(it, tag, stat){ - if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); -}; -},{"./$":89,"./$.has":75,"./$.wks":112}],102:[function(_dereq_,module,exports){ -var global = _dereq_('./$.global') - , SHARED = '__core-js_shared__' - , store = global[SHARED] || (global[SHARED] = {}); -module.exports = function(key){ - return store[key] || (store[key] = {}); -}; -},{"./$.global":74}],103:[function(_dereq_,module,exports){ -// 7.3.20 SpeciesConstructor(O, defaultConstructor) -var anObject = _dereq_('./$.an-object') - , aFunction = _dereq_('./$.a-function') - , SPECIES = _dereq_('./$.wks')('species'); -module.exports = function(O, D){ - var C = anObject(O).constructor, S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); -}; -},{"./$.a-function":56,"./$.an-object":58,"./$.wks":112}],104:[function(_dereq_,module,exports){ -module.exports = function(it, Constructor, name){ - if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); - return it; -}; -},{}],105:[function(_dereq_,module,exports){ -var toInteger = _dereq_('./$.to-integer') - , defined = _dereq_('./$.defined'); -// true -> String#at -// false -> String#codePointAt -module.exports = function(TO_STRING){ - return function(that, pos){ - var s = String(defined(that)) - , i = toInteger(pos) - , l = s.length - , a, b; - if(i < 0 || i >= l)return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; -}; -},{"./$.defined":66,"./$.to-integer":107}],106:[function(_dereq_,module,exports){ -var ctx = _dereq_('./$.ctx') - , invoke = _dereq_('./$.invoke') - , html = _dereq_('./$.html') - , cel = _dereq_('./$.dom-create') - , global = _dereq_('./$.global') - , process = global.process - , setTask = global.setImmediate - , clearTask = global.clearImmediate - , MessageChannel = global.MessageChannel - , counter = 0 - , queue = {} - , ONREADYSTATECHANGE = 'onreadystatechange' - , defer, channel, port; -var run = function(){ - var id = +this; - if(queue.hasOwnProperty(id)){ - var fn = queue[id]; - delete queue[id]; - fn(); +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } -}; -var listner = function(event){ - run.call(event.data); -}; -// Node.js 0.9+ & IE10+ has setImmediate, otherwise: -if(!setTask || !clearTask){ - setTask = function setImmediate(fn){ - var args = [], i = 1; - while(arguments.length > i)args.push(arguments[i++]); - queue[++counter] = function(){ - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id){ - delete queue[id]; - }; - // Node.js 0.8- - if(_dereq_('./$.cof')(process) == 'process'){ - defer = function(id){ - process.nextTick(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if(MessageChannel){ - channel = new MessageChannel; - port = channel.port2; - channel.port1.onmessage = listner; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ - defer = function(id){ - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listner, false); - // IE8- - } else if(ONREADYSTATECHANGE in cel('script')){ - defer = function(id){ - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } } else { - defer = function(id){ - setTimeout(ctx(run, id, 1), 0); - }; + target._set(this.subarray(start, start + len), targetStart) + } + + return len +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (end < start) throw new RangeError('end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] + } + } + + return this +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function toArrayBuffer () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer.TYPED_ARRAY_SUPPORT) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) { + buf[i] = this[i] + } + return buf.buffer + } + } else { + throw new TypeError('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function _augment (arr) { + arr.constructor = Buffer + arr._isBuffer = true + + // save reference to original Uint8Array set method before overwriting + arr._set = arr.set + + // deprecated + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.equals = BP.equals + arr.compare = BP.compare + arr.indexOf = BP.indexOf + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUIntLE = BP.readUIntLE + arr.readUIntBE = BP.readUIntBE + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readIntLE = BP.readIntLE + arr.readIntBE = BP.readIntBE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUIntLE = BP.writeUIntLE + arr.writeUIntBE = BP.writeUIntBE + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeIntLE = BP.writeIntLE + arr.writeIntBE = BP.writeIntBE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' } + return str } -module.exports = { - set: setTask, - clear: clearTask -}; -},{"./$.cof":60,"./$.ctx":65,"./$.dom-create":68,"./$.global":74,"./$.html":77,"./$.invoke":78}],107:[function(_dereq_,module,exports){ -// 7.1.4 ToInteger -var ceil = Math.ceil - , floor = Math.floor; -module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); -}; -},{}],108:[function(_dereq_,module,exports){ -// to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = _dereq_('./$.iobject') - , defined = _dereq_('./$.defined'); -module.exports = function(it){ - return IObject(defined(it)); -}; -},{"./$.defined":66,"./$.iobject":79}],109:[function(_dereq_,module,exports){ -// 7.1.15 ToLength -var toInteger = _dereq_('./$.to-integer') - , min = Math.min; -module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 -}; -},{"./$.to-integer":107}],110:[function(_dereq_,module,exports){ -// 7.1.13 ToObject(argument) -var defined = _dereq_('./$.defined'); -module.exports = function(it){ - return Object(defined(it)); -}; -},{"./$.defined":66}],111:[function(_dereq_,module,exports){ -var id = 0 - , px = Math.random(); -module.exports = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; -},{}],112:[function(_dereq_,module,exports){ -var store = _dereq_('./$.shared')('wks') - , uid = _dereq_('./$.uid') - , Symbol = _dereq_('./$.global').Symbol; -module.exports = function(name){ - return store[name] || (store[name] = - Symbol && Symbol[name] || (Symbol || uid)('Symbol.' + name)); -}; -},{"./$.global":74,"./$.shared":102,"./$.uid":111}],113:[function(_dereq_,module,exports){ -var classof = _dereq_('./$.classof') - , ITERATOR = _dereq_('./$.wks')('iterator') - , Iterators = _dereq_('./$.iterators'); -module.exports = _dereq_('./$.core').getIteratorMethod = function(it){ - if(it != undefined)return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; -}; -},{"./$.classof":59,"./$.core":64,"./$.iterators":88,"./$.wks":112}],114:[function(_dereq_,module,exports){ -var anObject = _dereq_('./$.an-object') - , get = _dereq_('./core.get-iterator-method'); -module.exports = _dereq_('./$.core').getIterator = function(it){ - var iterFn = get(it); - if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); - return anObject(iterFn.call(it)); -}; -},{"./$.an-object":58,"./$.core":64,"./core.get-iterator-method":113}],115:[function(_dereq_,module,exports){ -var classof = _dereq_('./$.classof') - , ITERATOR = _dereq_('./$.wks')('iterator') - , Iterators = _dereq_('./$.iterators'); -module.exports = _dereq_('./$.core').isIterable = function(it){ - var O = Object(it); - return O[ITERATOR] !== undefined - || '@@iterator' in O - || Iterators.hasOwnProperty(classof(O)); -}; -},{"./$.classof":59,"./$.core":64,"./$.iterators":88,"./$.wks":112}],116:[function(_dereq_,module,exports){ -'use strict'; -var ctx = _dereq_('./$.ctx') - , $export = _dereq_('./$.export') - , toObject = _dereq_('./$.to-object') - , call = _dereq_('./$.iter-call') - , isArrayIter = _dereq_('./$.is-array-iter') - , toLength = _dereq_('./$.to-length') - , getIterFn = _dereq_('./core.get-iterator-method'); -$export($export.S + $export.F * !_dereq_('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ - var O = toObject(arrayLike) - , C = typeof this == 'function' ? this : Array - , $$ = arguments - , $$len = $$.length - , mapfn = $$len > 1 ? $$[1] : undefined - , mapping = mapfn !== undefined - , index = 0 - , iterFn = getIterFn(O) - , length, result, step, iterator; - if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ - for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ - result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value; + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue } - } else { - length = toLength(O.length); - for(result = new C(length); length > index; index++){ - result[index] = mapping ? mapfn(O[index], index) : O[index]; + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') } - result.length = index; - return result; } -}); -},{"./$.ctx":65,"./$.export":70,"./$.is-array-iter":80,"./$.iter-call":83,"./$.iter-detect":86,"./$.to-length":109,"./$.to-object":110,"./core.get-iterator-method":113}],117:[function(_dereq_,module,exports){ -'use strict'; -var addToUnscopables = _dereq_('./$.add-to-unscopables') - , step = _dereq_('./$.iter-step') - , Iterators = _dereq_('./$.iterators') - , toIObject = _dereq_('./$.to-iobject'); + return bytes +} -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -module.exports = _dereq_('./$.iter-define')(Array, 'Array', function(iterated, kind){ - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function(){ - var O = this._t - , kind = this._k - , index = this._i++; - if(!O || index >= O.length){ - this._t = undefined; - return step(1); +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) } - if(kind == 'keys' )return step(0, index); - if(kind == 'values')return step(0, O[index]); - return step(0, [index, O[index]]); -}, 'values'); + return byteArray +} -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -Iterators.Arguments = Iterators.Array; +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); -},{"./$.add-to-unscopables":57,"./$.iter-define":85,"./$.iter-step":87,"./$.iterators":88,"./$.to-iobject":108}],118:[function(_dereq_,module,exports){ -'use strict'; -var strong = _dereq_('./$.collection-strong'); + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } -// 23.1 Map Objects -_dereq_('./$.collection')('Map', function(get){ - return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; -}, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key){ - var entry = strong.getEntry(this, key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value){ - return strong.def(this, key === 0 ? 0 : key, value); + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] } -}, strong, true); -},{"./$.collection":63,"./$.collection-strong":61}],119:[function(_dereq_,module,exports){ -// 20.2.2.22 Math.log2(x) -var $export = _dereq_('./$.export'); + return i +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":134,"ieee754":135,"isarray":136}],134:[function(_dereq_,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 -$export($export.S, 'Math', { - log2: function log2(x){ - return Math.log(x) / Math.LN2; - } -}); -},{"./$.export":70}],120:[function(_dereq_,module,exports){ -// 19.1.3.1 Object.assign(target, source) -var $export = _dereq_('./$.export'); + function push (v) { + arr[L++] = v + } -$export($export.S + $export.F, 'Object', {assign: _dereq_('./$.object-assign')}); -},{"./$.export":70,"./$.object-assign":93}],121:[function(_dereq_,module,exports){ -// 19.1.2.5 Object.freeze(O) -var isObject = _dereq_('./$.is-object'); + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } -_dereq_('./$.object-sap')('freeze', function($freeze){ - return function freeze(it){ - return $freeze && isObject(it) ? $freeze(it) : it; - }; -}); -},{"./$.is-object":82,"./$.object-sap":94}],122:[function(_dereq_,module,exports){ -// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) -var toIObject = _dereq_('./$.to-iobject'); + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } -_dereq_('./$.object-sap')('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){ - return function getOwnPropertyDescriptor(it, key){ - return $getOwnPropertyDescriptor(toIObject(it), key); - }; -}); -},{"./$.object-sap":94,"./$.to-iobject":108}],123:[function(_dereq_,module,exports){ -// 19.1.2.14 Object.keys(O) -var toObject = _dereq_('./$.to-object'); + return arr + } -_dereq_('./$.object-sap')('keys', function($keys){ - return function keys(it){ - return $keys(toObject(it)); - }; -}); -},{"./$.object-sap":94,"./$.to-object":110}],124:[function(_dereq_,module,exports){ -// 19.1.3.19 Object.setPrototypeOf(O, proto) -var $export = _dereq_('./$.export'); -$export($export.S, 'Object', {setPrototypeOf: _dereq_('./$.set-proto').set}); -},{"./$.export":70,"./$.set-proto":99}],125:[function(_dereq_,module,exports){ -module.exports=_dereq_(37) -},{"/Users/bcamper/Documents/dev/vector-map/node_modules/browser-resolve/empty.js":37}],126:[function(_dereq_,module,exports){ -'use strict'; -var $ = _dereq_('./$') - , LIBRARY = _dereq_('./$.library') - , global = _dereq_('./$.global') - , ctx = _dereq_('./$.ctx') - , classof = _dereq_('./$.classof') - , $export = _dereq_('./$.export') - , isObject = _dereq_('./$.is-object') - , anObject = _dereq_('./$.an-object') - , aFunction = _dereq_('./$.a-function') - , strictNew = _dereq_('./$.strict-new') - , forOf = _dereq_('./$.for-of') - , setProto = _dereq_('./$.set-proto').set - , same = _dereq_('./$.same-value') - , SPECIES = _dereq_('./$.wks')('species') - , speciesConstructor = _dereq_('./$.species-constructor') - , asap = _dereq_('./$.microtask') - , PROMISE = 'Promise' - , process = global.process - , isNode = classof(process) == 'process' - , P = global[PROMISE] - , Wrapper; + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length -var testResolve = function(sub){ - var test = new P(function(){}); - if(sub)test.constructor = Object; - return P.resolve(test) === test; -}; + function encode (num) { + return lookup.charAt(num) + } -var USE_NATIVE = function(){ - var works = false; - function P2(x){ - var self = new P(x); - setProto(self, P2.prototype); - return self; - } - try { - works = P && P.resolve && testResolve(); - setProto(P2, P); - P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); - // actual Firefox has broken subclass support, test that - if(!(P2.resolve(5).then(function(){}) instanceof P2)){ - works = false; - } - // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 - if(works && _dereq_('./$.descriptors')){ - var thenableThenGotten = false; - P.resolve($.setDesc({}, 'then', { - get: function(){ thenableThenGotten = true; } - })); - works = thenableThenGotten; - } - } catch(e){ works = false; } - return works; -}(); + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } -// helpers -var sameConstructor = function(a, b){ - // library wrapper special case - if(LIBRARY && a === P && b === Wrapper)return true; - return same(a, b); -}; -var getConstructor = function(C){ - var S = anObject(C)[SPECIES]; - return S != undefined ? S : C; -}; -var isThenable = function(it){ - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; -}; -var PromiseCapability = function(C){ - var resolve, reject; - this.promise = new C(function($$resolve, $$reject){ - if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve), - this.reject = aFunction(reject) -}; -var perform = function(exec){ - try { - exec(); - } catch(e){ - return {error: e}; - } -}; -var notify = function(record, isReject){ - if(record.n)return; - record.n = true; - var chain = record.c; - asap(function(){ - var value = record.v - , ok = record.s == 1 - , i = 0; - var run = function(reaction){ - var handler = ok ? reaction.ok : reaction.fail - , resolve = reaction.resolve - , reject = reaction.reject - , result, then; - try { - if(handler){ - if(!ok)record.h = true; - result = handler === true ? value : handler(value); - if(result === reaction.promise){ - reject(TypeError('Promise-chain cycle')); - } else if(then = isThenable(result)){ - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch(e){ - reject(e); - } - }; - while(chain.length > i)run(chain[i++]); // variable length - can't use forEach - chain.length = 0; - record.n = false; - if(isReject)setTimeout(function(){ - var promise = record.p - , handler, console; - if(isUnhandled(promise)){ - if(isNode){ - process.emit('unhandledRejection', value, promise); - } else if(handler = global.onunhandledrejection){ - handler({promise: promise, reason: value}); - } else if((console = global.console) && console.error){ - console.error('Unhandled promise rejection', value); - } - } record.a = undefined; - }, 1); - }); -}; -var isUnhandled = function(promise){ - var record = promise._d - , chain = record.a || record.c - , i = 0 - , reaction; - if(record.h)return false; - while(chain.length > i){ - reaction = chain[i++]; - if(reaction.fail || !isUnhandled(reaction.promise))return false; - } return true; -}; -var $reject = function(value){ - var record = this; - if(record.d)return; - record.d = true; - record = record.r || record; // unwrap - record.v = value; - record.s = 2; - record.a = record.c.slice(); - notify(record, true); -}; -var $resolve = function(value){ - var record = this - , then; - if(record.d)return; - record.d = true; - record = record.r || record; // unwrap - try { - if(record.p === value)throw TypeError("Promise can't be resolved itself"); - if(then = isThenable(value)){ - asap(function(){ - var wrapper = {r: record, d: false}; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch(e){ - $reject.call(wrapper, e); - } - }); - } else { - record.v = value; - record.s = 1; - notify(record, false); - } - } catch(e){ - $reject.call({r: record, d: false}, e); // wrap - } -}; + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } -// constructor polyfill -if(!USE_NATIVE){ - // 25.4.3.1 Promise(executor) - P = function Promise(executor){ - aFunction(executor); - var record = this._d = { - p: strictNew(this, P, PROMISE), // <- promise - c: [], // <- awaiting reactions - a: undefined, // <- checked in isUnhandled reactions - s: 0, // <- state - d: false, // <- done - v: undefined, // <- value - h: false, // <- handled rejection - n: false // <- notify - }; - try { - executor(ctx($resolve, record, 1), ctx($reject, record, 1)); - } catch(err){ - $reject.call(record, err); - } - }; - _dereq_('./$.redefine-all')(P.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected){ - var reaction = new PromiseCapability(speciesConstructor(this, P)) - , promise = reaction.promise - , record = this._d; - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - record.c.push(reaction); - if(record.a)record.a.push(reaction); - if(record.s)notify(record, false); - return promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function(onRejected){ - return this.then(undefined, onRejected); - } - }); -} + return output + } -$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P}); -_dereq_('./$.set-to-string-tag')(P, PROMISE); -_dereq_('./$.set-species')(PROMISE); -Wrapper = _dereq_('./$.core')[PROMISE]; + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) -// statics -$export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r){ - var capability = new PromiseCapability(this) - , $$reject = capability.reject; - $$reject(r); - return capability.promise; - } -}); -$export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x){ - // instanceof instead of internal slot check because we should fix it without replacement native Promise core - if(x instanceof P && sameConstructor(x.constructor, this))return x; - var capability = new PromiseCapability(this) - , $$resolve = capability.resolve; - $$resolve(x); - return capability.promise; - } -}); -$export($export.S + $export.F * !(USE_NATIVE && _dereq_('./$.iter-detect')(function(iter){ - P.all(iter)['catch'](function(){}); -})), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable){ - var C = getConstructor(this) - , capability = new PromiseCapability(C) - , resolve = capability.resolve - , reject = capability.reject - , values = []; - var abrupt = perform(function(){ - forOf(iterable, false, values.push, values); - var remaining = values.length - , results = Array(remaining); - if(remaining)$.each.call(values, function(promise, index){ - var alreadyCalled = false; - C.resolve(promise).then(function(value){ - if(alreadyCalled)return; - alreadyCalled = true; - results[index] = value; - --remaining || resolve(results); - }, reject); - }); - else resolve(results); - }); - if(abrupt)reject(abrupt.error); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable){ - var C = getConstructor(this) - , capability = new PromiseCapability(C) - , reject = capability.reject; - var abrupt = perform(function(){ - forOf(iterable, false, function(promise){ - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if(abrupt)reject(abrupt.error); - return capability.promise; - } -}); -},{"./$":89,"./$.a-function":56,"./$.an-object":58,"./$.classof":59,"./$.core":64,"./$.ctx":65,"./$.descriptors":67,"./$.export":70,"./$.for-of":72,"./$.global":74,"./$.is-object":82,"./$.iter-detect":86,"./$.library":91,"./$.microtask":92,"./$.redefine-all":96,"./$.same-value":98,"./$.set-proto":99,"./$.set-species":100,"./$.set-to-string-tag":101,"./$.species-constructor":103,"./$.strict-new":104,"./$.wks":112}],127:[function(_dereq_,module,exports){ -'use strict'; -var strong = _dereq_('./$.collection-strong'); +},{}],135:[function(_dereq_,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] -// 23.2 Set Objects -_dereq_('./$.collection')('Set', function(get){ - return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; -}, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value){ - return strong.def(this, value = value === 0 ? 0 : value, value); + 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 } -}, strong); -},{"./$.collection":63,"./$.collection-strong":61}],128:[function(_dereq_,module,exports){ -'use strict'; -var $at = _dereq_('./$.string-at')(true); + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} -// 21.1.3.27 String.prototype[@@iterator]() -_dereq_('./$.iter-define')(String, 'String', function(iterated){ - this._t = String(iterated); // target - this._i = 0; // next index -// 21.1.5.2.1 %StringIteratorPrototype%.next() -}, function(){ - var O = this._t - , index = this._i - , point; - if(index >= O.length)return {value: undefined, done: true}; - point = $at(O, index); - this._i += point.length; - return {value: point, done: false}; -}); -},{"./$.iter-define":85,"./$.string-at":105}],129:[function(_dereq_,module,exports){ -'use strict'; -// ECMAScript 6 symbols shim -var $ = _dereq_('./$') - , global = _dereq_('./$.global') - , has = _dereq_('./$.has') - , DESCRIPTORS = _dereq_('./$.descriptors') - , $export = _dereq_('./$.export') - , redefine = _dereq_('./$.redefine') - , $fails = _dereq_('./$.fails') - , shared = _dereq_('./$.shared') - , setToStringTag = _dereq_('./$.set-to-string-tag') - , uid = _dereq_('./$.uid') - , wks = _dereq_('./$.wks') - , keyOf = _dereq_('./$.keyof') - , $names = _dereq_('./$.get-names') - , enumKeys = _dereq_('./$.enum-keys') - , isArray = _dereq_('./$.is-array') - , anObject = _dereq_('./$.an-object') - , toIObject = _dereq_('./$.to-iobject') - , createDesc = _dereq_('./$.property-desc') - , getDesc = $.getDesc - , setDesc = $.setDesc - , _create = $.create - , getNames = $names.get - , $Symbol = global.Symbol - , $JSON = global.JSON - , _stringify = $JSON && $JSON.stringify - , setter = false - , HIDDEN = wks('_hidden') - , isEnum = $.isEnum - , SymbolRegistry = shared('symbol-registry') - , AllSymbols = shared('symbols') - , useNative = typeof $Symbol == 'function' - , ObjectProto = Object.prototype; +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 -// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 -var setSymbolDesc = DESCRIPTORS && $fails(function(){ - return _create(setDesc({}, 'a', { - get: function(){ return setDesc(this, 'a', {value: 7}).a; } - })).a != 7; -}) ? function(it, key, D){ - var protoDesc = getDesc(ObjectProto, key); - if(protoDesc)delete ObjectProto[key]; - setDesc(it, key, D); - if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc); -} : setDesc; + value = Math.abs(value) -var wrap = function(tag){ - var sym = AllSymbols[tag] = _create($Symbol.prototype); - sym._k = tag; - DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, { - configurable: true, - set: function(value){ - if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, 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 } - }); - return sym; -}; + } -var isSymbol = function(it){ - return typeof it == 'symbol'; -}; + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -var $defineProperty = function defineProperty(it, key, D){ - if(D && has(AllSymbols, key)){ - if(!D.enumerable){ - if(!has(it, HIDDEN))setDesc(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; - D = _create(D, {enumerable: createDesc(0, false)}); - } return setSymbolDesc(it, key, D); - } return setDesc(it, key, D); -}; -var $defineProperties = function defineProperties(it, P){ - anObject(it); - var keys = enumKeys(P = toIObject(P)) - , i = 0 - , l = keys.length - , key; - while(l > i)$defineProperty(it, key = keys[i++], P[key]); - return it; -}; -var $create = function create(it, P){ - return P === undefined ? _create(it) : $defineProperties(_create(it), P); -}; -var $propertyIsEnumerable = function propertyIsEnumerable(key){ - var E = isEnum.call(this, key); - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] - ? E : true; -}; -var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ - var D = getDesc(it = toIObject(it), key); - if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; - return D; -}; -var $getOwnPropertyNames = function getOwnPropertyNames(it){ - var names = getNames(toIObject(it)) - , result = [] - , i = 0 - , key; - while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); - return result; -}; -var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ - var names = getNames(toIObject(it)) - , result = [] - , i = 0 - , key; - while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); - return result; -}; -var $stringify = function stringify(it){ - if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined - var args = [it] - , i = 1 - , $$ = arguments - , replacer, $replacer; - while($$.length > i)args.push($$[i++]); - replacer = args[1]; - if(typeof replacer == 'function')$replacer = replacer; - if($replacer || !isArray(replacer))replacer = function(key, value){ - if($replacer)value = $replacer.call(this, key, value); - if(!isSymbol(value))return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); -}; -var buggyJSON = $fails(function(){ - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; -}); + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -// 19.4.1.1 Symbol([description]) -if(!useNative){ - $Symbol = function Symbol(){ - if(isSymbol(this))throw TypeError('Symbol is not a constructor'); - return wrap(uid(arguments.length > 0 ? arguments[0] : undefined)); - }; - redefine($Symbol.prototype, 'toString', function toString(){ - return this._k; - }); + buffer[offset + i - d] |= s * 128 +} - isSymbol = function(it){ - return it instanceof $Symbol; - }; +},{}],136:[function(_dereq_,module,exports){ +var toString = {}.toString; - $.create = $create; - $.isEnum = $propertyIsEnumerable; - $.getDesc = $getOwnPropertyDescriptor; - $.setDesc = $defineProperty; - $.setDescs = $defineProperties; - $.getNames = $names.get = $getOwnPropertyNames; - $.getSymbols = $getOwnPropertySymbols; +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; - if(DESCRIPTORS && !_dereq_('./$.library')){ - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } +},{}],137:[function(_dereq_,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } } -var symbolStatics = { - // 19.4.2.1 Symbol.for(key) - 'for': function(key){ - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(key){ - return keyOf(SymbolRegistry, key); - }, - useSetter: function(){ setter = true; }, - useSimple: function(){ setter = false; } -}; -// 19.4.2.2 Symbol.hasInstance -// 19.4.2.3 Symbol.isConcatSpreadable -// 19.4.2.4 Symbol.iterator -// 19.4.2.6 Symbol.match -// 19.4.2.8 Symbol.replace -// 19.4.2.9 Symbol.search -// 19.4.2.10 Symbol.species -// 19.4.2.11 Symbol.split -// 19.4.2.12 Symbol.toPrimitive -// 19.4.2.13 Symbol.toStringTag -// 19.4.2.14 Symbol.unscopables -$.each.call(( - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + - 'species,split,toPrimitive,toStringTag,unscopables' -).split(','), function(it){ - var sym = wks(it); - symbolStatics[it] = useNative ? sym : wrap(sym); -}); +function drainQueue() { + if (draining) { + return; + } + var timeout = setTimeout(cleanUpNextTick); + draining = true; -setter = 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; + clearTimeout(timeout); +} -$export($export.G + $export.W, {Symbol: $Symbol}); +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) { + setTimeout(drainQueue, 0); + } +}; -$export($export.S, 'Symbol', symbolStatics); +// 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 = {}; -$export($export.S + $export.F * !useNative, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols -}); +function noop() {} -// 24.3.2 JSON.stringify(value [, replacer [, space]]) -$JSON && $export($export.S + $export.F * (!useNative || buggyJSON), 'JSON', {stringify: $stringify}); +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; -// 19.4.3.5 Symbol.prototype[@@toStringTag] -setToStringTag($Symbol, 'Symbol'); -// 20.2.1.9 Math[@@toStringTag] -setToStringTag(Math, 'Math', true); -// 24.3.3 JSON[@@toStringTag] -setToStringTag(global.JSON, 'JSON', true); -},{"./$":89,"./$.an-object":58,"./$.descriptors":67,"./$.enum-keys":69,"./$.export":70,"./$.fails":71,"./$.get-names":73,"./$.global":74,"./$.has":75,"./$.is-array":81,"./$.keyof":90,"./$.library":91,"./$.property-desc":95,"./$.redefine":97,"./$.set-to-string-tag":101,"./$.shared":102,"./$.to-iobject":108,"./$.uid":111,"./$.wks":112}],130:[function(_dereq_,module,exports){ -// https://github.com/DavidBruant/Map-Set.prototype.toJSON -var $export = _dereq_('./$.export'); +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; -$export($export.P, 'Map', {toJSON: _dereq_('./$.collection-to-json')('Map')}); -},{"./$.collection-to-json":62,"./$.export":70}],131:[function(_dereq_,module,exports){ -// https://github.com/DavidBruant/Map-Set.prototype.toJSON -var $export = _dereq_('./$.export'); +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -$export($export.P, 'Set', {toJSON: _dereq_('./$.collection-to-json')('Set')}); -},{"./$.collection-to-json":62,"./$.export":70}],132:[function(_dereq_,module,exports){ -_dereq_('./es6.array.iterator'); -var Iterators = _dereq_('./$.iterators'); -Iterators.NodeList = Iterators.HTMLCollection = Iterators.Array; -},{"./$.iterators":88,"./es6.array.iterator":117}],133:[function(_dereq_,module,exports){ +},{}],138:[function(_dereq_,module,exports){ // (c) Dean McNamee , 2012. // // https://github.com/deanm/css-color-parser-js @@ -5851,161 +6804,105 @@ function parseCSSColor(css_str) { alpha]; default: return null; - } - } - - return null; -} - -try { exports.parseCSSColor = parseCSSColor } catch(e) { } - -},{}],134:[function(_dereq_,module,exports){ -"use strict" - -function dupe_array(count, value, i) { - var c = count[i]|0 - if(c <= 0) { - return [] - } - var result = new Array(c), j - if(i === count.length-1) { - for(j=0; j 0) { - return dupe_number(count|0, value) - } - break - case "object": - if(typeof (count.length) === "number") { - return dupe_array(count, value, 0) - } - break - } - return [] + return null; } -module.exports = dupe -},{}],135:[function(_dereq_,module,exports){ +try { exports.parseCSSColor = parseCSSColor } catch(e) { } + +},{}],139:[function(_dereq_,module,exports){ 'use strict'; module.exports = earcut; -function earcut(points) { +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 outerNode = linkedList(points[0], true), - node, minX, minY, maxX, maxY, x, y, size, - len = 0, - threshold = 80; + var minX, minY, maxX, maxY, x, y, size; - for (var i = 0; len < threshold && i < points.length; i++) len += points[i].length; + 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 (len >= threshold) { - node = outerNode.next; - minX = maxX = node.p[0]; - minY = maxY = node.p[1]; - do { - x = node.p[0]; - y = node.p[1]; + 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; - node = node.next; - } while (node !== outerNode); + } // minX, minY and size are later used to transform coords into integers for z-order calculation size = Math.max(maxX - minX, maxY - minY); } - if (points.length > 1) outerNode = eliminateHoles(points, outerNode); - - var triangles = []; - if (outerNode) earcutLinked(outerNode, triangles, minX, minY, size); + earcutLinked(outerNode, triangles, dim, minX, minY, size); return triangles; } // create a circular doubly linked list from polygon points in the specified winding order -function linkedList(points, clockwise) { - var sum = 0, - len = points.length, - i, j, last; +function linkedList(data, start, end, dim, clockwise) { + var i, last; - // calculate original winding order of a polygon ring - for (i = 0, j = len - 1; i < len; j = i++) { - var p1 = points[i], - p2 = points[j]; - sum += (p2[0] - p1[0]) * (p1[1] + p2[1]); + 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); } - // link points into circular doubly-linked list in the specified winding order - if (clockwise === (sum > 0)) { - for (i = 0; i < len; i++) last = insertNode(points[i], last); - } else { - for (i = len - 1; i >= 0; i--) last = insertNode(points[i], last); + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; } return last; } -function filterPoints(start) { - // eliminate colinear or duplicate points - var node = start, +// 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 (equals(node.p, node.next.p) || orient(node.prev.p, node.p, node.next.p) === 0) { - - node.prev.next = node.next; - node.next.prev = node.prev; - - if (node.prevZ) node.prevZ.nextZ = node.nextZ; - if (node.nextZ) node.nextZ.prevZ = node.prevZ; - - node = start = node.prev; - - if (node === node.next) return null; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; again = true; } else { - node = node.next; + p = p.next; } - } while (again || node !== start); + } while (again || p !== end); - return start; + return end; } -function earcutLinked(ear, triangles, minX, minY, size, secondPass) { - ear = filterPoints(ear); +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { if (!ear) return; - if (!secondPass && minX !== undefined) indexCurve(ear, minX, minY, size); + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); var stop = ear, prev, next; @@ -6015,15 +6912,15 @@ function earcutLinked(ear, triangles, minX, minY, size, secondPass) { prev = ear.prev; next = ear.next; - if (isEar(ear, minX, minY, size)) { - triangles.push(prev.p, ear.p, next.p); - - next.prev = prev; - prev.next = next; + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); - if (ear.prevZ) ear.prevZ.nextZ = ear.nextZ; - if (ear.nextZ) ear.nextZ.prevZ = ear.prevZ; + removeNode(ear); + // skipping the next vertice leads to less sliver triangles ear = next.next; stop = next.next; @@ -6032,133 +6929,130 @@ function earcutLinked(ear, triangles, minX, minY, size, secondPass) { ear = next; + // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { - // if we can't find any more ears, try filtering points and cutting again - if (!secondPass) earcutLinked(ear, triangles, minX, minY, size, true); - // if this didn't work, try splitting the remaining polygon into two - else splitEarcut(ear, triangles, minX, minY, size); + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 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, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + break; } } } -function isEar(ear, minX, minY, size) { +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; - var a = ear.prev.p, - b = ear.p, - c = ear.next.p, - - ax = a[0], bx = b[0], cx = c[0], - ay = a[1], by = b[1], cy = c[1], - - abd = ax * by - ay * bx, - acd = ax * cy - ay * cx, - cbd = cx * by - cy * bx, - A = abd - acd - cbd; - - if (A <= 0) return false; // reflex, can't be an ear + 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; - var cay = cy - ay, - acx = ax - cx, - aby = ay - by, - bax = bx - ax, - p, px, py, s, t, k, node; + 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; + } - // if we use z-order curve hashing, iterate through the curve - if (minX !== undefined) { + return true; +} - // triangle bbox; min & max are calculated like this for speed - var minTX = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), - minTY = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), - maxTX = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), - maxTY = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy), +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; - // z-order range for the current triangle bbox; - minZ = zOrder(minTX, minTY, minX, minY, size), - maxZ = zOrder(maxTX, maxTY, minX, minY, size); + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - // first look for points inside the triangle in increasing z-order - node = ear.nextZ; + // 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); - while (node && node.z <= maxZ) { - p = node.p; - node = node.nextZ; - if (p === a || p === c) continue; + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); - px = p[0]; - py = p[1]; + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; - s = cay * px + acx * py - acd; - if (s >= 0) { - t = aby * px + bax * py + abd; - if (t >= 0) { - k = A - s - t; - if ((k >= 0) && ((s && t) || (s && k) || (t && k))) return false; - } - } - } + while (p && p.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.nextZ; + } - // then look for points in decreasing z-order - node = ear.prevZ; + // then look for points in decreasing z-order + p = ear.prevZ; - while (node && node.z >= minZ) { - p = node.p; - node = node.prevZ; - if (p === a || p === c) continue; + 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; + } - px = p[0]; - py = p[1]; + return true; +} - s = cay * px + acx * py - acd; - if (s >= 0) { - t = aby * px + bax * py + abd; - if (t >= 0) { - k = A - s - t; - if ((k >= 0) && ((s && t) || (s && k) || (t && k))) return false; - } - } - } +// 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 we don't use z-order curve hash, simply iterate through all other points - } else { - node = ear.next.next; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - while (node !== ear.prev) { - p = node.p; - node = node.next; + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); - px = p[0]; - py = p[1]; + // remove two nodes involved + removeNode(p); + removeNode(p.next); - s = cay * px + acx * py - acd; - if (s >= 0) { - t = aby * px + bax * py + abd; - if (t >= 0) { - k = A - s - t; - if ((k >= 0) && ((s && t) || (s && k) || (t && k))) return false; - } - } + p = start = b; } - } + p = p.next; + } while (p !== start); - return true; + return p; } -function splitEarcut(start, triangles, minX, minY, size) { - // find a valid diagonal that divides the polygon into two +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // 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 (isValidDiagonal(a, b)) { + 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, minX, minY, size); - earcutLinked(c, triangles, minX, minY, size); + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); return; } b = b.next; @@ -6167,118 +7061,116 @@ function splitEarcut(start, triangles, minX, minY, size) { } while (a !== start); } -function eliminateHoles(points, outerNode) { - var len = points.length; +// 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; - var queue = []; - for (var i = 1; i < len; i++) { - var list = filterPoints(linkedList(points[i], false)); - if (list) queue.push(getLeftmost(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 = filterPoints(outerNode, outerNode.next); } return outerNode; } -function eliminateHole(holeNode, outerNode) { - outerNode = findHoleBridge(holeNode, outerNode); - if (outerNode) splitPolygon(holeNode, 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(holeNode, outerNode) { - var node = outerNode, - p = holeNode.p, - px = p[0], - py = p[1], - qMax = -Infinity, - mNode, a, b; +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 { - a = node.p; - b = node.next.p; - - if (py <= a[1] && py >= b[1]) { - var qx = a[0] + (py - a[1]) * (b[0] - a[0]) / (b[1] - a[1]); - if (qx <= px && qx > qMax) { - qMax = qx; - mNode = a[0] < b[0] ? node : node.next; + if (hy <= p.y && hy >= p.next.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; } } - node = node.next; - } while (node !== outerNode); + p = p.next; + } while (p !== outerNode); - if (!mNode) return null; + if (!m) return null; - // look for points strictly inside the triangle of hole point, segment intersection and endpoint; + 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 bx = mNode.p[0], - by = mNode.p[1], - pbd = px * by - py * bx, - pcd = px * py - py * qMax, - cpy = py - py, - pcx = px - qMax, - pby = py - by, - bpx = bx - px, - A = pbd - pcd - (qMax * by - py * bx), - sign = A <= 0 ? -1 : 1, - stop = mNode, + var stop = m, + mx = m.x, + my = m.y, tanMin = Infinity, - mx, my, amx, s, t, tan; - - node = mNode.next; + tan; - while (node !== stop) { + p = m.next; - mx = node.p[0]; - my = node.p[1]; - amx = px - mx; + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - if (amx >= 0 && mx >= bx) { - s = (cpy * mx + pcx * my - pcd) * sign; - if (s >= 0) { - t = (pby * mx + bpx * my + pbd) * sign; + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential - if (t >= 0 && A * sign - s - t >= 0) { - tan = Math.abs(py - my) / amx; // tangential - if (tan < tanMin && locallyInside(node, holeNode)) { - mNode = node; - tanMin = tan; - } - } + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; } } - node = node.next; + p = p.next; } - return mNode; + return m; } +// interlink polygon nodes in z-order function indexCurve(start, minX, minY, size) { - var node = start; - + var p = start; do { - node.z = node.z || zOrder(node.p[0], node.p[1], minX, minY, size); - node.prevZ = node.prev; - node.nextZ = node.next; - node = node.next; - } while (node !== start); + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); - node.prevZ.nextZ = null; - node.prevZ = null; + p.prevZ.nextZ = null; + p.prevZ = null; - sortLinked(node); + sortLinked(p); } // Simon Tatham's linked list merge sort algorithm @@ -6287,7 +7179,7 @@ function sortLinked(list) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; - while (true) { + do { p = list; list = null; tail = null; @@ -6336,23 +7228,24 @@ function sortLinked(list) { } tail.nextZ = null; + inSize *= 2; - if (numMerges <= 1) return list; + } while (numMerges > 1); - inSize *= 2; - } + return list; } -// z-order of a point given coords and bbox +// z-order of a point given coords and size of the data bounding box function zOrder(x, y, minX, minY, size) { - // coords are transformed into (0..1000) integer range - x = 1000 * (x - minX) / size; + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; - y = 1000 * (y - minY) / size; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; @@ -6361,89 +7254,88 @@ function zOrder(x, y, minX, minY, size) { return x | (y << 1); } +// find the leftmost node of a polygon ring function getLeftmost(start) { - var node = start, + var p = start, leftmost = start; do { - if (node.p[0] < leftmost.p[0]) leftmost = node; - node = node.next; - } while (node !== start); + 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 !intersectsPolygon(a, a.p, b.p) && - locallyInside(a, b) && locallyInside(b, a) && - middleInside(a, a.p, b.p); + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); } -// winding order of triangle formed by 3 given points -function orient(p, q, r) { - var o = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); - return o > 0 ? 1 : - o < 0 ? -1 : 0; +// 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[0] === p2[0] && p1[1] === p2[1]; + return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect function intersects(p1, q1, p2, q2) { - return orient(p1, q1, p2) !== orient(p1, q1, q2) && - orient(p2, q2, p1) !== orient(p2, q2, q1); + 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(start, a, b) { - var node = start; +function intersectsPolygon(a, b) { + var p = a; do { - var p1 = node.p, - p2 = node.next.p; - - if (p1 !== a && p2 !== a && p1 !== b && p2 !== b && intersects(p1, p2, a, b)) return true; - - node = node.next; - } while (node !== start); + 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 orient(a.prev.p, a.p, a.next.p) === -1 ? - orient(a.p, b.p, a.next.p) !== -1 && orient(a.p, a.prev.p, b.p) !== -1 : - orient(a.p, b.p, a.prev.p) === -1 || orient(a.p, a.next.p, b.p) === -1; + 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(start, a, b) { - var node = start, +function middleInside(a, b) { + var p = a, inside = false, - px = (a[0] + b[0]) / 2, - py = (a[1] + b[1]) / 2; + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; do { - var p1 = node.p, - p2 = node.next.p; - - if (((p1[1] > py) !== (p2[1] > py)) && - (px < (p2[0] - p1[0]) * (py - p1[1]) / (p2[1] - p1[1]) + p1[0])) inside = !inside; - - node = node.next; - } while (node !== start); + if (((p.y > py) !== (p.next.y > py)) && (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; } -function compareX(a, b) { - return a.p[0] - b.p[0]; -} - -// split the polygon vertices circular doubly-linked linked list into two +// 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.p), - b2 = new Node(b.p), + 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; @@ -6459,36 +7351,123 @@ function splitPolygon(a, b) { bp.next = b2; b2.prev = bp; - return a2; + return b2; } -function insertNode(point, last) { - var node = new Node(point); +// 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) { - node.prev = node; - node.next = node; + p.prev = p; + p.next = p; } else { - node.next = last.next; - node.prev = last; - last.next.prev = node; - last.next = node; + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; } - return node; + 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(p) { - this.p = p; +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; } -},{}],136:[function(_dereq_,module,exports){ +// 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; +}; + +},{}],140:[function(_dereq_,module,exports){ +(function(){var m=!!document.addEventListener;function n(a,b){m?a.addEventListener("scroll",b,!1):a.attachEvent("scroll",b)}function v(a){document.body?a():m?document.addEventListener("DOMContentLoaded",a):document.attachEvent("onreadystatechange",function(){"interactive"!=document.readyState&&"complete"!=document.readyState||a()})};function w(a){this.a=document.createElement("div");this.a.setAttribute("aria-hidden","true");this.a.appendChild(document.createTextNode(a));this.b=document.createElement("span");this.c=document.createElement("span");this.h=document.createElement("span");this.f=document.createElement("span");this.g=-1;this.b.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";this.c.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;"; +this.f.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";this.h.style.cssText="display:inline-block;width:200%;height:200%;font-size:16px;max-width:none;";this.b.appendChild(this.h);this.c.appendChild(this.f);this.a.appendChild(this.b);this.a.appendChild(this.c)} +function y(a,b){a.a.style.cssText="max-width:none;min-width:20px;min-height:20px;display:inline-block;overflow:hidden;position:absolute;width:auto;margin:0;padding:0;top:-999px;left:-999px;white-space:nowrap;font:"+b+";"}function z(a){var b=a.a.offsetWidth,c=b+100;a.f.style.width=c+"px";a.c.scrollLeft=c;a.b.scrollLeft=a.b.scrollWidth+100;return a.g!==b?(a.g=b,!0):!1}function A(a,b){function c(){var a=l;z(a)&&null!==a.a.parentNode&&b(a.g)}var l=a;n(a.b,c);n(a.c,c);z(a)};function B(a,b){var c=b||{};this.family=a;this.style=c.style||"normal";this.weight=c.weight||"normal";this.stretch=c.stretch||"normal"}var C=null,D=null,H=!!window.FontFace;function I(){if(null===D){var a=document.createElement("div");try{a.style.font="condensed 100px sans-serif"}catch(b){}D=""!==a.style.font}return D}function J(a,b){return[a.style,a.weight,I()?a.stretch:"","100px",b].join(" ")} +B.prototype.load=function(a,b){var c=this,l=a||"BESbswy",x=b||3E3,E=(new Date).getTime();return new Promise(function(a,b){if(H){var K=new Promise(function(a,b){var e=J(c,c.family);if(document.fonts.check(e,l))a();else{var f=function(){(new Date).getTime()-E>=x?b():document.fonts.load(e,l).then(function(c){1<=c.length?a():setTimeout(f,25)},function(){b()})};f()}}),L=new Promise(function(a,c){setTimeout(c,x)});Promise.race([L,K]).then(function(){a(c)},function(){b(c)})}else v(function(){function q(){var b; +if(b=-1!=g&&-1!=h||-1!=g&&-1!=k||-1!=h&&-1!=k)(b=g!=h&&g!=k&&h!=k)||(null===C&&(b=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(window.navigator.userAgent),C=!!b&&(536>parseInt(b[1],10)||536===parseInt(b[1],10)&&11>=parseInt(b[2],10))),b=C&&(g==r&&h==r&&k==r||g==t&&h==t&&k==t||g==u&&h==u&&k==u)),b=!b;b&&(null!==d.parentNode&&d.parentNode.removeChild(d),clearTimeout(G),a(c))}function F(){if((new Date).getTime()-E>=x)null!==d.parentNode&&d.parentNode.removeChild(d),b(c);else{var a=document.hidden;if(!0=== +a||void 0===a)g=e.a.offsetWidth,h=f.a.offsetWidth,k=p.a.offsetWidth,q();G=setTimeout(F,50)}}var e=new w(l),f=new w(l),p=new w(l),g=-1,h=-1,k=-1,r=-1,t=-1,u=-1,d=document.createElement("div"),G=0;d.dir="ltr";y(e,J(c,"sans-serif"));y(f,J(c,"serif"));y(p,J(c,"monospace"));d.appendChild(e.a);d.appendChild(f.a);d.appendChild(p.a);document.body.appendChild(d);r=e.a.offsetWidth;t=f.a.offsetWidth;u=p.a.offsetWidth;F();A(e,function(a){g=a;q()});y(e,J(c,'"'+c.family+'",sans-serif'));A(f,function(a){h=a;q()}); +y(f,J(c,'"'+c.family+'",serif'));A(p,function(a){k=a;q()});y(p,J(c,'"'+c.family+'",monospace'))})})};window.FontFaceObserver=B;window.FontFaceObserver.prototype.check=window.FontFaceObserver.prototype.load=B.prototype.load;"undefined"!==typeof module&&(module.exports=window.FontFaceObserver);}()); + +},{}],141:[function(_dereq_,module,exports){ 'use strict'; module.exports = clip; @@ -6641,7 +7620,7 @@ function newSlice(slices, slice, area, dist) { return []; } -},{}],137:[function(_dereq_,module,exports){ +},{}],142:[function(_dereq_,module,exports){ 'use strict'; module.exports = convert; @@ -6787,7 +7766,7 @@ function calcRingBBox(min, max, points) { } } -},{"./simplify":139}],138:[function(_dereq_,module,exports){ +},{"./simplify":144}],143:[function(_dereq_,module,exports){ 'use strict'; module.exports = geojsonvt; @@ -7054,7 +8033,7 @@ function isClippedSquare(tile, extent, buffer) { return true; } -},{"./clip":136,"./convert":137,"./tile":140,"./wrap":141}],139:[function(_dereq_,module,exports){ +},{"./clip":141,"./convert":142,"./tile":145,"./wrap":146}],144:[function(_dereq_,module,exports){ 'use strict'; module.exports = simplify; @@ -7130,7 +8109,7 @@ function getSqSegDist(p, a, b) { return dx * dx + dy * dy; } -},{}],140:[function(_dereq_,module,exports){ +},{}],145:[function(_dereq_,module,exports){ 'use strict'; module.exports = createTile; @@ -7217,7 +8196,7 @@ function addFeature(tile, feature, tolerance, noSimplify) { } } -},{}],141:[function(_dereq_,module,exports){ +},{}],146:[function(_dereq_,module,exports){ 'use strict'; var clip = _dereq_('./clip'); @@ -7280,7 +8259,7 @@ function shiftCoords(points, offset) { return newPoints; } -},{"./clip":136}],142:[function(_dereq_,module,exports){ +},{"./clip":141}],147:[function(_dereq_,module,exports){ module.exports = invert /** @@ -7319,7 +8298,7 @@ function invert(out, a) { return out } -},{}],143:[function(_dereq_,module,exports){ +},{}],148:[function(_dereq_,module,exports){ module.exports = normalFromMat4 /** @@ -7376,7 +8355,7 @@ function normalFromMat4(out, a) { return out } -},{}],144:[function(_dereq_,module,exports){ +},{}],149:[function(_dereq_,module,exports){ module.exports = copy; /** @@ -7405,7 +8384,7 @@ function copy(out, a) { out[15] = a[15]; return out; }; -},{}],145:[function(_dereq_,module,exports){ +},{}],150:[function(_dereq_,module,exports){ module.exports = identity; /** @@ -7433,7 +8412,7 @@ function identity(out) { out[15] = 1; return out; }; -},{}],146:[function(_dereq_,module,exports){ +},{}],151:[function(_dereq_,module,exports){ var identity = _dereq_('./identity'); module.exports = lookAt; @@ -7524,7 +8503,7 @@ function lookAt(out, eye, center, up) { return out; }; -},{"./identity":145}],147:[function(_dereq_,module,exports){ +},{"./identity":150}],152:[function(_dereq_,module,exports){ module.exports = multiply; /** @@ -7567,7 +8546,7 @@ function multiply(out, a, b) { out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; return out; }; -},{}],148:[function(_dereq_,module,exports){ +},{}],153:[function(_dereq_,module,exports){ module.exports = perspective; /** @@ -7601,7 +8580,7 @@ function perspective(out, fovy, aspect, near, far) { out[15] = 0; return out; }; -},{}],149:[function(_dereq_,module,exports){ +},{}],154:[function(_dereq_,module,exports){ module.exports = scale; /** @@ -7633,7 +8612,7 @@ function scale(out, a, v) { out[15] = a[15]; return out; }; -},{}],150:[function(_dereq_,module,exports){ +},{}],155:[function(_dereq_,module,exports){ module.exports = translate; /** @@ -7650,178 +8629,57 @@ function translate(out, a, v) { 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; -}; -},{}],151:[function(_dereq_,module,exports){ -module.exports = parseErrors - -function parseErrors(log) { - log = String(log) - - var logs = [] - var result - - while (result = log.match(/ERROR\:([^\n]+)/)) { - log = log.slice(result.index + 1) - - var line = result[1].trim() - var seps = line.split(':') - var emsg = seps.slice(2).join(':').trim() - var file = parseInt(seps[0], 10) - var line = parseInt(seps[1], 10) - - logs.push({ - message: emsg - , file: file - , line: line - }) - } - - return logs -} - -},{}],152:[function(_dereq_,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 + 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 { - 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) {} + 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]; - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + 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; - buffer[offset + i - d] |= s * 128 -} + 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]; + } -},{}],153:[function(_dereq_,module,exports){ + return out; +}; +},{}],156:[function(_dereq_,module,exports){ +module.exports = parseErrors -/** - * isArray - */ +function parseErrors(log) { + log = String(log) -var isArray = Array.isArray; + var logs = [] + var result -/** - * toString - */ + while (result = log.match(/ERROR\:([^\n]+)/)) { + log = log.slice(result.index + 1) -var str = Object.prototype.toString; + var line = result[1].trim() + var seps = line.split(':') + var emsg = seps.slice(2).join(':').trim() + var file = parseInt(seps[0], 10) + var line = parseInt(seps[1], 10) -/** - * Whether or not the given `val` - * is an array. - * - * example: - * - * isArray([]); - * // > true - * isArray(arguments); - * // > false - * isArray(''); - * // > false - * - * @param {mixed} val - * @return {bool} - */ + logs.push({ + message: emsg + , file: file + , line: line + }) + } -module.exports = isArray || function (val) { - return !! val && '[object Array]' == str.call(val); -}; + return logs +} -},{}],154:[function(_dereq_,module,exports){ +},{}],157:[function(_dereq_,module,exports){ 'use strict'; @@ -7830,7 +8688,7 @@ var yaml = _dereq_('./lib/js-yaml.js'); module.exports = yaml; -},{"./lib/js-yaml.js":155}],155:[function(_dereq_,module,exports){ +},{"./lib/js-yaml.js":158}],158:[function(_dereq_,module,exports){ 'use strict'; @@ -7871,7 +8729,7 @@ module.exports.parse = deprecated('parse'); module.exports.compose = deprecated('compose'); module.exports.addConstructor = deprecated('addConstructor'); -},{"./js-yaml/exception":157,"./js-yaml/loader":158,"./js-yaml/schema":160,"./js-yaml/schema/core":161,"./js-yaml/schema/default_full":162,"./js-yaml/schema/default_safe":163,"./js-yaml/schema/failsafe":164,"./js-yaml/schema/json":165,"./js-yaml/type":166}],156:[function(_dereq_,module,exports){ +},{"./js-yaml/exception":160,"./js-yaml/loader":161,"./js-yaml/schema":163,"./js-yaml/schema/core":164,"./js-yaml/schema/default_full":165,"./js-yaml/schema/default_safe":166,"./js-yaml/schema/failsafe":167,"./js-yaml/schema/json":168,"./js-yaml/type":169}],159:[function(_dereq_,module,exports){ 'use strict'; @@ -7932,7 +8790,7 @@ module.exports.repeat = repeat; module.exports.isNegativeZero = isNegativeZero; module.exports.extend = extend; -},{}],157:[function(_dereq_,module,exports){ +},{}],160:[function(_dereq_,module,exports){ // YAML error class. http://stackoverflow.com/questions/8458984 // 'use strict'; @@ -7977,7 +8835,7 @@ YAMLException.prototype.toString = function toString(compact) { module.exports = YAMLException; -},{}],158:[function(_dereq_,module,exports){ +},{}],161:[function(_dereq_,module,exports){ 'use strict'; /*eslint-disable max-len,no-use-before-define*/ @@ -9565,7 +10423,7 @@ module.exports.load = load; module.exports.safeLoadAll = safeLoadAll; module.exports.safeLoad = safeLoad; -},{"./common":156,"./exception":157,"./mark":159,"./schema/default_full":162,"./schema/default_safe":163}],159:[function(_dereq_,module,exports){ +},{"./common":159,"./exception":160,"./mark":162,"./schema/default_full":165,"./schema/default_safe":166}],162:[function(_dereq_,module,exports){ 'use strict'; @@ -9643,7 +10501,7 @@ Mark.prototype.toString = function toString(compact) { module.exports = Mark; -},{"./common":156}],160:[function(_dereq_,module,exports){ +},{"./common":159}],163:[function(_dereq_,module,exports){ 'use strict'; /*eslint-disable max-len*/ @@ -9749,7 +10607,7 @@ Schema.create = function createSchema() { module.exports = Schema; -},{"./common":156,"./exception":157,"./type":166}],161:[function(_dereq_,module,exports){ +},{"./common":159,"./exception":160,"./type":169}],164:[function(_dereq_,module,exports){ // Standard YAML's Core schema. // http://www.yaml.org/spec/1.2/spec.html#id2804923 // @@ -9769,7 +10627,7 @@ module.exports = new Schema({ ] }); -},{"../schema":160,"./json":165}],162:[function(_dereq_,module,exports){ +},{"../schema":163,"./json":168}],165:[function(_dereq_,module,exports){ // JS-YAML's default schema for `load` function. // It is not described in the YAML specification. // @@ -9796,7 +10654,7 @@ module.exports = Schema.DEFAULT = new Schema({ ] }); -},{"../schema":160,"../type/js/function":171,"../type/js/regexp":172,"../type/js/undefined":173,"./default_safe":163}],163:[function(_dereq_,module,exports){ +},{"../schema":163,"../type/js/function":174,"../type/js/regexp":175,"../type/js/undefined":176,"./default_safe":166}],166:[function(_dereq_,module,exports){ // JS-YAML's default schema for `safeLoad` function. // It is not described in the YAML specification. // @@ -9826,7 +10684,7 @@ module.exports = new Schema({ ] }); -},{"../schema":160,"../type/binary":167,"../type/merge":175,"../type/omap":177,"../type/pairs":178,"../type/set":180,"../type/timestamp":182,"./core":161}],164:[function(_dereq_,module,exports){ +},{"../schema":163,"../type/binary":170,"../type/merge":178,"../type/omap":180,"../type/pairs":181,"../type/set":183,"../type/timestamp":185,"./core":164}],167:[function(_dereq_,module,exports){ // Standard YAML's Failsafe schema. // http://www.yaml.org/spec/1.2/spec.html#id2802346 @@ -9845,7 +10703,7 @@ module.exports = new Schema({ ] }); -},{"../schema":160,"../type/map":174,"../type/seq":179,"../type/str":181}],165:[function(_dereq_,module,exports){ +},{"../schema":163,"../type/map":177,"../type/seq":182,"../type/str":184}],168:[function(_dereq_,module,exports){ // Standard YAML's JSON schema. // http://www.yaml.org/spec/1.2/spec.html#id2803231 // @@ -9872,7 +10730,7 @@ module.exports = new Schema({ ] }); -},{"../schema":160,"../type/bool":168,"../type/float":169,"../type/int":170,"../type/null":176,"./failsafe":164}],166:[function(_dereq_,module,exports){ +},{"../schema":163,"../type/bool":171,"../type/float":172,"../type/int":173,"../type/null":179,"./failsafe":167}],169:[function(_dereq_,module,exports){ 'use strict'; var YAMLException = _dereq_('./exception'); @@ -9935,7 +10793,7 @@ function Type(tag, options) { module.exports = Type; -},{"./exception":157}],167:[function(_dereq_,module,exports){ +},{"./exception":160}],170:[function(_dereq_,module,exports){ 'use strict'; /*eslint-disable no-bitwise*/ @@ -10067,7 +10925,7 @@ module.exports = new Type('tag:yaml.org,2002:binary', { represent: representYamlBinary }); -},{"../type":166,"buffer":37}],168:[function(_dereq_,module,exports){ +},{"../type":169,"buffer":132}],171:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10104,7 +10962,7 @@ module.exports = new Type('tag:yaml.org,2002:bool', { defaultStyle: 'lowercase' }); -},{"../type":166}],169:[function(_dereq_,module,exports){ +},{"../type":169}],172:[function(_dereq_,module,exports){ 'use strict'; var common = _dereq_('../common'); @@ -10211,7 +11069,7 @@ module.exports = new Type('tag:yaml.org,2002:float', { defaultStyle: 'lowercase' }); -},{"../common":156,"../type":166}],170:[function(_dereq_,module,exports){ +},{"../common":159,"../type":169}],173:[function(_dereq_,module,exports){ 'use strict'; var common = _dereq_('../common'); @@ -10381,7 +11239,7 @@ module.exports = new Type('tag:yaml.org,2002:int', { } }); -},{"../common":156,"../type":166}],171:[function(_dereq_,module,exports){ +},{"../common":159,"../type":169}],174:[function(_dereq_,module,exports){ 'use strict'; var esprima; @@ -10467,7 +11325,7 @@ module.exports = new Type('tag:yaml.org,2002:js/function', { represent: representJavascriptFunction }); -},{"../../type":166}],172:[function(_dereq_,module,exports){ +},{"../../type":169}],175:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../../type'); @@ -10529,7 +11387,7 @@ module.exports = new Type('tag:yaml.org,2002:js/regexp', { represent: representJavascriptRegExp }); -},{"../../type":166}],173:[function(_dereq_,module,exports){ +},{"../../type":169}],176:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../../type'); @@ -10559,7 +11417,7 @@ module.exports = new Type('tag:yaml.org,2002:js/undefined', { represent: representJavascriptUndefined }); -},{"../../type":166}],174:[function(_dereq_,module,exports){ +},{"../../type":169}],177:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10569,7 +11427,7 @@ module.exports = new Type('tag:yaml.org,2002:map', { construct: function (data) { return data !== null ? data : {}; } }); -},{"../type":166}],175:[function(_dereq_,module,exports){ +},{"../type":169}],178:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10583,7 +11441,7 @@ module.exports = new Type('tag:yaml.org,2002:merge', { resolve: resolveYamlMerge }); -},{"../type":166}],176:[function(_dereq_,module,exports){ +},{"../type":169}],179:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10619,7 +11477,7 @@ module.exports = new Type('tag:yaml.org,2002:null', { defaultStyle: 'lowercase' }); -},{"../type":166}],177:[function(_dereq_,module,exports){ +},{"../type":169}],180:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10665,7 +11523,7 @@ module.exports = new Type('tag:yaml.org,2002:omap', { construct: constructYamlOmap }); -},{"../type":166}],178:[function(_dereq_,module,exports){ +},{"../type":169}],181:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10720,7 +11578,7 @@ module.exports = new Type('tag:yaml.org,2002:pairs', { construct: constructYamlPairs }); -},{"../type":166}],179:[function(_dereq_,module,exports){ +},{"../type":169}],182:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10730,7 +11588,7 @@ module.exports = new Type('tag:yaml.org,2002:seq', { construct: function (data) { return data !== null ? data : []; } }); -},{"../type":166}],180:[function(_dereq_,module,exports){ +},{"../type":169}],183:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10761,7 +11619,7 @@ module.exports = new Type('tag:yaml.org,2002:set', { construct: constructYamlSet }); -},{"../type":166}],181:[function(_dereq_,module,exports){ +},{"../type":169}],184:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10771,7 +11629,7 @@ module.exports = new Type('tag:yaml.org,2002:str', { construct: function (data) { return data !== null ? data : ''; } }); -},{"../type":166}],182:[function(_dereq_,module,exports){ +},{"../type":169}],185:[function(_dereq_,module,exports){ 'use strict'; var Type = _dereq_('../type'); @@ -10854,166 +11712,7 @@ module.exports = new Type('tag:yaml.org,2002:timestamp', { represent: representYamlTimestamp }); -},{"../type":166}],183:[function(_dereq_,module,exports){ -/* -* loglevel - https://github.com/pimterry/loglevel -* -* Copyright (c) 2013 Tim Perry -* Licensed under the MIT license. -*/ -(function (root, definition) { - if (typeof module === 'object' && module.exports && typeof _dereq_ === 'function') { - module.exports = definition(); - } else if (typeof define === 'function' && typeof define.amd === 'object') { - define(definition); - } else { - root.log = definition(); - } -}(this, function () { - var self = {}; - var noop = function() {}; - var undefinedType = "undefined"; - - function realMethod(methodName) { - if (typeof console === undefinedType) { - return false; // We can't build a real method without a console to log to - } else if (console[methodName] !== undefined) { - return bindMethod(console, methodName); - } else if (console.log !== undefined) { - return bindMethod(console, 'log'); - } else { - return noop; - } - } - - function bindMethod(obj, methodName) { - var method = obj[methodName]; - if (typeof method.bind === 'function') { - return method.bind(obj); - } else { - try { - return Function.prototype.bind.call(method, obj); - } catch (e) { - // Missing bind shim or IE8 + Modernizr, fallback to wrapping - return function() { - return Function.prototype.apply.apply(method, [obj, arguments]); - }; - } - } - } - - function enableLoggingWhenConsoleArrives(methodName, level) { - return function () { - if (typeof console !== undefinedType) { - replaceLoggingMethods(level); - self[methodName].apply(self, arguments); - } - }; - } - - var logMethods = [ - "trace", - "debug", - "info", - "warn", - "error" - ]; - - function replaceLoggingMethods(level) { - for (var i = 0; i < logMethods.length; i++) { - var methodName = logMethods[i]; - self[methodName] = (i < level) ? noop : self.methodFactory(methodName, level); - } - } - - function persistLevelIfPossible(levelNum) { - var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); - - // Use localStorage if available - try { - window.localStorage['loglevel'] = levelName; - return; - } catch (ignore) {} - - // Use session cookie as fallback - try { - window.document.cookie = "loglevel=" + levelName + ";"; - } catch (ignore) {} - } - - function loadPersistedLevel() { - var storedLevel; - - try { - storedLevel = window.localStorage['loglevel']; - } catch (ignore) {} - - if (typeof storedLevel === undefinedType) { - try { - storedLevel = /loglevel=([^;]+)/.exec(window.document.cookie)[1]; - } catch (ignore) {} - } - - if (self.levels[storedLevel] === undefined) { - storedLevel = "WARN"; - } - - self.setLevel(self.levels[storedLevel]); - } - - /* - * - * Public API - * - */ - - self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, - "ERROR": 4, "SILENT": 5}; - - self.methodFactory = function (methodName, level) { - return realMethod(methodName) || - enableLoggingWhenConsoleArrives(methodName, level); - }; - - self.setLevel = function (level) { - if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) { - level = self.levels[level.toUpperCase()]; - } - if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) { - persistLevelIfPossible(level); - replaceLoggingMethods(level); - if (typeof console === undefinedType && level < self.levels.SILENT) { - return "No console available for logging"; - } - } else { - throw "log.setLevel() called with invalid level: " + level; - } - }; - - self.enableAll = function() { - self.setLevel(self.levels.TRACE); - }; - - self.disableAll = function() { - self.setLevel(self.levels.SILENT); - }; - - // Grab the current global log variable in case of overwrite - var _log = (typeof window !== undefinedType) ? window.log : undefined; - self.noConflict = function() { - if (typeof window !== undefinedType && - window.log === self) { - window.log = _log; - } - - return self; - }; - - loadPersistedLevel(); - return self; -})); - -},{}],184:[function(_dereq_,module,exports){ +},{"../type":169}],186:[function(_dereq_,module,exports){ 'use strict'; function notNull(x) { return x != null; } @@ -11152,7 +11851,7 @@ module.exports = { parseFilter: parseFilter }; -},{}],185:[function(_dereq_,module,exports){ +},{}],187:[function(_dereq_,module,exports){ 'use strict'; // lightweight Buffer shim for pbf browser build @@ -11313,7 +12012,7 @@ function encodeString(str) { return bytes; } -},{"ieee754":152}],186:[function(_dereq_,module,exports){ +},{"ieee754":189}],188:[function(_dereq_,module,exports){ (function (global){ 'use strict'; @@ -11729,240 +12428,20 @@ Pbf.prototype = { } }; -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]); } - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9wYmYvaW5kZXguanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtB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gc2ZpeGVkMzJcblxudmFyIFNISUZUX0xFRlRfMzIgPSAoMSA8PCAxNikgKiAoMSA8PCAxNiksXG4gICAgU0hJRlRfUklHSFRfMzIgPSAxIC8gU0hJRlRfTEVGVF8zMixcbiAgICBQT1dfMl82MyA9IE1hdGgucG93KDIsIDYzKTtcblxuUGJmLnByb3RvdHlwZSA9IHtcblxuICAgIGRlc3Ryb3k6IGZ1bmN0aW9uKCkge1xuICAgICAgICB0aGlzLmJ1ZiA9IG51bGw7XG4gICAgfSxcblxuICAgIC8vID09PSBSRUFESU5HID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG5cbiAgICByZWFkRmllbGRzOiBmdW5jdGlvbihyZWFkRmllbGQsIHJlc3VsdCwgZW5kKSB7XG4gICAgICAgIGVuZCA9IGVuZCB8fCB0aGlzLmxlbmd0aDtcblxuICAgICAgICB3aGlsZSAodGhpcy5wb3MgPCBlbmQpIHtcbiAgICAgICAgICAgIHZhciB2YWwgPSB0aGlzLnJlYWRWYXJpbnQoKSxcbiAgICAgICAgICAgICAgICB0YWcgPSB2YWwgPj4gMyxcbiAgICAgICAgICAgICAgICBzdGFydFBvcyA9IHRoaXMucG9zO1xuXG4gICAgICAgICAgICByZWFkRmllbGQodGFnLCByZXN1bHQsIHRoaXMpO1xuXG4gICAgICAgICAgICBpZiAodGhpcy5wb3MgPT09IHN0YXJ0UG9zKSB0aGlzLnNraXAodmFsKTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gcmVzdWx0O1xuICAgIH0sXG5cbiAgICByZWFkTWVzc2FnZTogZnVuY3Rpb24ocmVhZEZpZWxkLCByZXN1bHQpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMucmVhZEZpZWxkcyhyZWFkRmllbGQsIHJlc3VsdCwgdGhpcy5yZWFkVmFyaW50KCkgKyB0aGlzLnBvcyk7XG4gICAgfSxcblxuICAgIHJlYWRGaXhlZDMyOiBmdW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W5ndGg7IGkrKykgcGJmLndyaXRlRml4ZWQ2NChhcnJbaV0pOyAgfVxuZnVuY3Rpb24gd3JpdGVQYWNrZWRTRml4ZWQ2NChhcnIsIHBiZikgeyBmb3IgKHZhciBpID0gMDsgaSA8IGFyci5sZW5ndGg7IGkrKykgcGJmLndyaXRlU0ZpeGVkNjQoYXJyW2ldKTsgfVxuIl19 -},{"./buffer":185}],187:[function(_dereq_,module,exports){ -'use strict'; - -module.exports = Point; - -function Point(x, y) { - this.x = x; - this.y = y; -} - -Point.prototype = { - clone: function() { return new Point(this.x, this.y); }, - - add: function(p) { return this.clone()._add(p); }, - sub: function(p) { return this.clone()._sub(p); }, - mult: function(k) { return this.clone()._mult(k); }, - div: function(k) { return this.clone()._div(k); }, - rotate: function(a) { return this.clone()._rotate(a); }, - matMult: function(m) { return this.clone()._matMult(m); }, - unit: function() { return this.clone()._unit(); }, - perp: function() { return this.clone()._perp(); }, - round: function() { return this.clone()._round(); }, - - mag: function() { - return Math.sqrt(this.x * this.x + this.y * this.y); - }, - - equals: function(p) { - return this.x === p.x && - this.y === p.y; - }, - - dist: function(p) { - return Math.sqrt(this.distSqr(p)); - }, - - distSqr: function(p) { - var dx = p.x - this.x, - dy = p.y - this.y; - return dx * dx + dy * dy; - }, - - angle: function() { - return Math.atan2(this.y, this.x); - }, - - angleTo: function(b) { - return Math.atan2(this.y - b.y, this.x - b.x); - }, - - 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 θ. - 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; - }, - - _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; - }, - - _round: function() { - this.x = Math.round(this.x); - this.y = Math.round(this.y); - return this; - } -}; - -// constructs Point from an array if necessary -Point.convert = function (a) { - if (a instanceof Point) { - return a; - } - if (Array.isArray(a)) { - return new Point(a[0], a[1]); - } - return a; -}; - -},{}],188:[function(_dereq_,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; - -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canMutationObserver = typeof window !== 'undefined' - && window.MutationObserver; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canSetImmediate) { - return function (f) { return window.setImmediate(f) }; - } - - var queue = []; - - if (canMutationObserver) { - var hiddenDiv = document.createElement("div"); - var observer = new MutationObserver(function () { - var queueList = queue.slice(); - queue.length = 0; - queueList.forEach(function (fn) { - fn(); - }); - }); - - observer.observe(hiddenDiv, { attributes: true }); - - return function nextTick(fn) { - if (!queue.length) { - hiddenDiv.setAttribute('yes', 'no'); - } - queue.push(fn); - }; - } - - if (canPost) { - window.addEventListener('message', function (ev) { - var source = ev.source; - if ((source === window || source === null) && ev.data === 'process-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; - } - - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; +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]); } -},{}],189:[function(_dereq_,module,exports){ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./buffer":187}],189:[function(_dereq_,module,exports){ +arguments[4][135][0].apply(exports,arguments) +},{"dup":135}],190:[function(_dereq_,module,exports){ /*! * strip-comments * @@ -12037,7 +12516,7 @@ strip.line = function(str, opts) { return str ? str.replace(re, '') : ''; }; -},{}],190:[function(_dereq_,module,exports){ +},{}],191:[function(_dereq_,module,exports){ !function() { var topojson = { version: "1.6.19", @@ -12492,306 +12971,88 @@ strip.line = function(str, opts) { }; heap.pop = function() { - if (size <= 0) return; - var removed = array[0], object; - if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); - return removed; - }; - - heap.remove = function(removed) { - var i = removed._, object; - if (array[i] !== removed) return; // invalid request - if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); - return i; - }; - - function up(object, i) { - while (i > 0) { - var j = ((i + 1) >> 1) - 1, - parent = array[j]; - if (compareArea(object, parent) >= 0) break; - array[parent._ = i] = parent; - array[object._ = i = j] = object; - } - } - - function down(object, i) { - while (true) { - var r = (i + 1) << 1, - l = r - 1, - j = i, - child = array[j]; - if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; - if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; - if (j === i) break; - array[child._ = i] = child; - array[object._ = i = j] = object; - } - } - - return heap; - } - - function transformAbsolute(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - point[0] = (x0 += point[0]) * kx + dx; - point[1] = (y0 += point[1]) * ky + dy; - }; - } - - function transformRelative(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - var x1 = (point[0] - dx) / kx | 0, - y1 = (point[1] - dy) / ky | 0; - point[0] = x1 - x0; - point[1] = y1 - y0; - x0 = x1; - y0 = y1; - }; - } - - function noop() {} - - if (typeof define === "function" && define.amd) define(topojson); - else if (typeof module === "object" && module.exports) module.exports = topojson; - else this.topojson = topojson; -}(); - -},{}],191:[function(_dereq_,module,exports){ -(function (global,Buffer){ -'use strict' - -var bits = _dereq_('bit-twiddle') -var dup = _dereq_('dup') - -//Legacy pool support -if(!global.__TYPEDARRAY_POOL) { - global.__TYPEDARRAY_POOL = { - UINT8 : dup([32, 0]) - , UINT16 : dup([32, 0]) - , UINT32 : dup([32, 0]) - , INT8 : dup([32, 0]) - , INT16 : dup([32, 0]) - , INT32 : dup([32, 0]) - , FLOAT : dup([32, 0]) - , DOUBLE : dup([32, 0]) - , DATA : dup([32, 0]) - , UINT8C : dup([32, 0]) - , BUFFER : dup([32, 0]) - } -} - -var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' -var POOL = global.__TYPEDARRAY_POOL - -//Upgrade pool -if(!POOL.UINT8C) { - POOL.UINT8C = dup([32, 0]) -} -if(!POOL.BUFFER) { - POOL.BUFFER = dup([32, 0]) -} - -//New technique: Only allocate from ArrayBufferView and Buffer -var DATA = POOL.DATA - , BUFFER = POOL.BUFFER - -exports.free = function free(array) { - if(Buffer.isBuffer(array)) { - BUFFER[bits.log2(array.length)].push(array) - } else { - if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { - array = array.buffer - } - if(!array) { - return - } - var n = array.length || array.byteLength - var log_n = bits.log2(n)|0 - DATA[log_n].push(array) - } -} - -function freeArrayBuffer(buffer) { - if(!buffer) { - return - } - var n = buffer.length || buffer.byteLength - var log_n = bits.log2(n) - DATA[log_n].push(buffer) -} - -function freeTypedArray(array) { - freeArrayBuffer(array.buffer) -} - -exports.freeUint8 = -exports.freeUint16 = -exports.freeUint32 = -exports.freeInt8 = -exports.freeInt16 = -exports.freeInt32 = -exports.freeFloat32 = -exports.freeFloat = -exports.freeFloat64 = -exports.freeDouble = -exports.freeUint8Clamped = -exports.freeDataView = freeTypedArray - -exports.freeArrayBuffer = freeArrayBuffer - -exports.freeBuffer = function freeBuffer(array) { - BUFFER[bits.log2(array.length)].push(array) -} - -exports.malloc = function malloc(n, dtype) { - if(dtype === undefined || dtype === 'arraybuffer') { - return mallocArrayBuffer(n) - } else { - switch(dtype) { - case 'uint8': - return mallocUint8(n) - case 'uint16': - return mallocUint16(n) - case 'uint32': - return mallocUint32(n) - case 'int8': - return mallocInt8(n) - case 'int16': - return mallocInt16(n) - case 'int32': - return mallocInt32(n) - case 'float': - case 'float32': - return mallocFloat(n) - case 'double': - case 'float64': - return mallocDouble(n) - case 'uint8_clamped': - return mallocUint8Clamped(n) - case 'buffer': - return mallocBuffer(n) - case 'data': - case 'dataview': - return mallocDataView(n) - - default: - return null - } - } - return null -} - -function mallocArrayBuffer(n) { - var n = bits.nextPow2(n) - var log_n = bits.log2(n) - var d = DATA[log_n] - if(d.length > 0) { - return d.pop() - } - return new ArrayBuffer(n) -} -exports.mallocArrayBuffer = mallocArrayBuffer - -function mallocUint8(n) { - return new Uint8Array(mallocArrayBuffer(n), 0, n) -} -exports.mallocUint8 = mallocUint8 - -function mallocUint16(n) { - return new Uint16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocUint16 = mallocUint16 - -function mallocUint32(n) { - return new Uint32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocUint32 = mallocUint32 - -function mallocInt8(n) { - return new Int8Array(mallocArrayBuffer(n), 0, n) -} -exports.mallocInt8 = mallocInt8 - -function mallocInt16(n) { - return new Int16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocInt16 = mallocInt16 + if (size <= 0) return; + var removed = array[0], object; + if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); + return removed; + }; -function mallocInt32(n) { - return new Int32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocInt32 = mallocInt32 + heap.remove = function(removed) { + var i = removed._, object; + if (array[i] !== removed) return; // invalid request + if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); + return i; + }; -function mallocFloat(n) { - return new Float32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocFloat32 = exports.mallocFloat = mallocFloat + function up(object, i) { + while (i > 0) { + var j = ((i + 1) >> 1) - 1, + parent = array[j]; + if (compareArea(object, parent) >= 0) break; + array[parent._ = i] = parent; + array[object._ = i = j] = object; + } + } -function mallocDouble(n) { - return new Float64Array(mallocArrayBuffer(8*n), 0, n) -} -exports.mallocFloat64 = exports.mallocDouble = mallocDouble + function down(object, i) { + while (true) { + var r = (i + 1) << 1, + l = r - 1, + j = i, + child = array[j]; + if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; + if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; + if (j === i) break; + array[child._ = i] = child; + array[object._ = i = j] = object; + } + } -function mallocUint8Clamped(n) { - if(hasUint8C) { - return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) - } else { - return mallocUint8(n) + return heap; } -} -exports.mallocUint8Clamped = mallocUint8Clamped - -function mallocDataView(n) { - return new DataView(mallocArrayBuffer(n), 0, n) -} -exports.mallocDataView = mallocDataView -function mallocBuffer(n) { - n = bits.nextPow2(n) - var log_n = bits.log2(n) - var cache = BUFFER[log_n] - if(cache.length > 0) { - return cache.pop() + function transformAbsolute(transform) { + if (!transform) return noop; + var x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + point[0] = (x0 += point[0]) * kx + dx; + point[1] = (y0 += point[1]) * ky + dy; + }; } - return new Buffer(n) -} -exports.mallocBuffer = mallocBuffer -exports.clearCache = function clearCache() { - for(var i=0; i<32; ++i) { - POOL.UINT8[i].length = 0 - POOL.UINT16[i].length = 0 - POOL.UINT32[i].length = 0 - POOL.INT8[i].length = 0 - POOL.INT16[i].length = 0 - POOL.INT32[i].length = 0 - POOL.FLOAT[i].length = 0 - POOL.DOUBLE[i].length = 0 - POOL.UINT8C[i].length = 0 - DATA[i].length = 0 - BUFFER[i].length = 0 + function transformRelative(transform) { + if (!transform) return noop; + var x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + var x1 = (point[0] - dx) / kx | 0, + y1 = (point[1] - dy) / ky | 0; + point[0] = x1 - x0; + point[1] = y1 - y0; + x0 = x1; + y0 = y1; + }; } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer) -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy90eXBlZ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huLCBkdHlwZSkge1xuICBpZihkdHlwZSA9PT0gdW5kZWZpbmVkIHx8IGR0eXBlID09PSAnYXJyYXlidWZmZXInKSB7XG4gICAgcmV0dXJuIG1hbGxvY0FycmF5QnVmZmVyKG4pXG4gIH0gZWxzZSB7XG4gICAgc3dpdGNoKGR0eXBlKSB7XG4gICAgICBjYXNlICd1aW50OCc6XG4gICAgICAgIHJldHVybiBtYWxsb2NVaW50OChuKVxuICAgICAgY2FzZSAndWludDE2JzpcbiAgICAgICAgcmV0dXJuIG1hbGxvY1VpbnQxNihuKVxuICAgICAgY2FzZSAndWludDMyJzpcbiAgICAgICAgcmV0dXJuIG1hbGxvY1VpbnQzMihuKVxuICAgICAgY2FzZSAnaW50OCc6XG4gICAgICAgIHJldHVybiBtYWxsb2NJbnQ4KG4pXG4gICAgICBjYXNlICdpbnQxNic6XG4gICAgICAgIHJldHVybiBtYWxsb2NJbnQxNihuKVxuICAgICAgY2FzZSAnaW50MzInOlxuICAgICAgICByZXR1cm4gbWFsbG9jSW50MzIobilcbiAgICAgIGNhc2UgJ2Zsb2F0JzpcbiAgICAgIGNhc2UgJ2Zsb2F0MzInOlxuICAgICAgICByZXR1cm4gbWFsbG9jRmxvYXQobilcbiAgICAgIGNhc2UgJ2RvdWJsZSc6XG4gICAgICBjYXNlICdmbG9hdDY0JzpcbiAgICAgICAgcmV0dXJuIG1hbGxvY0RvdWJsZShuKVxuICAgICAgY2FzZSAndWludDhfY2xhbXBlZCc6XG4gICAgICAgIHJldHVybiBtYWxsb2NVaW50OENsYW1wZWQobilcbiAgICAgIGNhc2UgJ2J1ZmZlcic6XG4gICAgICAgIHJldHVybiBtYWxsb2NCdWZmZXIobilcbiAgICAgIGNhc2UgJ2RhdGEnOlxuICAgICAgY2FzZSAnZGF0YXZpZXcnOlxuICAgICAgICByZXR1cm4gbWFsbG9jRGF0YVZpZXcobilcblxuICAgICAgZGVmYXVsdDpcbiAgICAgICAgcmV0dXJuIG51bGxcbiAgICB9XG4gI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YVZpZXdcblxuZnVuY3Rpb24gbWFsbG9jQnVmZmVyKG4pIHtcbiAgbiA9IGJpdHMubmV4dFBvdzIobilcbiAgdmFyIGxvZ19uID0gYml0cy5sb2cyKG4pXG4gIHZhciBjYWNoZSA9IEJVRkZFUltsb2dfbl1cbiAgaWYoY2FjaGUubGVuZ3RoID4gMCkge1xuICAgIHJldHVybiBjYWNoZS5wb3AoKVxuICB9XG4gIHJldHVybiBuZXcgQnVmZmVyKG4pXG59XG5leHBvcnRzLm1hbGxvY0J1ZmZlciA9IG1hbGxvY0J1ZmZlclxuXG5leHBvcnRzLmNsZWFyQ2FjaGUgPSBmdW5jdGlvbiBjbGVhckNhY2hlKCkge1xuICBmb3IodmFyIGk9MDsgaTwzMjsgKytpKSB7XG4gICAgUE9PTC5VSU5UOFtpXS5sZW5ndGggPSAwXG4gICAgUE9PTC5VSU5UMTZbaV0ubGVuZ3RoID0gMFxuICAgIFBPT0wuVUlOVDMyW2ldLmxlbmd0aCA9IDBcbiAgICBQT09MLklOVDhbaV0ubGVuZ3RoID0gMFxuICAgIFBPT0wuSU5UMTZbaV0ubGVuZ3RoID0gMFxuICAgIFBPT0wuSU5UMzJbaV0ubGVuZ3RoID0gMFxuICAgIFBPT0wuRkxPQVRbaV0ubGVuZ3RoID0gMFxuICAgIFBPT0wuRE9VQkxFW2ldLmxlbmd0aCA9IDBcbiAgICBQT09MLlVJTlQ4Q1tpXS5sZW5ndGggPSAwXG4gICAgREFUQVtpXS5sZW5ndGggPSAwXG4gICAgQlVGRkVSW2ldLmxlbmd0aCA9IDBcbiAgfVxufSJdfQ== -},{"bit-twiddle":29,"buffer":38,"dup":134}],192:[function(_dereq_,module,exports){ + + function noop() {} + + if (typeof define === "function" && define.amd) define(topojson); + else if (typeof module === "object" && module.exports) module.exports = topojson; + else this.topojson = topojson; +}(); + +},{}],192:[function(_dereq_,module,exports){ module.exports.VectorTile = _dereq_('./lib/vectortile.js'); module.exports.VectorTileFeature = _dereq_('./lib/vectortilefeature.js'); module.exports.VectorTileLayer = _dereq_('./lib/vectortilelayer.js'); @@ -12979,7 +13240,7 @@ VectorTileFeature.prototype.toGeoJSON = function(x, y, z) { }; }; -},{"point-geometry":187}],195:[function(_dereq_,module,exports){ +},{"point-geometry":196}],195:[function(_dereq_,module,exports){ 'use strict'; var VectorTileFeature = _dereq_('./vectortilefeature.js'); @@ -13043,6 +13304,139 @@ VectorTileLayer.prototype.feature = function(i) { }; },{"./vectortilefeature.js":194}],196:[function(_dereq_,module,exports){ +'use strict'; + +module.exports = Point; + +function Point(x, y) { + this.x = x; + this.y = y; +} + +Point.prototype = { + clone: function() { return new Point(this.x, this.y); }, + + add: function(p) { return this.clone()._add(p); }, + sub: function(p) { return this.clone()._sub(p); }, + mult: function(k) { return this.clone()._mult(k); }, + div: function(k) { return this.clone()._div(k); }, + rotate: function(a) { return this.clone()._rotate(a); }, + matMult: function(m) { return this.clone()._matMult(m); }, + unit: function() { return this.clone()._unit(); }, + perp: function() { return this.clone()._perp(); }, + round: function() { return this.clone()._round(); }, + + mag: function() { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + equals: function(p) { + return this.x === p.x && + this.y === p.y; + }, + + dist: function(p) { + return Math.sqrt(this.distSqr(p)); + }, + + distSqr: function(p) { + var dx = p.x - this.x, + dy = p.y - this.y; + return dx * dx + dy * dy; + }, + + angle: function() { + return Math.atan2(this.y, this.x); + }, + + angleTo: function(b) { + return Math.atan2(this.y - b.y, this.x - b.x); + }, + + 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 θ. + 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; + }, + + _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; + }, + + _round: function() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } +}; + +// constructs Point from an array if necessary +Point.convert = function (a) { + if (a instanceof Point) { + return a; + } + if (Array.isArray(a)) { + return new Point(a[0], a[1]); + } + return a; +}; + +},{}],197:[function(_dereq_,module,exports){ // Geometry building functions 'use strict'; @@ -13052,6 +13446,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); exports.outsideTile = outsideTile; +exports.isCoordOutsideTile = isCoordOutsideTile; var _geo = _dereq_('../geo'); @@ -13076,10 +13471,18 @@ function outsideTile(_a, _b, tolerance) { return true; } - return false; + return false; +} + +function isCoordOutsideTile(coord, tolerance) { + tolerance = tolerance || 0; + var tile_min = tile_bounds[0]; + var tile_max = tile_bounds[1]; + + return coord[0] <= tile_min.x + tolerance || coord[0] >= tile_max.x - tolerance || coord[1] >= tile_min.y - tolerance || coord[1] <= tile_max.y + tolerance; } -},{"../geo":201,"babel-runtime/helpers/interop-require-default":23}],197:[function(_dereq_,module,exports){ +},{"../geo":202,"babel-runtime/helpers/interop-require-default":23}],198:[function(_dereq_,module,exports){ // Point builders 'use strict'; @@ -13102,15 +13505,20 @@ function buildQuadsForPoints(points, vertex_data, vertex_template, _ref, _ref2) var shape_index = _ref.shape_index; var offset_index = _ref.offset_index; var quad = _ref2.quad; - var quad_scale = _ref2.quad_scale; + var quad_normalize = _ref2.quad_normalize; var offset = _ref2.offset; var angle = _ref2.angle; + var shape_w = _ref2.shape_w; var texcoord_scale = _ref2.texcoord_scale; var texcoord_normalize = _ref2.texcoord_normalize; - var w2 = quad[0] / 2; - var h2 = quad[1] / 2; - var scaling = [[-w2, -h2], [w2, -h2], [w2, h2], [-w2, -h2], [w2, h2], [-w2, h2]]; + quad_normalize = quad_normalize || 1; + var w2 = quad[0] / 2 * quad_normalize; + var h2 = quad[1] / 2 * quad_normalize; + var scaling = [[-w2, -h2], [w2, -h2], [w2, h2], [-w2, h2]]; + + var vertex_elements = vertex_data.vertex_elements; + var element_offset = vertex_data.vertex_count; var texcoords = undefined; if (texcoord_index) { @@ -13125,14 +13533,14 @@ function buildQuadsForPoints(points, vertex_data, vertex_template, _ref, _ref2) var max_u = _ref32[2]; var max_v = _ref32[3]; - texcoords = [[min_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, min_v], [max_u, max_v], [min_u, max_v]]; + texcoords = [[min_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, max_v]]; } var num_points = points.length; for (var p = 0; p < num_points; p++) { var point = points[p]; - for (var pos = 0; pos < 6; pos++) { + for (var pos = 0; pos < 4; pos++) { // Add texcoords if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[pos][0] * texcoord_normalize; @@ -13145,17 +13553,26 @@ function buildQuadsForPoints(points, vertex_data, vertex_template, _ref, _ref2) vertex_template[shape_index + 0] = scaling[pos][0]; vertex_template[shape_index + 1] = scaling[pos][1]; vertex_template[shape_index + 2] = angle; - vertex_template[shape_index + 3] = quad_scale; + vertex_template[shape_index + 3] = shape_w; vertex_template[offset_index + 0] = offset[0]; vertex_template[offset_index + 1] = offset[1]; vertex_data.addVertex(vertex_template); } + + vertex_elements.push(element_offset + 0); + vertex_elements.push(element_offset + 1); + vertex_elements.push(element_offset + 2); + vertex_elements.push(element_offset + 2); + vertex_elements.push(element_offset + 3); + vertex_elements.push(element_offset + 0); + + element_offset += 4; } } -},{"./common":196,"babel-runtime/helpers/sliced-to-array":24}],198:[function(_dereq_,module,exports){ +},{"./common":197,"babel-runtime/helpers/sliced-to-array":24}],199:[function(_dereq_,module,exports){ // Polygon builders 'use strict'; @@ -13194,6 +13611,8 @@ function buildPolygons(polygons, vertex_data, vertex_template, _ref) { var texcoord_scale = _ref.texcoord_scale; var texcoord_normalize = _ref.texcoord_normalize; + var vertex_elements = vertex_data.vertex_elements; + if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; @@ -13209,6 +13628,8 @@ function buildPolygons(polygons, vertex_data, vertex_template, _ref) { var num_polygons = polygons.length; for (var p = 0; p < num_polygons; p++) { + var element_offset = vertex_data.vertex_count; + var polygon = polygons[p]; // Find polygon extents to calculate UVs, fit them to the axis-aligned bounding box @@ -13228,23 +13649,28 @@ function buildPolygons(polygons, vertex_data, vertex_template, _ref) { var scale_v = (max_v - min_v) / span_y; } - // Tessellate - var vertices = triangulatePolygon(polygon); + for (var ring_index = 0; ring_index < polygon.length; ring_index++) { + // Add vertex data + var polygon_ring = polygon[ring_index]; + for (var i = 0; i < polygon_ring.length; i++) { + var vertex = polygon_ring[i]; + vertex_template[0] = vertex[0]; + vertex_template[1] = vertex[1]; - // Add vertex data - var num_vertices = vertices.length; - for (var v = 0; v < num_vertices; v++) { - var vertex = vertices[v]; - vertex_template[0] = vertex[0]; - vertex_template[1] = vertex[1]; + // Add UVs + if (texcoord_index) { + vertex_template[texcoord_index + 0] = ((vertex[0] - min_x) * scale_u + min_u) * texcoord_normalize; + vertex_template[texcoord_index + 1] = ((vertex[1] - min_y) * scale_v + min_v) * texcoord_normalize; + } - // Add UVs - if (texcoord_index) { - vertex_template[texcoord_index + 0] = ((vertex[0] - min_x) * scale_u + min_u) * texcoord_normalize; - vertex_template[texcoord_index + 1] = ((vertex[1] - min_y) * scale_v + min_v) * texcoord_normalize; + vertex_data.addVertex(vertex_template); } + } - vertex_data.addVertex(vertex_template); + // Add element indices + var indices = triangulatePolygon(_earcut2['default'].flatten(polygon)); + for (var i = 0; i < indices.length; i++) { + vertex_elements.push(element_offset + indices[i]); } } } @@ -13265,6 +13691,9 @@ function buildExtrudedPolygons(polygons, z, height, min_height, vertex_data, ver vertex_template[2] = max_z; buildPolygons(polygons, vertex_data, vertex_template, { texcoord_index: texcoord_index, texcoord_scale: texcoord_scale, texcoord_normalize: texcoord_normalize }); + var vertex_elements = vertex_data.vertex_elements; + var element_offset = vertex_data.vertex_count; + // Walls // Fit UVs to wall quad if (texcoord_index) { @@ -13279,7 +13708,7 @@ function buildExtrudedPolygons(polygons, z, height, min_height, vertex_data, ver var max_u = _ref42[2]; var max_v = _ref42[3]; - var texcoords = [[min_u, max_v], [min_u, min_v], [max_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, max_v]]; + var texcoords = [[min_u, max_v], [min_u, min_v], [max_u, min_v], [max_u, max_v]]; } var num_polygons = polygons.length; @@ -13306,11 +13735,7 @@ function buildExtrudedPolygons(polygons, z, height, min_height, vertex_data, ver } // Two triangles for the quad formed by each vertex pair, going from bottom to top height - var wall_vertices = [ - // Triangle - [contour[w1][0], contour[w1][1], max_z], [contour[w1][0], contour[w1][1], min_z], [contour[w0][0], contour[w0][1], min_z], - // Triangle - [contour[w0][0], contour[w0][1], min_z], [contour[w0][0], contour[w0][1], max_z], [contour[w1][0], contour[w1][1], max_z]]; + var wall_vertices = [[contour[w1][0], contour[w1][1], max_z], [contour[w1][0], contour[w1][1], min_z], [contour[w0][0], contour[w0][1], min_z], [contour[w0][0], contour[w0][1], max_z]]; // Calc the normal of the wall from up vector and one segment of the wall triangles var wall_vec = _vector2['default'].normalize([contour[w1][0] - contour[w0][0], contour[w1][1] - contour[w0][1], 0]); @@ -13333,6 +13758,15 @@ function buildExtrudedPolygons(polygons, z, height, min_height, vertex_data, ver vertex_data.addVertex(vertex_template); } + + vertex_elements.push(element_offset + 0); + vertex_elements.push(element_offset + 1); + vertex_elements.push(element_offset + 2); + vertex_elements.push(element_offset + 2); + vertex_elements.push(element_offset + 3); + vertex_elements.push(element_offset + 0); + + element_offset += 4; } } } @@ -13341,16 +13775,16 @@ function buildExtrudedPolygons(polygons, z, height, min_height, vertex_data, ver // Triangulation using earcut // https://github.com/mapbox/earcut -function triangulatePolygon(contours) { - return (0, _earcut2['default'])(contours); +function triangulatePolygon(data) { + return (0, _earcut2['default'])(data.vertices, data.holes, data.dimensions); } -},{"../geo":201,"../vector":255,"./common":196,"babel-runtime/helpers/interop-require-default":23,"babel-runtime/helpers/sliced-to-array":24,"earcut":135}],199:[function(_dereq_,module,exports){ +},{"../geo":202,"../vector":260,"./common":197,"babel-runtime/helpers/interop-require-default":23,"babel-runtime/helpers/sliced-to-array":24,"earcut":139}],200:[function(_dereq_,module,exports){ // Geometry building functions 'use strict'; -var _slicedToArray = _dereq_('babel-runtime/helpers/sliced-to-array')['default']; +var _Math$log2 = _dereq_('babel-runtime/core-js/math/log2')['default']; var _interopRequireDefault = _dereq_('babel-runtime/helpers/interop-require-default')['default']; @@ -13372,16 +13806,23 @@ var _common = _dereq_('./common'); var zero_vec2 = [0, 0]; // Build tessellated triangles for a polyline -var corners_for_cap = { +var CAP_TYPE = { butt: 0, - square: 2, - round: 3 + square: 1, + round: 2 }; -var triangles_for_join = { +var JOIN_TYPE = { miter: 0, bevel: 1, - round: 3 + round: 2 +}; + +var DEFAULT = { + MITER_LIMIT: 3, + TEXCOORD_NORMALIZE: 1, + TEXCOORD_RATIO: 1, + MIN_FAN_WIDTH: 5 // Width of line in tile units to place 1 triangle per fan }; // Scaling factor to add precision to line texture V coordinate packed as normalized short @@ -13393,606 +13834,547 @@ function buildPolylines(lines, width, vertex_data, vertex_template, _ref) { var tile_edge_tolerance = _ref.tile_edge_tolerance; var texcoord_index = _ref.texcoord_index; var texcoord_scale = _ref.texcoord_scale; - var texcoord_normalize = _ref.texcoord_normalize; + var texcoord_width = _ref.texcoord_width; var texcoord_ratio = _ref.texcoord_ratio; + var texcoord_normalize = _ref.texcoord_normalize; var scaling_index = _ref.scaling_index; var scaling_normalize = _ref.scaling_normalize; var join = _ref.join; var cap = _ref.cap; var miter_limit = _ref.miter_limit; - var cornersOnCap = corners_for_cap[cap] || 0; // default 'butt' - var trianglesOnJoin = triangles_for_join[join] || 0; // default 'miter' + var cap_type = cap ? CAP_TYPE[cap] : CAP_TYPE.butt; + var join_type = join ? JOIN_TYPE[join] : JOIN_TYPE.miter; // Configure miter limit - if (trianglesOnJoin === 0) { - miter_limit = miter_limit || 3; // default miter limit + if (join_type === JOIN_TYPE.miter) { + miter_limit = miter_limit || DEFAULT.MITER_LIMIT; // default miter limit var miter_len_sq = miter_limit * miter_limit; } - // Build variables + // Texture Variables + var v_scale; if (texcoord_index) { - texcoord_normalize = texcoord_normalize || 1; - texcoord_ratio = texcoord_ratio || 1; - - var _ref2 = texcoord_scale || _common.default_uvs; - - var _ref22 = _slicedToArray(_ref2, 4); - - var min_u = _ref22[0]; - var min_v = _ref22[1]; - var max_u = _ref22[2]; - var max_v = _ref22[3]; + texcoord_normalize = texcoord_normalize || DEFAULT.TEXCOORD_NORMALIZE; + texcoord_ratio = texcoord_ratio || DEFAULT.TEXCOORD_RATIO; + v_scale = 1 / (texcoord_width * texcoord_ratio * v_scale_adjust); // scales line texture as a ratio of the line's width } // Values that are constant for each line and are passed to helper functions var context = { + closed_polygon: closed_polygon, + remove_tile_edges: remove_tile_edges, + tile_edge_tolerance: tile_edge_tolerance, + miter_len_sq: miter_len_sq, + join_type: join_type, + cap_type: cap_type, vertex_data: vertex_data, vertex_template: vertex_template, half_width: width / 2, - vertices: [], scaling_index: scaling_index, scaling_normalize: scaling_normalize, - scalingVecs: scaling_index && [], + v_scale: v_scale, texcoord_index: texcoord_index, - texcoords: texcoord_index && [], - texcoord_normalize: texcoord_normalize, - min_u: min_u, min_v: min_v, max_u: max_u, max_v: max_v, - v_scale: 1 / (width * texcoord_ratio * v_scale_adjust), // scales line texture as a ratio of the line's width - total_dist: 0, - num_pairs: 0 + texcoord_width: texcoord_width, + texcoord_normalize: texcoord_normalize }; - for (var ln = 0; ln < lines.length; ln++) { - // Remove dupe points from lines - var line = dedupeLine(lines[ln], closed_polygon); - if (!line) { - continue; // skip if no valid line remaining - } - - var lineSize = line.length; - - // Ignore non-lines - if (lineSize < 2) { - continue; - } + // Buffer for extra lines to process + var extra_lines = []; - // Initialize variables - var coordPrev = [0, 0], - // Previous point coordinates - coordCurr = [0, 0], - // Current point coordinates - coordNext = [0, 0]; // Next point coordinates + // Process lines + for (var index = 0; index < lines.length; index++) { + buildPolyline(lines[index], context, extra_lines); + } - var normPrev = [0, 0], - // Right normal to segment between previous and current m_points - normCurr = [0, 0], - // Right normal at current point, scaled for miter joint - normNext = [0, 0]; // Right normal to segment between current and next m_points + // Process extra lines + for (var index = 0; index < extra_lines.length; index++) { + buildPolyline(extra_lines[index], context, extra_lines); + } +} - var isPrev = false, - isNext = true; +function buildPolyline(line, context, extra_lines) { + // Skip if line is not valid + if (line.length < 2) { + return; + } - // Add vertices to buffer according to their index - indexPairs(context); + var coordCurr, coordNext, normPrev, normNext; + var join_type = context.join_type; + var cap_type = context.cap_type; + var closed_polygon = context.closed_polygon; + var remove_tile_edges = context.remove_tile_edges; + var tile_edge_tolerance = context.tile_edge_tolerance; + var v_scale = context.v_scale; + var miter_len_sq = context.miter_len_sq; + + var v = 0; // Texture v-coordinate + + // Loop backwards through line to a tile boundary if found + if (closed_polygon && join_type === JOIN_TYPE.miter) { + var boundaryIndex = getTileBoundaryIndex(line); + if (boundaryIndex !== 0) { + // create new line that is a cyclic permutation of the original + var permutedLine = permuteLine(line, boundaryIndex); + extra_lines.push(permutedLine); + return; + } + } - // Do this with the rest (except the last one) - for (var i = 0; i < lineSize; i++) { + // FIRST POINT + coordCurr = line[0]; + coordNext = line[1]; - // There is a next one? - isNext = i + 1 < lineSize; + // If first pair of points is redundant, slice and push to the lines array + if (_vector2['default'].isEqual(coordCurr, coordNext)) { + if (line.length > 2) { + extra_lines.push(line.slice(1)); + } + return; + } - if (isPrev) { - // If there is a previous one, copy the current (previous) values on *Prev - coordPrev = coordCurr; - normPrev = _vector2['default'].normalize(_vector2['default'].perp(coordPrev, line[i])); - } else if (i === 0 && closed_polygon === true) { - // If it's the first point and is a closed polygon + normNext = _vector2['default'].normalize(_vector2['default'].perp(coordCurr, coordNext)); - var needToClose = true; - if (remove_tile_edges) { - if ((0, _common.outsideTile)(line[i], line[lineSize - 2], tile_edge_tolerance)) { - needToClose = false; - } - } + // Skip tile boundary lines and append a new line if needed + if (remove_tile_edges && (0, _common.outsideTile)(coordCurr, coordNext, tile_edge_tolerance)) { + var nonBoundarySegment = getNextNonBoundarySegment(line, 0, tile_edge_tolerance); + if (nonBoundarySegment) { + extra_lines.push(nonBoundarySegment); + } + return; + } - if (needToClose) { - coordPrev = line[lineSize - 2]; - normPrev = _vector2['default'].normalize(_vector2['default'].perp(coordPrev, line[i])); - isPrev = true; - } + if (closed_polygon) { + // Begin the polygon with a join (connecting the first and last segments) + normPrev = _vector2['default'].normalize(_vector2['default'].perp(line[line.length - 2], coordCurr)); + startPolygon(coordCurr, normPrev, normNext, join_type, context); + } else { + // If line begins at edge, don't add a cap + if (!(0, _common.isCoordOutsideTile)(coordCurr)) { + addCap(coordCurr, v, normNext, cap_type, true, context); + if (cap_type !== CAP_TYPE.butt) { + v += 0.5 * v_scale * context.texcoord_width; } + } - // Assign current coordinate - coordCurr = line[i]; - - if (isNext) { - coordNext = line[i + 1]; - } else if (closed_polygon === true) { - // If it's the last point in a closed polygon - coordNext = line[1]; - isNext = true; - } + // Add first pair of points for the line strip + addVertex(coordCurr, normNext, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normNext), [0, v], context); + } - if (isNext) { - // If it's not the last one get next coordinates and calculate the right normal + // INTERMEDIARY POINTS + v += v_scale * _vector2['default'].length(_vector2['default'].sub(coordNext, coordCurr)); + for (var i = 1; i < line.length - 1; i++) { + var currIndex = i; + var nextIndex = i + 1; + coordCurr = line[currIndex]; + coordNext = line[nextIndex]; - normNext = _vector2['default'].normalize(_vector2['default'].perp(coordCurr, coordNext)); - if (remove_tile_edges) { - if ((0, _common.outsideTile)(coordCurr, coordNext, tile_edge_tolerance)) { - normCurr = _vector2['default'].normalize(_vector2['default'].perp(coordPrev, coordCurr)); - if (isPrev) { - addVertexPair(coordCurr, normCurr, context.texcoords && _vector2['default'].length(_vector2['default'].sub(coordCurr, coordPrev)), context); - context.num_pairs++; + // Skip redundant vertices + if (_vector2['default'].isEqual(coordCurr, coordNext)) { + continue; + } - // Add vertices to buffer acording their index - indexPairs(context); - } - isPrev = false; - continue; - } - } - } + // Remove tile boundaries + if (remove_tile_edges && (0, _common.outsideTile)(coordCurr, coordNext, tile_edge_tolerance)) { + addVertex(coordCurr, normNext, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normNext), [0, v], context); + indexPairs(1, context); - // Compute current normal - if (isPrev) { - // If there is a PREVIOUS ... - if (isNext) { - // ... and a NEXT ONE, compute previous and next normals (scaled by the angle with the last prev) - normCurr = _vector2['default'].normalize(_vector2['default'].add(normPrev, normNext)); - var scale = 2 / (1 + Math.abs(_vector2['default'].dot(normPrev, normCurr))); - normCurr = _vector2['default'].mult(normCurr, scale * scale); - } else { - // ... and there is NOT a NEXT ONE, copy the previous next one (which is the current one) - normCurr = _vector2['default'].normalize(_vector2['default'].perp(coordPrev, coordCurr)); - } - } else { - // If there is NO PREVIOUS ... - if (isNext) { - // ... and a NEXT ONE, - normNext = _vector2['default'].normalize(_vector2['default'].perp(coordCurr, coordNext)); - normCurr = normNext; - } else { - // ... and NO NEXT ONE, nothing to do (without prev or next one this is just a point) - continue; - } + var nonBoundaryLines = getNextNonBoundarySegment(line, currIndex + 1, tile_edge_tolerance); + if (nonBoundaryLines) { + extra_lines.push(nonBoundaryLines); } + return; + } - if (isPrev || isNext) { - // If it's the BEGINNING of a LINE - if (i === 0 && !isPrev && !closed_polygon) { - addCap(coordCurr, normCurr, cornersOnCap, true, context); - } - - // Miter limit: if miter join is too sharp, convert to bevel instead - if (trianglesOnJoin === 0 && _vector2['default'].lengthSq(normCurr) > miter_len_sq) { - trianglesOnJoin = triangles_for_join['bevel']; // switch to bevel - } + normPrev = normNext; + normNext = _vector2['default'].normalize(_vector2['default'].perp(coordCurr, coordNext)); - // If it's a JOIN - if (trianglesOnJoin !== 0 && isPrev && isNext) { - addJoin([coordPrev, coordCurr, coordNext], [normPrev, normCurr, normNext], trianglesOnJoin, context); - } else { - addVertexPair(coordCurr, normCurr, context.texcoords && _vector2['default'].length(_vector2['default'].sub(coordCurr, coordPrev)), context); - } + // Add join + if (join_type === JOIN_TYPE.miter) { + addMiter(v, coordCurr, normPrev, normNext, miter_len_sq, false, context); + } else { + addJoin(join_type, v, coordCurr, normPrev, normNext, false, context); + } - if (isNext) { - context.num_pairs++; - } + v += v_scale * _vector2['default'].length(_vector2['default'].sub(coordNext, coordCurr)); + } - isPrev = true; - } - } + // LAST POINT + coordCurr = coordNext; + normPrev = normNext; - // Add vertices to buffer according to their index - indexPairs(context); + if (closed_polygon) { + // Close the polygon with a miter joint or butt cap if on a tile boundary + normNext = _vector2['default'].normalize(_vector2['default'].perp(coordCurr, line[1])); + endPolygon(coordCurr, normPrev, normNext, join_type, v, context); + } else { + // Finish the line strip + addVertex(coordCurr, normPrev, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normPrev), [0, v], context); + indexPairs(1, context); - // If it's the END of a LINE - if (!closed_polygon) { - addCap(coordCurr, normCurr, cornersOnCap, false, context); + // If line ends at edge, don't add a cap + if (!(0, _common.isCoordOutsideTile)(coordCurr)) { + addCap(coordCurr, v, normPrev, cap_type, false, context); } } } -// Remove duplicate points from a line, creating a new line only when points must be removed -function dedupeLine(line, closed) { - var i = undefined, - dupes = undefined; - - // Collect dupe points - for (i = 0; i < line.length - 1; i++) { - if (line[i][0] === line[i + 1][0] && line[i][1] === line[i + 1][1]) { - dupes = dupes || []; - dupes.push(i); - } +function getTileBoundaryIndex(line) { + if ((0, _common.isCoordOutsideTile)(line[0])) { + return 0; } - // Remove dupe points - if (dupes) { - line = line.slice(0); - dupes.forEach(function (d) { - return line.splice(d, 1); - }); + for (var backIndex = 0; backIndex < line.length; backIndex++) { + var coordCurr = line[line.length - 1 - backIndex]; + if ((0, _common.isCoordOutsideTile)(coordCurr)) { + return line.length - 1 - backIndex; + } } - // Line needs at least 2 points, polygon needs at least 3 (+1 to close) - if (!closed && line.length < 2 || closed && line.length < 4) { - return; - } - return line; + return 0; } -// Add to equidistant pairs of vertices (internal method for polyline builder) -function addVertex(coord, normal, uv, _ref3) { - var half_width = _ref3.half_width; - var vertices = _ref3.vertices; - var scalingVecs = _ref3.scalingVecs; - var texcoords = _ref3.texcoords; - - if (scalingVecs) { - // a. If scaling is on add the vertex (the currCoord) and the scaling Vecs (normals pointing where to extrude the vertices) - vertices.push(coord); - scalingVecs.push(normal); - } else { - // b. Add the extruded vertices - vertices.push([coord[0] + normal[0] * half_width, coord[1] + normal[1] * half_width]); +// Iterate through line from startIndex to find a segment not on a tile boundary, if any. +function getNextNonBoundarySegment(line, startIndex, tolerance) { + var endIndex = startIndex; + while (line[endIndex + 1] && (0, _common.outsideTile)(line[endIndex], line[endIndex + 1], tolerance)) { + endIndex++; } - // c) Add UVs if they are enabled - if (texcoords) { - texcoords.push(uv); - } + // If there is a line segment remaining that is within the tile, push it to the lines array + return line.length - endIndex >= 2 ? line.slice(endIndex) : false; } -// Add to equidistant pairs of vertices (internal method for polyline builder) -function addVertexPair(coord, normal, dist, context) { - if (context.texcoords) { - context.total_dist += dist * context.v_scale; - addVertex(coord, normal, [context.max_u, context.total_dist], context); - addVertex(coord, _vector2['default'].neg(normal), [context.min_u, context.total_dist], context); +// Begin a polygon with a join connecting to the last segment (if valid join-type specified) +function startPolygon(coordCurr, normPrev, normNext, join_type, context) { + // If polygon starts on a tile boundary, don't add a join + if (join_type === undefined || (0, _common.isCoordOutsideTile)(coordCurr)) { + addVertex(coordCurr, normNext, [1, 0], context); + addVertex(coordCurr, _vector2['default'].neg(normNext), [0, 0], context); } else { - addVertex(coord, normal, null, context); - addVertex(coord, _vector2['default'].neg(normal), null, context); + // If polygon starts within a tile, add a join + var v = 0; + if (join_type === JOIN_TYPE.miter) { + addMiter(v, coordCurr, normPrev, normNext, context.miter_len_sq, true, context); + } else { + addJoin(join_type, v, coordCurr, normPrev, normNext, true, context); + } } } -// Tessalate a FAN geometry between points A B -// using their normals from a center \ . . / -// and interpolating their UVs \ p / -// \./ -// C -function addFan(coord, nA, nC, nB, uA, uC, uB, signed, numTriangles, context) { +// End a polygon appropriately +function endPolygon(coordCurr, normPrev, normNext, join_type, v, context) { + // If polygon ends on a tile boundary, don't add a join + if ((0, _common.isCoordOutsideTile)(coordCurr)) { + addVertex(coordCurr, normPrev, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normPrev), [0, v], context); + indexPairs(1, context); + } else { + // If polygon ends within a tile, add Miter or no joint (join added on startPolygon) + var miterVec = createMiterVec(normPrev, normNext); - if (numTriangles < 1) { - return; + if (join_type === JOIN_TYPE.miter && _vector2['default'].lengthSq(miterVec) > context.miter_len_sq) { + join_type = JOIN_TYPE.bevel; // switch to bevel + } + + if (join_type === JOIN_TYPE.miter) { + addVertex(coordCurr, miterVec, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(miterVec), [0, v], context); + indexPairs(1, context); + } else { + addVertex(coordCurr, normPrev, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normPrev), [0, v], context); + indexPairs(1, context); + } } +} - // Add previous vertices to buffer and clear the buffers and index pairs - // because we are going to add more triangles. - indexPairs(context); +function createMiterVec(normPrev, normNext) { + var miterVec = _vector2['default'].normalize(_vector2['default'].add(normPrev, normNext)); + var scale = 2 / (1 + Math.abs(_vector2['default'].dot(normPrev, miterVec))); + return _vector2['default'].mult(miterVec, scale * scale); +} - // Initial parameters - var normCurr = _vector2['default'].set(nA); - var normPrev = [0, 0]; +// Add a miter vector or a join if the miter is too sharp +function addMiter(v, coordCurr, normPrev, normNext, miter_len_sq, isBeginning, context) { + var miterVec = createMiterVec(normPrev, normNext); - // Calculate the angle between A and B - var angle_delta = _vector2['default'].angleBetween(nA, nB); + // Miter limit: if miter join is too sharp, convert to bevel instead + if (_vector2['default'].lengthSq(miterVec) > miter_len_sq) { + addJoin(JOIN_TYPE.miter, v, coordCurr, normPrev, normNext, isBeginning, context); + } else { + addVertex(coordCurr, miterVec, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(miterVec), [0, v], context); + if (!isBeginning) { + indexPairs(1, context); + } + } +} - // Calculate the angle for each triangle - var angle_step = angle_delta / numTriangles; +// Add a bevel or round join +function addJoin(join_type, v, coordCurr, normPrev, normNext, isBeginning, context) { + var miterVec = createMiterVec(normPrev, normNext); + var isClockwise = normNext[0] * normPrev[1] - normNext[1] * normPrev[0] > 0; - // Joins that turn left or right behave diferently... - // triangles need to be rotated in diferent directions - if (!signed) { - angle_step *= -1; - } + if (isClockwise) { + addVertex(coordCurr, miterVec, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normPrev), [0, v], context); - if (context.texcoords) { - var uvCurr = _vector2['default'].set(uA); - var uv_delta = _vector2['default'].div(_vector2['default'].sub(uB, uA), numTriangles); - } + if (!isBeginning) { + indexPairs(1, context); + } - // Add the FIRST and CENTER vertex - // The triangles will be composed in a FAN style around it - addVertex(coord, nC, uC, context); + if (join_type === JOIN_TYPE.bevel) { + addBevel(coordCurr, _vector2['default'].neg(normPrev), miterVec, _vector2['default'].neg(normNext), [0, v], [1, v], [0, v], context); + } else if (join_type === JOIN_TYPE.round) { + addFan(coordCurr, _vector2['default'].neg(normPrev), miterVec, _vector2['default'].neg(normNext), [0, v], [1, v], [0, v], false, context); + } - // Add first corner - addVertex(coord, normCurr, uA, context); + addVertex(coordCurr, miterVec, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(normNext), [0, v], context); + } else { + addVertex(coordCurr, normPrev, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(miterVec), [0, v], context); - // Iterate through the rest of the corners - for (var t = 0; t < numTriangles; t++) { - normPrev = _vector2['default'].normalize(normCurr); - normCurr = _vector2['default'].rot(_vector2['default'].normalize(normCurr), angle_step); // Rotate the extrusion normal - if (context.texcoords) { - uvCurr = _vector2['default'].add(uvCurr, uv_delta); + if (!isBeginning) { + indexPairs(1, context); } - addVertex(coord, normCurr, uvCurr, context); // Add computed corner - } - // Index the vertices - for (var i = 0; i < numTriangles; i++) { - if (signed) { - addIndex(i + 2, context); - addIndex(0, context); - addIndex(i + 1, context); - } else { - addIndex(i + 1, context); - addIndex(0, context); - addIndex(i + 2, context); + if (join_type === JOIN_TYPE.bevel) { + addBevel(coordCurr, normPrev, _vector2['default'].neg(miterVec), normNext, [1, v], [0, v], [1, v], context); + } else if (join_type === JOIN_TYPE.round) { + addFan(coordCurr, normPrev, _vector2['default'].neg(miterVec), normNext, [1, v], [0, v], [1, v], false, context); } - } - // Clear the buffer - context.vertices = []; - if (context.scalingVecs) { - context.scalingVecs = []; - } - if (context.texcoords) { - context.texcoords = []; + addVertex(coordCurr, normNext, [1, v], context); + addVertex(coordCurr, _vector2['default'].neg(miterVec), [0, v], context); } } -// addBevel A ----- B -// / \ , . / \ -// / /\ /\ \ -// / \ / \ \ -// / C \ -function addBevel(coord, nA, nC, nB, uA, uC, uB, signed, context) { - // Add previous vertices to buffer and clear the buffers and index pairs - // because we are going to add more triangles. - indexPairs(context); - - // Add the FIRST and CENTER vertex - addVertex(coord, nC, uC, context); - addVertex(coord, nA, uA, context); - addVertex(coord, nB, uB, context); - - if (signed) { - addIndex(2, context); - addIndex(0, context); - addIndex(1, context); - } else { - addIndex(1, context); - addIndex(0, context); - addIndex(2, context); - } +// Add indices to vertex_elements +function indexPairs(num_pairs, context) { + var vertex_elements = context.vertex_data.vertex_elements; + var num_vertices = context.vertex_data.vertex_count; + var offset = num_vertices - 2 * num_pairs - 2; - // Clear the buffer - context.vertices = []; - if (context.scalingVecs) { - context.scalingVecs = []; - } - if (context.texcoords) { - context.texcoords = []; + for (var i = 0; i < num_pairs; i++) { + vertex_elements.push(offset + 2 * i + 2); + vertex_elements.push(offset + 2 * i + 1); + vertex_elements.push(offset + 2 * i + 0); + vertex_elements.push(offset + 2 * i + 2); + vertex_elements.push(offset + 2 * i + 3); + vertex_elements.push(offset + 2 * i + 1); } } -// Tessalate a SQUARE geometry between A and B + ........+ -// and interpolating their UVs : \ 2 / : -// : 1\ /3 : -// A -- C -- B -function addSquare(coord, nA, nB, uA, uC, uB, signed, context) { +function addVertex(coordinate, normal, uv, context) { + var vertex_template = context.vertex_template; + var vertex_data = context.vertex_data; - // Add previous vertices to buffer and clear the buffers and index pairs - // because we are going to add more triangles. - indexPairs(context); + buildVertexTemplate(vertex_template, coordinate, uv, normal, context); + vertex_data.addVertex(vertex_template); +} - // Initial parameters - var normCurr = _vector2['default'].set(nA); - var normPrev = [0, 0]; - if (context.texcoords) { - var uvCurr = _vector2['default'].set(uA); - var uv_delta = _vector2['default'].div(_vector2['default'].sub(uB, uA), 4); - } +function buildVertexTemplate(vertex_template, vertex, texture_coord, scale, context) { + // set vertex position + vertex_template[0] = vertex[0]; + vertex_template[1] = vertex[1]; - // First and last cap have different directions - var angle_step = 0.78539816339; // PI/4 = 45 degrees - if (!signed) { - angle_step *= -1; + // set UVs + if (context.texcoord_index && texture_coord) { + vertex_template[context.texcoord_index + 0] = texture_coord[0] * context.texcoord_normalize; + vertex_template[context.texcoord_index + 1] = texture_coord[1] * context.texcoord_normalize; } - // Add the FIRST and CENTER vertex - // The triangles will be add in a FAN style around it - // - // A -- C - addVertex(coord, zero_vec2, uC, context); + // set Scaling vertex (X, Y normal direction + Z half_width as attribute) + if (context.scaling_index) { + vertex_template[context.scaling_index + 0] = scale[0] * context.scaling_normalize; + vertex_template[context.scaling_index + 1] = scale[1] * context.scaling_normalize; + vertex_template[context.scaling_index + 2] = context.half_width; + } +} - // Add first corner + - // : - // A -- C - addVertex(coord, normCurr, uA, context); +// Tessalate a FAN geometry between points A B +// using their normals from a center \ . . / +// and interpolating their UVs \ p / +// \./ +function addFan(coord, nA, nC, nB, uvA, uvC, uvB, isCap, context) { + var cross = nA[0] * nB[1] - nA[1] * nB[0]; + var dot = _vector2['default'].dot(nA, nB); - // Iterate through the rest of the coorners completing the triangles - // (except the corner 1 to save one triangle to be draw ) - for (var t = 0; t < 4; t++) { + var angle = Math.atan2(cross, dot); + while (angle >= Math.PI) { + angle -= 2 * Math.PI; + } - // 0 1 2 - // + ........+ - // : \ / : - // : \ / : - // A -- C -- B 3 + var numTriangles = trianglesPerArc(angle, context.half_width); + if (numTriangles < 1) { + return; + } - normPrev = _vector2['default'].normalize(normCurr); - normCurr = _vector2['default'].rot(_vector2['default'].normalize(normCurr), angle_step); // Rotate the extrusion normal + var pivotIndex = context.vertex_data.vertex_count; + var vertex_elements = context.vertex_data.vertex_elements; - if (t === 0 || t === 2) { - // In order to make this "fan" look like a square the mitters need to be streach - var scale = 2 / (1 + Math.abs(_vector2['default'].dot(normPrev, normCurr))); - normCurr = _vector2['default'].mult(normCurr, scale * scale); - } + addVertex(coord, nC, uvC, context); + addVertex(coord, nA, uvA, context); - if (context.texcoords) { - uvCurr = _vector2['default'].add(uvCurr, uv_delta); - } + var blade = nA; - if (t !== 1) { - // Add computed corner (except the corner 1) - addVertex(coord, normCurr, uvCurr, context); + if (context.texcoord_index !== undefined) { + var uvCurr; + if (isCap) { + uvCurr = []; + var affine_uvCurr = _vector2['default'].sub(uvA, uvC); + } else { + uvCurr = _vector2['default'].set(uvA); + var uv_delta = _vector2['default'].div(_vector2['default'].sub(uvB, uvA), numTriangles); } } - for (var i = 0; i < 3; i++) { - if (signed) { - addIndex(i + 2, context); - addIndex(0, context); - addIndex(i + 1, context); - } else { - addIndex(i + 1, context); - addIndex(0, context); - addIndex(i + 2, context); + var angle_step = angle / numTriangles; + for (var i = 0; i < numTriangles; i++) { + blade = _vector2['default'].rot(blade, angle_step); + + if (context.texcoord_index !== undefined) { + if (isCap) { + // UV textures go "through" the cap + affine_uvCurr = _vector2['default'].rot(affine_uvCurr, angle_step); + uvCurr[0] = affine_uvCurr[0] + uvC[0]; + uvCurr[1] = affine_uvCurr[1] * context.texcoord_width * context.v_scale + uvC[1]; // scale the v-coordinate + } else { + // UV textures go "around" the join + uvCurr = _vector2['default'].add(uvCurr, uv_delta); + } } - } - // Clear the buffer - context.vertices = []; - if (context.scalingVecs) { - context.scalingVecs = []; - } - if (context.texcoords) { - context.texcoords = []; + addVertex(coord, blade, uvCurr, context); + + vertex_elements.push(pivotIndex + i + (cross > 0 ? 2 : 1)); + vertex_elements.push(pivotIndex); + vertex_elements.push(pivotIndex + i + (cross > 0 ? 1 : 2)); } } -// Add special joins (not miter) types that require FAN tessellations -// Using http://www.codeproject.com/Articles/226569/Drawing-polylines-by-tessellation as reference -function addJoin(coords, normals, nTriangles, context) { - var signed = _vector2['default'].signed_area(coords[0], coords[1], coords[2]) > 0; - var nA = normals[0], - // normal to point A (aT) - nC = _vector2['default'].neg(normals[1]), - // normal to center (-vP) - nB = normals[2]; // normal to point B (bT) - var uA, uB, uC; - - if (context.texcoords) { - context.total_dist += _vector2['default'].length(_vector2['default'].sub(coords[1], coords[0])) * context.v_scale; - uA = [context.max_u, context.total_dist]; - uC = [context.min_u, context.total_dist]; - uB = uA; - } +// addBevel A ----- B +// / \ / \ +// / /\ /\ \ +// / \ / \ \ +// / C \ +function addBevel(coord, nA, nC, nB, uA, uC, uB, context) { + var pivotIndex = context.vertex_data.vertex_count; - if (signed) { - addVertex(coords[1], nA, uA, context); - addVertex(coords[1], nC, uC, context); - } else { - nA = _vector2['default'].neg(normals[0]); - nC = normals[1]; - nB = _vector2['default'].neg(normals[2]); + addVertex(coord, nC, uC, context); + addVertex(coord, nA, uA, context); + addVertex(coord, nB, uB, context); - if (context.texcoords) { - uA = [context.min_u, context.total_dist]; - uC = [context.max_u, context.total_dist]; - uB = uA; - } - addVertex(coords[1], nC, uC, context); - addVertex(coords[1], nA, uA, context); - } + var orientation = nA[0] * nB[1] - nA[1] * nB[0] > 0; - if (nTriangles === 1) { - addBevel(coords[1], nA, nC, nB, uA, uC, uB, signed, context); - } else if (nTriangles > 1) { - addFan(coords[1], nA, nC, nB, uA, uC, uB, signed, nTriangles, context); - } + var vertex_elements = context.vertex_data.vertex_elements; - if (signed) { - addVertex(coords[1], nB, uB, context); - addVertex(coords[1], nC, uC, context); + if (orientation) { + vertex_elements.push(pivotIndex + 2); + vertex_elements.push(pivotIndex + 0); + vertex_elements.push(pivotIndex + 1); } else { - addVertex(coords[1], nC, uC, context); - addVertex(coords[1], nB, uB, context); + vertex_elements.push(pivotIndex + 1); + vertex_elements.push(pivotIndex + 0); + vertex_elements.push(pivotIndex + 2); } } // Function to add the vertex need for line caps, // because re-use the buffers needs to be at the end -function addCap(coord, normal, numCorners, isBeginning, context) { +function addCap(coord, v, normal, type, isBeginning, context) { + var neg_normal = _vector2['default'].neg(normal); - if (numCorners < 1) { - return; - } + switch (type) { + case CAP_TYPE.square: + var tangent; + if (isBeginning) { + tangent = [normal[1], -normal[0]]; - // UVs - var uvA, uvB, uvC; - if (context.texcoords) { - uvC = [context.min_u + (context.max_u - context.min_u) / 2, context.total_dist]; // Center point UVs - uvA = [context.min_u, context.total_dist]; // Beginning angle UVs - uvB = [context.max_u, context.total_dist]; // Ending angle UVs - } + addVertex(coord, _vector2['default'].add(normal, tangent), [1, v], context); + addVertex(coord, _vector2['default'].add(neg_normal, tangent), [0, v], context); - if (numCorners === 2) { - // If caps are set as squares - addSquare(coord, _vector2['default'].neg(normal), normal, uvA, uvC, uvB, isBeginning, context); - } else { - // If caps are set as round ( numCorners===3 ) - addFan(coord, _vector2['default'].neg(normal), zero_vec2, normal, uvA, uvC, uvB, isBeginning, numCorners * 2, context); - } -} - -// Add a vertex based on the index position into the VBO (internal method for polyline builder) -function addIndex(index, _ref4) { - var vertex_data = _ref4.vertex_data; - var vertex_template = _ref4.vertex_template; - var half_width = _ref4.half_width; - var vertices = _ref4.vertices; - var scaling_index = _ref4.scaling_index; - var scaling_normalize = _ref4.scaling_normalize; - var scalingVecs = _ref4.scalingVecs; - var texcoord_index = _ref4.texcoord_index; - var texcoords = _ref4.texcoords; - var texcoord_normalize = _ref4.texcoord_normalize; - - // Prevent access to undefined vertices - if (index >= vertices.length) { - return; - } + // Add length of square cap to texture coordinate + v += 0.5 * context.texcoord_width * context.v_scale; - // set vertex position - vertex_template[0] = vertices[index][0]; - vertex_template[1] = vertices[index][1]; + addVertex(coord, normal, [1, v], context); + addVertex(coord, neg_normal, [0, v], context); + } else { + tangent = [-normal[1], normal[0]]; - // set UVs - if (texcoord_index) { - vertex_template[texcoord_index + 0] = texcoords[index][0] * texcoord_normalize; - vertex_template[texcoord_index + 1] = texcoords[index][1] * texcoord_normalize; - } + addVertex(coord, normal, [1, v], context); + addVertex(coord, neg_normal, [0, v], context); - // set Scaling vertex (X, Y normal direction + Z half_width as attribute) - if (scaling_index) { - vertex_template[scaling_index + 0] = scalingVecs[index][0] * scaling_normalize; - vertex_template[scaling_index + 1] = scalingVecs[index][1] * scaling_normalize; - vertex_template[scaling_index + 2] = half_width; - } + // Add length of square cap to texture coordinate + v += 0.5 * context.texcoord_width * context.v_scale; - // Add vertex to VBO - vertex_data.addVertex(vertex_template); -} + addVertex(coord, _vector2['default'].add(normal, tangent), [1, v], context); + addVertex(coord, _vector2['default'].add(neg_normal, tangent), [0, v], context); + } + + indexPairs(1, context); + break; + case CAP_TYPE.round: + var nA, nB, uvA, uvB, uvC; + if (isBeginning) { + nA = normal; + nB = neg_normal; + + if (context.texcoord_index !== undefined) { + v += 0.5 * context.texcoord_width * context.v_scale; + uvA = [1, v]; + uvB = [0, v]; + uvC = [0.5, v]; + } + } else { + nA = neg_normal; + nB = normal; -// Add the index vertex to the VBO and clean the buffers -function indexPairs(context) { - // Add vertices to buffer acording their index - for (var i = 0; i < context.num_pairs; i++) { - addIndex(2 * i + 2, context); - addIndex(2 * i + 1, context); - addIndex(2 * i + 0, context); + if (context.texcoord_index !== undefined) { + uvA = [0, v]; + uvB = [1, v]; + uvC = [0.5, v]; + } + } - addIndex(2 * i + 2, context); - addIndex(2 * i + 3, context); - addIndex(2 * i + 1, context); - } + addFan(coord, nA, zero_vec2, nB, uvA, uvC, uvB, true, context); - context.num_pairs = 0; + break; + case CAP_TYPE.butt: + return; + } +} - // Clean the buffer - context.vertices = []; - if (context.scalingVecs) { - context.scalingVecs = []; +// Calculate number of triangles for a fan given an angle and line width +function trianglesPerArc(angle, width) { + if (angle < 0) { + angle = -angle; } - if (context.texcoords) { - context.texcoords = []; + + var numTriangles = width > 2 * DEFAULT.MIN_FAN_WIDTH ? _Math$log2(width / DEFAULT.MIN_FAN_WIDTH) : 1; + return Math.ceil(angle / Math.PI * numTriangles); +} + +// Cyclically permute closed line starting at an index +function permuteLine(line, startIndex) { + var newLine = []; + for (var i = 0; i < line.length; i++) { + var index = (i + startIndex) % line.length; + // skip the first (repeated) index + if (index !== 0) { + newLine.push(line[index]); + } } + newLine.push(newLine[0]); + return newLine; } -},{"../geo":201,"../vector":255,"./common":196,"babel-runtime/helpers/interop-require-default":23,"babel-runtime/helpers/sliced-to-array":24}],200:[function(_dereq_,module,exports){ +},{"../geo":202,"../vector":260,"./common":197,"babel-runtime/core-js/math/log2":5,"babel-runtime/helpers/interop-require-default":23}],201:[function(_dereq_,module,exports){ 'use strict'; var _createClass = _dereq_('babel-runtime/helpers/create-class')['default']; @@ -14083,13 +14465,13 @@ var Camera = (function () { value: function setupMatrices(matrices, program) { // Model view matrix - transform tile space into view space (meters, relative to camera) _utilsGlMatrix.mat4.multiply(matrices.model_view32, this.view_matrix, matrices.model); - program.uniform('Matrix4fv', 'u_modelView', false, matrices.model_view32); + program.uniform('Matrix4fv', 'u_modelView', matrices.model_view32); // Normal matrices - transforms surface normals into view space _utilsGlMatrix.mat3.normalFromMat4(matrices.normal32, matrices.model_view32); _utilsGlMatrix.mat3.invert(matrices.inverse_normal32, matrices.normal32); - program.uniform('Matrix3fv', 'u_normalMatrix', false, matrices.normal32); - program.uniform('Matrix3fv', 'u_inverseNormalMatrix', false, matrices.inverse_normal32); + program.uniform('Matrix3fv', 'u_normalMatrix', matrices.normal32); + program.uniform('Matrix3fv', 'u_inverseNormalMatrix', matrices.inverse_normal32); } }], [{ key: 'create', @@ -14243,8 +14625,8 @@ var PerspectiveCamera = (function (_Camera) { }, { key: 'setupProgram', value: function setupProgram(program) { - program.uniform('Matrix4fv', 'u_projection', false, this.projection_matrix); - program.uniform('3f', 'u_eye', 0, 0, this.position_meters[2]); + program.uniform('Matrix4fv', 'u_projection', this.projection_matrix); + program.uniform('3f', 'u_eye', [0, 0, this.position_meters[2]]); program.uniform('2fv', 'u_vanishing_point', this.vanishing_point_skew); } }]); @@ -14305,11 +14687,11 @@ var IsometricCamera = (function (_Camera2) { }, { key: 'setupProgram', value: function setupProgram(program) { - program.uniform('Matrix4fv', 'u_projection', false, this.projection_matrix); + program.uniform('Matrix4fv', 'u_projection', this.projection_matrix); - program.uniform('3f', 'u_eye', 0, 0, this.viewport_height); + program.uniform('3fv', 'u_eye', [0, 0, this.viewport_height]); // program.uniform('3f', 'u_eye', this.viewport_height * this.axis.x, this.viewport_height * this.axis.y, this.viewport_height); - program.uniform('2f', 'u_vanishing_point', 0, 0); + program.uniform('2fv', 'u_vanishing_point', [0, 0]); } }]); @@ -14344,7 +14726,7 @@ var FlatCamera = (function (_IsometricCamera) { module.exports = exports['default']; -},{"./gl/shader_program":207,"./utils/gl-matrix":248,"./utils/utils":252,"babel-runtime/helpers/class-call-check":18,"babel-runtime/helpers/create-class":19,"babel-runtime/helpers/get":21,"babel-runtime/helpers/inherits":22,"babel-runtime/helpers/interop-require-default":23}],201:[function(_dereq_,module,exports){ +},{"./gl/shader_program":208,"./utils/gl-matrix":251,"./utils/utils":257,"babel-runtime/helpers/class-call-check":18,"babel-runtime/helpers/create-class":19,"babel-runtime/helpers/get":21,"babel-runtime/helpers/inherits":22,"babel-runtime/helpers/interop-require-default":23}],202:[function(_dereq_,module,exports){ // Miscellaneous geo functions 'use strict'; @@ -14382,6 +14764,7 @@ Geo.metersPerTile = function (z) { // Conversion functions based on an defined tile scale Geo.tile_scale = 4096; // coordinates are locally scaled to the range [0, tile_scale] Geo.units_per_pixel = Geo.tile_scale / Geo.tile_size; +Geo.height_scale = 16; // provides sub-meter precision for height values (16ths of a meters) var units_per_meter = []; Geo.unitsPerMeter = function (z) { @@ -14547,18 +14930,24 @@ Geo.geometryType = function (type) { }; Geo.centroid = function (polygon) { - var n = polygon.length; - var centroid = [0, 0]; + // Adapted from https://github.com/Leaflet/Leaflet/blob/c10f405a112142b19785967ce0e142132a6095ad/src/layer/vector/Polygon.js#L57 + var x = 0, + y = 0, + area = 0; + var ring = polygon[0]; // only use first ring for now + var len = ring.length; - for (var p = 0; p < polygon.length; p++) { - centroid[0] += polygon[p][0]; - centroid[1] += polygon[p][1]; - } + for (var i = 0, j = len - 1; i < len; j = i, i++) { + var p0 = ring[i]; + var p1 = ring[j]; + var f = p0[1] * p1[0] - p1[1] * p0[0]; - centroid[0] /= n; - centroid[1] /= n; + x += (p0[0] + p1[0]) * f; + y += (p0[1] + p1[1]) * f; + area += f * 3; + } - return centroid; + return [x / area, y / area]; }; Geo.multiCentroid = function (polygons) { @@ -14566,8 +14955,7 @@ Geo.multiCentroid = function (polygons) { var centroid = [0, 0]; for (var p = 0; p < polygons.length; p++) { - var polygon = polygons[p][0]; - var c = Geo.centroid(polygon); + var c = Geo.centroid(polygons[p]); centroid[0] += c[0]; centroid[1] += c[1]; } @@ -14578,39 +14966,42 @@ Geo.multiCentroid = function (polygons) { return centroid; }; -Geo.signedPolygonAreaSum = function (polygon) { +Geo.signedPolygonRingAreaSum = function (ring) { var area = 0; - var n = polygon.length; + var n = ring.length; for (var i = 0; i < n - 1; i++) { - var p0 = polygon[i]; - var p1 = polygon[i + 1]; + var p0 = ring[i]; + var p1 = ring[i + 1]; area += p0[0] * p1[1] - p1[0] * p0[1]; } - area += polygon[n - 1][0] * polygon[0][1] - polygon[0][0] * polygon[n - 1][1]; + area += ring[n - 1][0] * ring[0][1] - ring[0][0] * ring[n - 1][1]; return area; }; -// TODO: subtract inner ring areas +Geo.polygonRingArea = function (ring) { + return Math.abs(Geo.signedPolygonRingAreaSum(ring)) / 2; +}; + +// TODO: subtract inner rings Geo.polygonArea = function (polygon) { - return Math.abs(Geo.signedPolygonAreaSum(polygon)) / 2; + return Geo.polygonRingArea(polygon[0]); }; Geo.multiPolygonArea = function (polygons) { var area = 0; for (var p = 0; p < polygons.length; p++) { - var polygon = polygons[p][0]; - area += Geo.polygonArea(polygon); + area += Geo.polygonArea(polygons[p]); } return area; }; Geo.ringWinding = function (ring) { - var area = Geo.signedPolygonAreaSum(ring); + var area = Geo.signedPolygonRingAreaSum(ring); if (area > 0) { return 'CW'; } else if (area < 0) { @@ -14667,7 +15058,7 @@ Geo.enforceWinding = function (geom, winding) { }; module.exports = exports['default']; -},{"babel-runtime/core-js/get-iterator":2,"babel-runtime/helpers/sliced-to-array":24}],202:[function(_dereq_,module,exports){ +},{"babel-runtime/core-js/get-iterator":2,"babel-runtime/helpers/sliced-to-array":24}],203:[function(_dereq_,module,exports){ // WebGL constants - need to import these separately to make them available in the web worker "use strict"; @@ -14688,7 +15079,7 @@ gl.UNSIGNED_INT = 0x1405; gl.FLOAT = 0x1406; module.exports = exports["default"]; -},{}],203:[function(_dereq_,module,exports){ +},{}],204:[function(_dereq_,module,exports){ // WebGL context wrapper 'use strict'; @@ -14741,7 +15132,7 @@ Context.resize = function (gl, width, height, device_pixel_ratio) { }; module.exports = exports['default']; -},{}],204:[function(_dereq_,module,exports){ +},{}],205:[function(_dereq_,module,exports){ // WebGL extension wrapper // Stores extensions by name and GL context @@ -14770,7 +15161,7 @@ function getExtension(gl, name) { module.exports = exports["default"]; -},{"babel-runtime/core-js/map":4}],205:[function(_dereq_,module,exports){ +},{"babel-runtime/core-js/map":4}],206:[function(_dereq_,module,exports){ 'use strict'; var _toConsumableArray = _dereq_('babel-runtime/helpers/to-consumable-array')['default']; @@ -14798,8 +15189,6 @@ exports['default'] = GLSL; known texture names, or it could simply be used as a URL to dynamically load the texture from. */ GLSL.parseUniforms = function (uniforms) { - var prefix = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - var parsed = []; for (var name in uniforms) { @@ -14807,10 +15196,6 @@ GLSL.parseUniforms = function (uniforms) { var uniform = uniforms[name]; var u; - if (prefix) { - name = prefix + '.' + name; - } - // Single float if (typeof uniform === 'number') { parsed.push({ @@ -14822,7 +15207,7 @@ GLSL.parseUniforms = function (uniforms) { uniforms: uniforms }); } - // Array: vector, array of floats, array of textures, or array of structs + // Array: vector, array of floats, array of textures else if (Array.isArray(uniform)) { // Numeric values if (typeof uniform[0] === 'number') { @@ -14879,15 +15264,8 @@ GLSL.parseUniforms = function (uniforms) { }); } } - // else error? } - // Array of structures - else if (typeof uniform[0] === 'object') { - for (u = 0; u < uniform.length; u++) { - // Set each struct in the array - parsed.push.apply(parsed, _toConsumableArray(GLSL.parseUniforms(uniform[u], name + '[' + u + ']'))); - } - } + // TODO: else warning } // Boolean else if (typeof uniform === 'boolean') { @@ -14911,13 +15289,6 @@ GLSL.parseUniforms = function (uniforms) { uniforms: uniforms }); } - // Structure - else if (typeof uniform === 'object') { - // Set each field in the struct - parsed.push.apply(parsed, _toConsumableArray(GLSL.parseUniforms(uniform, name))); - } - - // TODO: support other non-float types? (int, etc.) } return parsed; @@ -14927,11 +15298,7 @@ GLSL.parseUniforms = function (uniforms) { Generate a GLSL variable definition from a JS object */ GLSL.defineVariable = function (name, value) { - var prefix = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; - var type, array; - var structs = ''; - prefix = prefix ? prefix + '_' + name : name; // Single float if (typeof value === 'number') { @@ -14958,21 +15325,6 @@ GLSL.defineVariable = function (name, value) { type = 'sampler2D'; array = value.length; } - // Array of arrays - but only arrays of vectors are allowed in this case - else if (Array.isArray(value[0]) && typeof value[0][0] === 'number') { - // float vectors (vec2, vec3, vec4) - if (value[0].length >= 2 && value[0].length <= 4) { - type = 'vec' + value[0].length; - } - // else error? - array = value[0].length; - } - // Array of structures - else if (typeof value[0] === 'object') { - type = '_type_' + prefix; // custom struct name - array = value.length; - structs += GLSL.defineStruct(type, value[0], prefix) + '\n'; // build & add to list of dependent structs - } } // Boolean else if (typeof value === 'boolean') { @@ -14982,11 +15334,6 @@ GLSL.defineVariable = function (name, value) { else if (typeof value === 'string') { type = 'sampler2D'; } - // Structure - else if (typeof value === 'object') { - type = '_type_' + prefix; // custom struct name - structs += GLSL.defineStruct(type, value, prefix) + '\n'; // build & add to list of dependent structs - } // Construct variable definition var variable = ''; @@ -14996,35 +15343,14 @@ GLSL.defineVariable = function (name, value) { } variable += ';\n'; - // Return the variable definition itself, and any dependent struct definitions - return { variable: variable, structs: structs }; -}; - -/** - Generate a GLSL structure definition from a JS object -*/ -GLSL.defineStruct = function (type, value) { - var prefix = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; - - var struct = 'struct ' + type + ' {\n'; - var dependents = ''; - for (var field in value) { - var subvar = GLSL.defineVariable(field, value[field], prefix); - struct += ' ' + subvar.variable; - dependents += subvar.structs; - } - struct += '};\n'; - struct = dependents + struct; - return struct; + return variable; }; /** Generate a GLSL uniform definition from a JS object */ GLSL.defineUniform = function (name, value) { - var def = GLSL.defineVariable(name, value); - def = def.structs + 'uniform ' + def.variable; - return def; + return 'uniform ' + GLSL.defineVariable(name, value); }; /** @@ -15104,7 +15430,7 @@ GLSL.expandVec4 = function (v) { }; module.exports = exports['default']; -},{"babel-runtime/helpers/to-consumable-array":25}],206:[function(_dereq_,module,exports){ +},{"babel-runtime/helpers/to-consumable-array":25}],207:[function(_dereq_,module,exports){ "use strict"; var _createClass = _dereq_("babel-runtime/helpers/create-class")["default"]; @@ -15112,102 +15438,101 @@ var _createClass = _dereq_("babel-runtime/helpers/create-class")["default"]; var _classCallCheck = _dereq_("babel-runtime/helpers/class-call-check")["default"]; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var RenderState = (function () { - function RenderState(value, setup) { - _classCallCheck(this, RenderState); + function RenderState(value, setup) { + _classCallCheck(this, RenderState); - setup(value); - this.value = value; - this.setup = setup; - } - - _createClass(RenderState, [{ - key: "set", - value: function set(value) { - // if the states are different, call the GL context for a state change - if (JSON.stringify(this.value) !== JSON.stringify(value)) { - this.setup(value); + setup(value); this.value = value; - } + this.setup = setup; } - }], [{ - key: "initialize", - value: function initialize(gl) { - RenderState.defaults = {}; - // Culling - RenderState.defaults.culling = true; - RenderState.defaults.culling_face = gl.BACK; - - // Blending - RenderState.defaults.blending = false; - RenderState.defaults.blending_src = gl.ONE_MINUS_SRC_ALPHA; - RenderState.defaults.blending_dst = gl.ONE_MINUS_SRC_ALPHA; - RenderState.defaults.blending_src_alpha = gl.ONE; - RenderState.defaults.blending_dst_alpha = gl.ONE_MINUS_SRC_ALPHA; - - // Depth test/write - RenderState.defaults.depth_write = true; - RenderState.defaults.depth_test = true; - RenderState.defaults.depth_func = gl.LESS; - - // Culling - RenderState.culling = new RenderState({ cull: RenderState.defaults.culling, face: RenderState.defaults.culling_face }, function (value) { - if (value.cull) { - gl.enable(gl.CULL_FACE); - gl.cullFace(value.face); - } else { - gl.disable(gl.CULL_FACE); - } - }); - // Blending mode - RenderState.blending = new RenderState({ - blend: RenderState.defaults.blending, - src: RenderState.defaults.blending_src, - dst: RenderState.defaults.blending_dst, - src_alpha: RenderState.defaults.blending_src_alpha, - dst_alpha: RenderState.defaults.blending_dst_alpha - }, function (value) { - if (value.blend) { - gl.enable(gl.BLEND); - - if (value.src_alpha && value.dst_alpha) { - gl.blendFuncSeparate(value.src, value.dst, value.src_alpha, value.dst_alpha); - } else { - gl.blendFunc(value.src, value.dst); - } - } else { - gl.disable(gl.BLEND); + _createClass(RenderState, [{ + key: "set", + value: function set(value) { + // if the states are different, call the GL context for a state change + if (JSON.stringify(this.value) !== JSON.stringify(value)) { + this.setup(value); + this.value = value; + } } - }); + }], [{ + key: "initialize", + value: function initialize(gl) { + RenderState.defaults = {}; + // Culling + RenderState.defaults.culling = true; + RenderState.defaults.culling_face = gl.BACK; + + // Blending + RenderState.defaults.blending = false; + RenderState.defaults.blending_src = gl.ONE_MINUS_SRC_ALPHA; + RenderState.defaults.blending_dst = gl.ONE_MINUS_SRC_ALPHA; + RenderState.defaults.blending_src_alpha = gl.ONE; + RenderState.defaults.blending_dst_alpha = gl.ONE_MINUS_SRC_ALPHA; + + // Depth test/write + RenderState.defaults.depth_write = true; + RenderState.defaults.depth_test = true; + gl.depthFunc(gl.LESS); // depth function only needs to be set once + + // Culling + RenderState.culling = new RenderState({ cull: RenderState.defaults.culling, face: RenderState.defaults.culling_face }, function (value) { + if (value.cull) { + gl.enable(gl.CULL_FACE); + gl.cullFace(value.face); + } else { + gl.disable(gl.CULL_FACE); + } + }); + + // Blending mode + RenderState.blending = new RenderState({ + blend: RenderState.defaults.blending, + src: RenderState.defaults.blending_src, + dst: RenderState.defaults.blending_dst, + src_alpha: RenderState.defaults.blending_src_alpha, + dst_alpha: RenderState.defaults.blending_dst_alpha + }, function (value) { + if (value.blend) { + gl.enable(gl.BLEND); + + if (value.src_alpha && value.dst_alpha) { + gl.blendFuncSeparate(value.src, value.dst, value.src_alpha, value.dst_alpha); + } else { + gl.blendFunc(value.src, value.dst); + } + } else { + gl.disable(gl.BLEND); + } + }); - // Depth write - RenderState.depth_write = new RenderState({ depth_write: RenderState.defaults.depth_write }, function (value) { - gl.depthMask(value.depth_write); - }); + // Depth write + RenderState.depth_write = new RenderState({ depth_write: RenderState.defaults.depth_write }, function (value) { + gl.depthMask(value.depth_write); + }); - // Depth test - RenderState.depth_test = new RenderState({ depth_test: RenderState.defaults.depth_test, depth_func: RenderState.defaults.depth_func }, function (value) { - if (value.depth_test) { - gl.enable(gl.DEPTH_TEST); - gl.depthFunc(value.depth_func); - } else { - gl.disable(gl.DEPTH_TEST); + // Depth test + RenderState.depth_test = new RenderState({ depth_test: RenderState.defaults.depth_test }, function (value) { + if (value.depth_test) { + gl.enable(gl.DEPTH_TEST); + } else { + gl.disable(gl.DEPTH_TEST); + } + }); } - }); - } - }]); + }]); - return RenderState; + return RenderState; })(); exports["default"] = RenderState; module.exports = exports["default"]; -},{"babel-runtime/helpers/class-call-check":18,"babel-runtime/helpers/create-class":19}],207:[function(_dereq_,module,exports){ +},{"babel-runtime/helpers/class-call-check":18,"babel-runtime/helpers/create-class":19}],208:[function(_dereq_,module,exports){ // GL program wrapper to cache uniform locations/values, do compile-time pre-processing // (injecting #defines and #pragma blocks into shaders), etc. @@ -15229,6 +15554,10 @@ Object.defineProperty(exports, '__esModule', { value: true }); +var _utilsLog = _dereq_('../utils/log'); + +var _utilsLog2 = _interopRequireDefault(_utilsLog); + var _glsl = _dereq_('./glsl'); var _glsl2 = _interopRequireDefault(_glsl); @@ -15241,10 +15570,6 @@ var _extensions = _dereq_('./extensions'); var _extensions2 = _interopRequireDefault(_extensions); -var _loglevel = _dereq_('loglevel'); - -var _loglevel2 = _interopRequireDefault(_loglevel); - var _stripComments = _dereq_('strip-comments'); var _stripComments2 = _interopRequireDefault(_stripComments); @@ -15253,6 +15578,10 @@ var _glShaderErrors = _dereq_('gl-shader-errors'); var _glShaderErrors2 = _interopRequireDefault(_glShaderErrors); +// Regex patterns +var re_pragma = /^\s*#pragma.*$/gm; // for removing unused pragmas after shader block injection +var re_continue_line = /\\\s*\n/mg; // for removing backslash line continuations + var ShaderProgram = (function () { function ShaderProgram(gl, vertex_source, fragment_source, options) { _classCallCheck(this, ShaderProgram); @@ -15387,9 +15716,8 @@ var ShaderProgram = (function () { } // Clean-up any #pragmas that weren't replaced (to prevent compiler warnings) - regexp = new RegExp('^\\s*#pragma.*$', 'gm'); - this.computed_vertex_source = this.computed_vertex_source.replace(regexp, ''); - this.computed_fragment_source = this.computed_fragment_source.replace(regexp, ''); + this.computed_vertex_source = this.computed_vertex_source.replace(re_pragma, ''); + this.computed_fragment_source = this.computed_fragment_source.replace(re_pragma, ''); // Detect uniform definitions, inject any missing ones this.ensureUniforms(this.dependent_uniforms); @@ -15417,6 +15745,10 @@ var ShaderProgram = (function () { defines['TANGRAM_FRAGMENT_SHADER'] = true; this.computed_fragment_source = ShaderProgram.buildExtensionString(extensions) + header + precision + ShaderProgram.buildDefineString(defines) + this.computed_fragment_source; + // Replace multi-line backslashes + this.computed_vertex_source = this.computed_vertex_source.replace(re_continue_line, ''); + this.computed_fragment_source = this.computed_fragment_source.replace(re_continue_line, ''); + // Compile & set uniforms to cached values try { this.program = ShaderProgram.updateProgram(this.gl, this.program, this.computed_vertex_source, this.computed_fragment_source); @@ -15560,7 +15892,7 @@ var ShaderProgram = (function () { if (!inject) { inject = _glsl2['default'].defineUniform(name, uniforms[name]); } - _loglevel2['default'].trace('Program ' + this.name + ': ' + name + ' not defined in vertex shader, injecting: \'' + inject + '\''); + (0, _utilsLog2['default'])('trace', 'Program ' + this.name + ': ' + name + ' not defined in vertex shader, injecting: \'' + inject + '\''); vs_injections.push(inject); } // Check fragment shader @@ -15568,7 +15900,7 @@ var ShaderProgram = (function () { if (!inject) { inject = _glsl2['default'].defineUniform(name, uniforms[name]); } - _loglevel2['default'].trace('Program ' + this.name + ': ' + name + ' not defined in fragment shader, injecting: \'' + inject + '\''); + (0, _utilsLog2['default'])('trace', 'Program ' + this.name + ': ' + name + ' not defined in fragment shader, injecting: \'' + inject + '\''); fs_injections.push(inject); } } @@ -15609,33 +15941,13 @@ var ShaderProgram = (function () { var parsed = _glsl2['default'].parseUniforms(uniforms); // Set each uniform - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = _getIterator(parsed), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var uniform = _step2.value; - - if (uniform.type === 'sampler2D') { - // For textures, we need to track texture units, so we have a special setter - this.setTextureUniform(uniform.name, uniform.value); - } else { - this.uniform(uniform.method, uniform.name, uniform.value); - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2['return']) { - _iterator2['return'](); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } + for (var u = 0; u < parsed.length; u++) { + var uniform = parsed[u]; + if (uniform.type === 'sampler2D') { + // For textures, we need to track texture units, so we have a special setter + this.setTextureUniform(uniform.name, uniform.value); + } else { + this.uniform(uniform.method, uniform.name, uniform.value); } } } @@ -15663,7 +15975,7 @@ var ShaderProgram = (function () { var uniform = this.uniforms[u]; if (uniform && uniform.saved_value) { uniform.value = uniform.saved_value; - this.updateUniform(u); + this.updateUniform(uniform); } } this.texture_unit = this.saved_texture_unit || 0; @@ -15675,7 +15987,7 @@ var ShaderProgram = (function () { value: function setTextureUniform(uniform_name, texture_name) { var texture = _texture2['default'].textures[texture_name]; if (texture == null) { - _loglevel2['default'].warn('Can\'t find texture \'' + texture_name + '\''); + (0, _utilsLog2['default'])('warn', 'Cannot find texture \'' + texture_name + '\''); return; } @@ -15684,11 +15996,11 @@ var ShaderProgram = (function () { this.texture_unit++; // TODO: track max texture units and log/throw errors } - // ex: program.uniform('3f', 'position', x, y, z); + // ex: program.uniform('3fv', 'position', [x, y, z]); // TODO: only update uniforms when changed }, { key: 'uniform', - value: function uniform(method, name) { + value: function uniform(method, name, value) { // 'value' is a method-appropriate arguments list if (!this.compiled) { return; @@ -15700,31 +16012,75 @@ var ShaderProgram = (function () { if (uniform.location === undefined) { uniform.location = this.gl.getUniformLocation(this.program, name); } - uniform.method = 'uniform' + method; - - for (var _len = arguments.length, value = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - value[_key - 2] = arguments[_key]; - } - + uniform.method = method; uniform.value = value; - this.updateUniform(name); + this.updateUniform(uniform); } // Set a single uniform }, { key: 'updateUniform', - value: function updateUniform(name) { + value: function updateUniform(uniform) { if (!this.compiled) { return; } - var uniform = this.uniforms[name]; if (!uniform || uniform.location == null) { return; } this.use(); - this.gl[uniform.method].apply(this.gl, [uniform.location].concat(uniform.value)); // call appropriate GL uniform method and pass through arguments + this.commitUniform(uniform); + } + + // Commits the uniform to the GPU + }, { + key: 'commitUniform', + value: function commitUniform(uniform) { + var location = uniform.location; + var value = uniform.value; + + switch (uniform.method) { + case '1i': + this.gl.uniform1i(location, value); + break; + case '1f': + this.gl.uniform1f(location, value); + break; + case '2f': + this.gl.uniform2f(location, value[0], value[1]); + break; + case '3f': + this.gl.uniform3f(location, value[0], value[1], value[2]); + break; + case '4f': + this.gl.uniform4f(location, value[0], value[1], value[2], value[3]); + break; + case '1iv': + this.gl.uniform1iv(location, value); + break; + case '3iv': + this.gl.uniform3iv(location, value); + break; + case '1fv': + this.gl.uniform1fv(location, value); + break; + case '2fv': + this.gl.uniform2fv(location, value); + break; + case '3fv': + this.gl.uniform3fv(location, value); + break; + case '4fv': + this.gl.uniform4fv(location, value); + break; + case 'Matrix3fv': + this.gl.uniformMatrix3fv(location, false, value); + break; + case 'Matrix4fv': + this.gl.uniformMatrix4fv(location, false, value); + break; + } } // Refresh uniform locations and set to last cached values @@ -15736,8 +16092,9 @@ var ShaderProgram = (function () { } for (var u in this.uniforms) { - this.uniforms[u].location = this.gl.getUniformLocation(this.program, u); - this.updateUniform(u); + var uniform = this.uniforms[u]; + uniform.location = this.gl.getUniformLocation(this.program, u); + this.updateUniform(uniform); } } }, { @@ -15854,13 +16211,13 @@ var ShaderProgram = (function () { key: 'checkExtensions', value: function checkExtensions() { var exts = []; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; try { - for (var _iterator3 = _getIterator(this.extensions), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _name = _step3.value; + for (var _iterator2 = _getIterator(this.extensions), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _name = _step2.value; var ext = (0, _extensions2['default'])(this.gl, _name); var def = 'TANGRAM_EXTENSION_' + _name; @@ -15870,20 +16227,20 @@ var ShaderProgram = (function () { if (ext) { exts.push(_name); } else { - _loglevel2['default'].debug('Could not enable extension \'' + _name + '\''); + (0, _utilsLog2['default'])('debug', 'Could not enable extension \'' + _name + '\''); } } } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; + _didIteratorError2 = true; + _iteratorError2 = err; } finally { try { - if (!_iteratorNormalCompletion3 && _iterator3['return']) { - _iterator3['return'](); + if (!_iteratorNormalCompletion2 && _iterator2['return']) { + _iterator2['return'](); } } finally { - if (_didIteratorError3) { - throw _iteratorError3; + if (_didIteratorError2) { + throw _iteratorError2; } } } @@ -15908,7 +16265,7 @@ ShaderProgram.blocks = {}; ShaderProgram.buildDefineString = function (defines) { var define_str = ""; for (var d in defines) { - if (defines[d] === false) { + if (defines[d] == null || defines[d] === false) { continue; } else if (typeof defines[d] === 'boolean' && defines[d] === true) { // booleans are simple defines with no value @@ -15928,27 +16285,27 @@ ShaderProgram.buildDefineString = function (defines) { ShaderProgram.buildExtensionString = function (extensions) { extensions = extensions || []; var str = ""; - var _iteratorNormalCompletion4 = true; - var _didIteratorError4 = false; - var _iteratorError4 = undefined; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; try { - for (var _iterator4 = _getIterator(extensions), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { - var ext = _step4.value; + for (var _iterator3 = _getIterator(extensions), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var ext = _step3.value; str += '#ifdef GL_' + ext + '\n#extension GL_' + ext + ' : enable\n#endif\n'; } } catch (err) { - _didIteratorError4 = true; - _iteratorError4 = err; + _didIteratorError3 = true; + _iteratorError3 = err; } finally { try { - if (!_iteratorNormalCompletion4 && _iterator4['return']) { - _iterator4['return'](); + if (!_iteratorNormalCompletion3 && _iterator3['return']) { + _iterator3['return'](); } } finally { - if (_didIteratorError4) { - throw _iteratorError4; + if (_didIteratorError3) { + throw _iteratorError3; } } } @@ -15961,8 +16318,8 @@ ShaderProgram.addBlock = function (key) { ShaderProgram.blocks[key] = ShaderProgram.blocks[key] || []; - for (var _len2 = arguments.length, blocks = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - blocks[_key2 - 1] = arguments[_key2]; + for (var _len = arguments.length, blocks = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + blocks[_key - 1] = arguments[_key]; } (_ShaderProgram$blocks$key = ShaderProgram.blocks[key]).push.apply(_ShaderProgram$blocks$key, blocks); @@ -15976,8 +16333,8 @@ ShaderProgram.removeBlock = function (key) { ShaderProgram.replaceBlock = function (key) { ShaderProgram.removeBlock(key); - for (var _len3 = arguments.length, blocks = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - blocks[_key3 - 1] = arguments[_key3]; + for (var _len2 = arguments.length, blocks = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + blocks[_key2 - 1] = arguments[_key2]; } ShaderProgram.addBlock.apply(ShaderProgram, [key].concat(blocks)); @@ -15990,7 +16347,7 @@ ShaderProgram.updateProgram = function (gl, program, vertex_shader_source, fragm var vertex_shader = ShaderProgram.createShader(gl, vertex_shader_source, gl.VERTEX_SHADER); var fragment_shader = ShaderProgram.createShader(gl, fragment_shader_source, gl.FRAGMENT_SHADER); } catch (err) { - _loglevel2['default'].error(err.message); + (0, _utilsLog2['default'])('error', err.message); throw err; } @@ -16020,7 +16377,7 @@ ShaderProgram.updateProgram = function (gl, program, vertex_shader_source, fragm var message = new Error('WebGL program error:\n VALIDATE_STATUS: ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n ERROR: ' + gl.getError() + '\n --- Vertex Shader ---\n ' + vertex_shader_source + '\n --- Fragment Shader ---\n ' + fragment_shader_source); var error = { type: 'program', message: message }; - _loglevel2['default'].error(error.message); + (0, _utilsLog2['default'])('error', error.message); throw error; } @@ -16045,53 +16402,7 @@ ShaderProgram.createShader = function (gl, source, stype) { }; module.exports = exports['default']; -},{"./extensions":204,"./glsl":205,"./texture":209,"babel-runtime/core-js/get-iterator":2,"babel-runtime/core-js/object/assign":6,"babel-runtime/helpers/class-call-check":18,"babel-runtime/helpers/create-class":19,"babel-runtime/helpers/interop-require-default":23,"babel-runtime/helpers/to-consumable-array":25,"gl-shader-errors":151,"loglevel":183,"strip-comments":189}],208:[function(_dereq_,module,exports){ -// Generated from GLSL files, don't edit! -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var shaderSources = {}; - -shaderSources['gl/shaders/accessors'] = "#ifdef TANGRAM_VERTEX_SHADER\n" + "\n" + "// Vertex position in model space: [0, 1] range over the local tile\n" + "// Note positions can be outside that range due to unclipped geometry, geometry higher than a unit cube, etc.\n" + "vec4 modelPosition() {\n" + " return\n" + " vec4(\n" + " SHORT(a_position.xyz) // scale normalized short to full range\n" + " / TANGRAM_TILE_SCALE // scale coords to ~0-1 range\n" + " * exp2(u_tile_origin.z - u_tile_origin.w), // adjust for tile overzooming\n" + " 1.)\n" + " + vec4(0., 1., 0., 0.);\n" + " // NB: additional offset to account for unusual Tangram JS y coords,\n" + " // should be refactored to remove\n" + "}\n" + "\n" + "// Position in model space as above, but according to tile coordinate (as opposed to style) zoom\n" + "// e.g. unadjusted for tile overzooming\n" + "vec4 modelPositionBaseZoom() {\n" + " return\n" + " vec4(\n" + " SHORT(a_position.xyz) // scale normalized short to full range\n" + " / TANGRAM_TILE_SCALE, // scale coords to ~0-1 range\n" + " 1.)\n" + " + vec4(0., 1., 0., 0.);\n" + "}\n" + "\n" + "#endif\n" + "\n" + "// Vertex position in world coordinates, useful for 3d procedural textures, etc.\n" + "vec4 worldPosition() {\n" + " return v_world_position;\n" + "}\n" + "\n" + "// Optionally wrap world coordinates (allows more precision at higher zooms)\n" + "// e.g. at wrap 1000, the world space will wrap every 1000 meters\n" + "#ifdef TANGRAM_VERTEX_SHADER\n" + "\n" + "vec4 wrapWorldPosition(vec4 world_position) {\n" + " #if defined(TANGRAM_WORLD_POSITION_WRAP)\n" + " vec2 anchor = u_tile_origin.xy - mod(u_tile_origin.xy, TANGRAM_WORLD_POSITION_WRAP);\n" + " world_position.xy -= anchor;\n" + " #endif\n" + " return world_position;\n" + "}\n" + "\n" + "#endif\n" + "\n" + "// Normal in world space\n" + "#if defined(TANGRAM_VERTEX_SHADER)\n" + "\n" + "vec3 worldNormal() {\n" + " return TANGRAM_NORMAL;\n" + "}\n" + "\n" + "#elif defined(TANGRAM_FRAGMENT_SHADER)\n" + "\n" + "vec3 worldNormal() {\n" + " return u_inverseNormalMatrix * TANGRAM_NORMAL;\n" + "}\n" + "\n" + "#endif\n" + ""; - -shaderSources['gl/shaders/ambientLight'] = "/*\n" + "\n" + "Expected globals:\n" + "light_accumulator_*\n" + "\n" + "*/\n" + "\n" + "struct AmbientLight {\n" + " vec4 ambient;\n" + "};\n" + "\n" + "void calculateLight(in AmbientLight _light, in vec3 _eyeToPoint, in vec3 _normal) {\n" + " light_accumulator_ambient += _light.ambient;\n" + "}\n" + ""; - -shaderSources['gl/shaders/directionalLight'] = "/*\n" + "\n" + "Expected globals:\n" + "material\n" + "light_accumulator_*\n" + "\n" + "*/\n" + "\n" + "struct DirectionalLight {\n" + " vec4 ambient;\n" + " vec4 diffuse;\n" + " vec4 specular;\n" + " vec3 direction;\n" + "};\n" + "\n" + "void calculateLight(in DirectionalLight _light, in vec3 _eyeToPoint, in vec3 _normal) {\n" + "\n" + " light_accumulator_ambient += _light.ambient;\n" + "\n" + " float nDotVP = clamp(dot(_normal, -normalize(_light.direction)), 0.0, 1.0);\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE\n" + " light_accumulator_diffuse += _light.diffuse * nDotVP;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR\n" + " float pf = 0.0;\n" + " if (nDotVP > 0.0) {\n" + " vec3 reflectVector = reflect(normalize(_light.direction), _normal);\n" + " float eyeDotR = max(dot(normalize(_eyeToPoint), reflectVector), 0.0);\n" + " pf = pow(eyeDotR, material.shininess);\n" + " }\n" + " light_accumulator_specular += _light.specular * pf;\n" + " #endif\n" + "}\n" + ""; - -shaderSources['gl/shaders/layer_order'] = "// Apply layer ordering to avoid z-fighting\n" + "void applyLayerOrder (float layer, inout vec4 position) {\n" + " position.z -= layer * TANGRAM_LAYER_DELTA * position.w;\n" + "}\n" + ""; - -shaderSources['gl/shaders/material'] = "/*\n" + "\n" + "Defines globals:\n" + "material\n" + "light_accumulator_*\n" + "\n" + "*/\n" + "\n" + "\n" + "// MATERIALS\n" + "//\n" + "struct Material {\n" + " #ifdef TANGRAM_MATERIAL_EMISSION\n" + " vec4 emission;\n" + " #ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE\n" + " vec3 emissionScale;\n" + " #endif\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT\n" + " vec4 ambient;\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE\n" + " vec3 ambientScale;\n" + " #endif\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE\n" + " vec4 diffuse;\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE\n" + " vec3 diffuseScale;\n" + " #endif\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR\n" + " vec4 specular;\n" + " float shininess;\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE\n" + " vec3 specularScale;\n" + " #endif\n" + " #endif\n" + "\n" + "\n" + " #ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE\n" + " vec3 normalScale;\n" + " float normalAmount;\n" + " #endif\n" + "};\n" + "\n" + "// Note: uniform is copied to a global instance to allow modification\n" + "uniform Material u_material;\n" + "Material material;\n" + "\n" + "#ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE\n" + "uniform sampler2D u_material_emission_texture;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE\n" + "uniform sampler2D u_material_ambient_texture;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE\n" + "uniform sampler2D u_material_diffuse_texture;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE\n" + "uniform sampler2D u_material_specular_texture;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE\n" + "uniform sampler2D u_material_normal_texture;\n" + "#endif\n" + "\n" + "// Global light accumulators for each property\n" + "vec4 light_accumulator_ambient = vec4(0.0);\n" + "vec4 light_accumulator_diffuse = vec4(0.0);\n" + "#ifdef TANGRAM_MATERIAL_SPECULAR\n" + " vec4 light_accumulator_specular = vec4(0.0);\n" + "#endif\n" + "\n" + "\n" + "#ifdef TANGRAM_MATERIAL_TEXTURE_SPHEREMAP\n" + "vec4 getSphereMap (in sampler2D _tex, in vec3 _eyeToPoint, in vec3 _normal, in vec2 _skew) {\n" + " vec3 eye = normalize(_eyeToPoint);\n" + " eye.xy -= _skew;\n" + " eye = normalize(eye);\n" + "\n" + " vec3 r = reflect(eye, _normal);\n" + " r.z += 1.0;\n" + " float m = 2. * length(r);\n" + " vec2 uv = r.xy / m + .5;\n" + " return texture2D(_tex, uv);\n" + "}\n" + "#endif\n" + "\n" + "\n" + "#ifdef TANGRAM_MATERIAL_TEXTURE_TRIPLANAR\n" + "vec3 getTriPlanarBlend (in vec3 _normal) {\n" + " vec3 blending = abs(_normal);\n" + " blending = normalize(max(blending, 0.00001));\n" + " float b = (blending.x + blending.y + blending.z);\n" + " return blending / b;\n" + "}\n" + "\n" + "vec4 getTriPlanar (in sampler2D _tex, in vec3 _pos, in vec3 _normal, in vec3 _scale) {\n" + " vec3 blending = getTriPlanarBlend(_normal);\n" + " vec4 xaxis = texture2D(_tex, fract(_pos.yz * _scale.x));\n" + " vec4 yaxis = texture2D(_tex, fract(_pos.xz * _scale.y));\n" + " vec4 zaxis = texture2D(_tex, fract(_pos.xy * _scale.z));\n" + " return xaxis * blending.x + yaxis * blending.y + zaxis * blending.z;\n" + "}\n" + "#endif\n" + "\n" + "\n" + "#ifdef TANGRAM_MATERIAL_TEXTURE_PLANAR\n" + "vec4 getPlanar (in sampler2D _tex, in vec3 _pos, in vec2 _scale) {\n" + " return texture2D( _tex, fract(_pos.xy * _scale.x) );\n" + "}\n" + "#endif\n" + "\n" + "\n" + "#ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE\n" + "void calculateNormal (inout vec3 _normal) {\n" + " // Get NORMALMAP\n" + " //------------------------------------------------\n" + " #ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE_UV\n" + " _normal += texture2D(u_material_normal_texture, fract(v_texcoord*material.normalScale.xy)).rgb*2.0-1.0;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE_PLANAR\n" + " vec3 normalTex = getPlanar(u_material_normal_texture, v_world_position.xyz, material.normalScale.xy).rgb*2.0-1.0;\n" + " _normal += normalTex;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_NORMAL_TEXTURE_TRIPLANAR\n" + " vec3 normalTex = getTriPlanar(u_material_normal_texture, v_world_position.xyz, _normal, material.normalScale).rgb*2.0-1.0;\n" + " _normal += normalTex;\n" + " #endif\n" + "\n" + " _normal = normalize(_normal);\n" + "}\n" + "#endif\n" + "\n" + "void calculateMaterial (in vec3 _eyeToPoint, inout vec3 _normal) {\n" + " // get EMISSION TEXTUREMAP\n" + " //------------------------------------------------\n" + " #ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE\n" + " #ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE_UV\n" + " material.emission *= texture2D(u_material_emission_texture,v_texcoord);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE_PLANAR\n" + " material.emission *= getPlanar(u_material_emission_texture, v_world_position.xyz, material.emissionScale.xy);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE_TRIPLANAR\n" + " material.emission *= getTriPlanar(u_material_emission_texture, v_world_position.xyz, _normal, material.emissionScale);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_EMISSION_TEXTURE_SPHEREMAP\n" + " material.emission *= getSphereMap(u_material_emission_texture, _eyeToPoint, _normal, u_vanishing_point);\n" + " #endif\n" + " #endif\n" + "\n" + " // get AMBIENT TEXTUREMAP\n" + " //------------------------------------------------\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE_UV\n" + " material.ambient *= texture2D(u_material_ambient_texture,v_texcoord);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE_PLANAR\n" + " material.ambient *= getPlanar(u_material_ambient_texture, v_world_position.xyz, material.ambientScale.xy);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE_TRIPLANAR\n" + " material.ambient *= getTriPlanar(u_material_ambient_texture, v_world_position.xyz, _normal, material.ambientScale);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_AMBIENT_TEXTURE_SPHEREMAP\n" + " material.ambient *= getSphereMap(u_material_ambient_texture, _eyeToPoint, _normal, u_vanishing_point);\n" + " #endif\n" + " #endif\n" + "\n" + " // get DIFFUSE TEXTUREMAP\n" + " //------------------------------------------------\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE_UV\n" + " material.diffuse *= texture2D(u_material_diffuse_texture,v_texcoord);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE_PLANAR\n" + " material.diffuse *= getPlanar(u_material_diffuse_texture, v_world_position.xyz, material.diffuseScale.xy);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE_TRIPLANAR\n" + " material.diffuse *= getTriPlanar(u_material_diffuse_texture, v_world_position.xyz, _normal, material.diffuseScale);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE_TEXTURE_SPHEREMAP\n" + " material.diffuse *= getSphereMap(u_material_diffuse_texture, _eyeToPoint, _normal, u_vanishing_point);\n" + " #endif\n" + " #endif\n" + "\n" + " // get SPECULAR TEXTUREMAP\n" + " //------------------------------------------------\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE_UV\n" + " material.specular *= texture2D(u_material_specular_texture,v_texcoord);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE_PLANAR\n" + " material.specular *= getPlanar(u_material_specular_texture, v_world_position.xyz, material.specularScale.xy);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE_TRIPLANAR\n" + " material.specular *= getTriPlanar(u_material_specular_texture, v_world_position.xyz, _normal, material.specularScale);\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR_TEXTURE_SPHEREMAP\n" + " material.specular *= getSphereMap(u_material_specular_texture, _eyeToPoint, _normal, u_vanishing_point);\n" + " #endif\n" + " #endif\n" + "}\n" + ""; - -shaderSources['gl/shaders/pointLight'] = "/*\n" + "\n" + "Expected globals:\n" + "material\n" + "light_accumulator_*\n" + "\n" + "*/\n" + "\n" + "struct PointLight {\n" + " vec4 ambient;\n" + " vec4 diffuse;\n" + " vec4 specular;\n" + " vec4 position;\n" + "\n" + "#ifdef TANGRAM_POINTLIGHT_ATTENUATION_EXPONENT\n" + " float attenuationExponent;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n" + " float innerRadius;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float outerRadius;\n" + "#endif\n" + "};\n" + "\n" + "void calculateLight(in PointLight _light, in vec3 _eyeToPoint, in vec3 _normal) {\n" + "\n" + " float dist = length(_light.position.xyz - _eyeToPoint);\n" + "\n" + " // Compute vector from surface to light position\n" + " vec3 VP = (_light.position.xyz - _eyeToPoint) / dist;\n" + "\n" + " // Normalize the vector from surface to light position\n" + " float nDotVP = clamp(dot(VP, _normal), 0.0, 1.0);\n" + "\n" + " // Attenuation defaults\n" + " float attenuation = 1.0;\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_EXPONENT\n" + " float Rin = 1.0;\n" + " float e = _light.attenuationExponent;\n" + "\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n" + " Rin = _light.innerRadius;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float Rdiff = _light.outerRadius-Rin;\n" + " float d = clamp(max(0.0,dist-Rin)/Rdiff, 0.0, 1.0);\n" + " attenuation = 1.0-(pow(d,e));\n" + " #else\n" + " // If no outer is provide behaves like:\n" + " // https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/\n" + " float d = max(0.0,dist-Rin)/Rin+1.0;\n" + " attenuation = clamp(1.0/(pow(d,e)), 0.0, 1.0);\n" + " #endif\n" + " #else\n" + " float Rin = 0.0;\n" + "\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n" + " Rin = _light.innerRadius;\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float Rdiff = _light.outerRadius-Rin;\n" + " float d = clamp(max(0.0,dist-Rin)/Rdiff, 0.0, 1.0);\n" + " attenuation = 1.0-d*d;\n" + " #else\n" + " // If no outer is provide behaves like:\n" + " // https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/\n" + " float d = max(0.0,dist-Rin)/Rin+1.0;\n" + " attenuation = clamp(1.0/d, 0.0, 1.0);\n" + " #endif\n" + " #else\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float d = clamp(dist/_light.outerRadius, 0.0, 1.0);\n" + " attenuation = 1.0-d*d;\n" + " #else\n" + " attenuation = 1.0;\n" + " #endif\n" + " #endif\n" + " #endif\n" + "\n" + " // Computer accumulators\n" + " light_accumulator_ambient += _light.ambient * attenuation;\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE\n" + " light_accumulator_diffuse += _light.diffuse * nDotVP * attenuation;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR\n" + " float pf = 0.0; // power factor for shiny speculars\n" + " if (nDotVP > 0.0) {\n" + " vec3 reflectVector = reflect(-VP, _normal);\n" + " float eyeDotR = max(0.0, dot(-normalize(_eyeToPoint), reflectVector));\n" + " pf = pow(eyeDotR, material.shininess);\n" + " }\n" + "\n" + " light_accumulator_specular += _light.specular * pf * attenuation;\n" + " #endif\n" + "}\n" + ""; - -shaderSources['gl/shaders/rasters'] = "// Uniforms defining raster textures and macros for accessing them\n" + "\n" + "#ifdef TANGRAM_FRAGMENT_SHADER\n" + "uniform sampler2D u_rasters[TANGRAM_NUM_RASTER_SOURCES]; // raster tile texture samplers\n" + "uniform vec2 u_raster_sizes[TANGRAM_NUM_RASTER_SOURCES]; // raster tile texture sizes (width/height in pixels)\n" + "uniform vec3 u_raster_offsets[TANGRAM_NUM_RASTER_SOURCES]; // raster tile texture UV starting offset for tile\n" + "\n" + "// Note: the raster accessors below are #defines rather than functions to\n" + "// avoid issues with constant integer expressions for array indices\n" + "\n" + "// Adjusts UVs in model space to account for raster tile texture overzooming\n" + "// (applies scale and offset adjustments)\n" + "#define adjustRasterUV(raster_index, uv) " + " ((uv) * u_raster_offsets[raster_index].z + u_raster_offsets[raster_index].xy)\n" + "\n" + "// Returns the UVs of the current model position for a raster sampler\n" + "#define currentRasterUV(raster_index) " + " (adjustRasterUV(raster_index, v_modelpos_base_zoom.xy))\n" + "\n" + "// Returns pixel location in raster tile texture at current model position\n" + "#define currentRasterPixel(raster_index) " + " (currentRasterUV(raster_index) * rasterPixelSize(raster_index))\n" + "\n" + "// Samples a raster tile texture for the current model position\n" + "#define sampleRaster(raster_index) " + " (texture2D(u_rasters[raster_index], currentRasterUV(raster_index)))\n" + "\n" + "// Samples a raster tile texture for a given pixel\n" + "#define sampleRasterAtPixel(raster_index, pixel) " + " (texture2D(u_rasters[raster_index], adjustRasterUV(raster_index, (pixel) / rasterPixelSize(raster_index))))\n" + "\n" + "// Returns size of raster sampler in pixels\n" + "#define rasterPixelSize(raster_index) " + " (u_raster_sizes[raster_index])\n" + "\n" + "#endif\n" + ""; - -shaderSources['gl/shaders/selection_fragment'] = "// Fragment shader for feature selection passes\n" + "// Renders in silhouette according to selection (picking) color, or black if none defined\n" + "\n" + "#ifdef TANGRAM_FEATURE_SELECTION\n" + " varying vec4 v_selection_color;\n" + "#endif\n" + "\n" + "void main (void) {\n" + " #ifdef TANGRAM_FEATURE_SELECTION\n" + " gl_FragColor = v_selection_color;\n" + " #else\n" + " gl_FragColor = vec4(0., 0., 0., 1.);\n" + " #endif\n" + "}\n" + ""; - -shaderSources['gl/shaders/selection_globals'] = "// Vertex attribute + varying for feature selection\n" + "#if defined(TANGRAM_FEATURE_SELECTION) && defined(TANGRAM_VERTEX_SHADER)\n" + " attribute vec4 a_selection_color;\n" + " varying vec4 v_selection_color;\n" + "#endif\n" + ""; - -shaderSources['gl/shaders/selection_vertex'] = "// Selection pass-specific rendering\n" + "#if defined(TANGRAM_FEATURE_SELECTION) && defined(TANGRAM_VERTEX_SHADER)\n" + " if (a_selection_color.rgb == vec3(0.)) {\n" + " // Discard by forcing invalid triangle if we\'re in the feature\n" + " // selection pass but have no selection info\n" + " // TODO: in some cases we may actually want non-selectable features to occlude selectable ones?\n" + " gl_Position = vec4(0., 0., 0., 1.);\n" + " return;\n" + " }\n" + " v_selection_color = a_selection_color;\n" + "#endif\n" + ""; - -shaderSources['gl/shaders/spherical_environment_map'] = "// Spherical environment map\n" + "// Based on: http://www.clicktorelease.com/blog/creating-spherical-environment-mapping-shader\n" + "\n" + "// view: location of camera\n" + "// position: location of current point on surface\n" + "// normal: normal of current point on surface\n" + "// skew: skewing factor (used to compensate for altered vanishing point)\n" + "// envmap: spherical environment map texture\n" + "\n" + "vec4 sphericalEnvironmentMap(vec3 view, vec3 position, vec3 normal, vec2 skew, sampler2D envmap) {\n" + " // Normalized vector from camera to surface\n" + " vec3 eye = normalize(position.xyz - view.xyz);\n" + "\n" + " // Skew\n" + " eye.xy -= skew;\n" + " eye = normalize(eye);\n" + "\n" + " // Reflection of eye off of surface normal\n" + " vec3 r = reflect(eye, normal);\n" + "\n" + " // Map reflected vector onto the surface of a sphere\n" + " r.z += 1.;\n" + " float m = 2. * length(r);\n" + "\n" + " // Adjust xy to account for spherical shape, and center in middle of texture\n" + " vec2 uv = r.xy / m + .5;\n" + "\n" + " // Sample the environment map\n" + " return texture2D(envmap, uv);\n" + "}\n" + ""; - -shaderSources['gl/shaders/spotLight'] = "/*\n" + "\n" + "Expected globals:\n" + "material\n" + "light_accumulator_*\n" + "\n" + "*/\n" + "\n" + "struct SpotLight {\n" + " vec4 ambient;\n" + " vec4 diffuse;\n" + " vec4 specular;\n" + " vec4 position;\n" + "\n" + "#ifdef TANGRAM_POINTLIGHT_ATTENUATION_EXPONENT\n" + " float attenuationExponent;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n" + " float innerRadius;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float outerRadius;\n" + "#endif\n" + "\n" + " vec3 direction;\n" + " float spotCosCutoff;\n" + " float spotExponent;\n" + "};\n" + "\n" + "void calculateLight(in SpotLight _light, in vec3 _eyeToPoint, in vec3 _normal) {\n" + "\n" + " float dist = length(_light.position.xyz - _eyeToPoint);\n" + "\n" + " // Compute vector from surface to light position\n" + " vec3 VP = (_light.position.xyz - _eyeToPoint) / dist;\n" + "\n" + " // normal . light direction\n" + " float nDotVP = clamp(dot(_normal, VP), 0.0, 1.0);\n" + "\n" + " // Attenuation defaults\n" + " float attenuation = 1.0;\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_EXPONENT\n" + " float Rin = 1.0;\n" + " float e = _light.attenuationExponent;\n" + "\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n" + " Rin = _light.innerRadius;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float Rdiff = _light.outerRadius-Rin;\n" + " float d = clamp(max(0.0,dist-Rin)/Rdiff, 0.0, 1.0);\n" + " attenuation = 1.0-(pow(d,e));\n" + " #else\n" + " // If no outer is provide behaves like:\n" + " // https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/\n" + " float d = max(0.0,dist-Rin)/Rin+1.0;\n" + " attenuation = clamp(1.0/(pow(d,e)), 0.0, 1.0);\n" + " #endif\n" + " #else\n" + " float Rin = 0.0;\n" + "\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_INNER_RADIUS\n" + " Rin = _light.innerRadius;\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float Rdiff = _light.outerRadius-Rin;\n" + " float d = clamp(max(0.0,dist-Rin)/Rdiff, 0.0, 1.0);\n" + " attenuation = 1.0-d*d;\n" + " #else\n" + " // If no outer is provide behaves like:\n" + " // https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/\n" + " float d = max(0.0,dist-Rin)/Rin+1.0;\n" + " attenuation = clamp(1.0/d, 0.0, 1.0);\n" + " #endif\n" + " #else\n" + " #ifdef TANGRAM_POINTLIGHT_ATTENUATION_OUTER_RADIUS\n" + " float d = clamp(dist/_light.outerRadius, 0.0, 1.0);\n" + " attenuation = 1.0-d*d;\n" + " #else\n" + " attenuation = 1.0;\n" + " #endif\n" + " #endif\n" + " #endif\n" + "\n" + " // spotlight attenuation factor\n" + " float spotAttenuation = 0.0;\n" + "\n" + " // See if point on surface is inside cone of illumination\n" + " float spotDot = clamp(dot(-VP, normalize(_light.direction)), 0.0, 1.0);\n" + "\n" + " if (spotDot >= _light.spotCosCutoff) {\n" + " spotAttenuation = pow(spotDot, _light.spotExponent);\n" + " }\n" + "\n" + " light_accumulator_ambient += _light.ambient * attenuation * spotAttenuation;\n" + "\n" + " #ifdef TANGRAM_MATERIAL_DIFFUSE\n" + " light_accumulator_diffuse += _light.diffuse * nDotVP * attenuation * spotAttenuation;\n" + " #endif\n" + "\n" + " #ifdef TANGRAM_MATERIAL_SPECULAR\n" + " // Power factor for shiny speculars\n" + " float pf = 0.0;\n" + " if (nDotVP > 0.0) {\n" + " vec3 reflectVector = reflect(-VP, _normal);\n" + " float eyeDotR = max(dot(-normalize(_eyeToPoint), reflectVector), 0.0);\n" + " pf = pow(eyeDotR, material.shininess);\n" + " }\n" + " light_accumulator_specular += _light.specular * pf * attenuation * spotAttenuation;\n" + " #endif\n" + "}\n" + ""; - -shaderSources['gl/shaders/unpack'] = "\n" + "// Unpack normalized shorts back to their original integer values\n" + "#define SHORT(x) (x * 32767.)\n" + "#define UNSIGNED_SHORT(x) (x * 65535.)\n" + "\n" + "// Used for cases where an attribute is stored as a normalized int type,\n" + "// but is a floating point value that needs a range greater than [0, 1] or [-1, 1].\n" + "// The integer value is \"scaled\" to an 8.8 fixed point style integer before it is\n" + "// normalized in the VBO. Used for cases where low precision is suitable for both\n" + "// the integer and fractional portions of the number.\n" + "// Examples are extrusion vectors for dynamic lines, and screen-space size for point sprites.\n" + "#define SCALE_8(x) (x * 256.)\n" + ""; - -shaderSources['styles/points/points_fragment'] = "uniform vec2 u_resolution;\n" + "uniform float u_time;\n" + "uniform vec3 u_map_position;\n" + "uniform vec4 u_tile_origin;\n" + "uniform float u_meters_per_pixel;\n" + "uniform float u_device_pixel_ratio;\n" + "\n" + "uniform mat3 u_normalMatrix;\n" + "uniform mat3 u_inverseNormalMatrix;\n" + "\n" + "uniform sampler2D u_texture;\n" + "\n" + "varying vec4 v_color;\n" + "varying vec2 v_texcoord;\n" + "varying vec4 v_world_position;\n" + "\n" + "#define TANGRAM_NORMAL vec3(0., 0., 1.)\n" + "\n" + "// Alpha discard threshold (substitute for alpha blending)\n" + "#ifndef TANGRAM_ALPHA_DISCARD\n" + "#define TANGRAM_ALPHA_DISCARD 0.5\n" + "#endif\n" + "\n" + "// Alpha fade range for edges of points\n" + "#ifndef TANGRAM_FADE_RANGE\n" + "#define TANGRAM_FADE_RANGE .15\n" + "#endif\n" + "#define TANGRAM_FADE_START (1. - TANGRAM_FADE_RANGE)\n" + "\n" + "#pragma tangram: camera\n" + "#pragma tangram: material\n" + "#pragma tangram: lighting\n" + "#pragma tangram: raster\n" + "#pragma tangram: global\n" + "\n" + "void main (void) {\n" + " // Initialize globals\n" + " #pragma tangram: setup\n" + "\n" + " vec4 color = v_color;\n" + "\n" + " // Apply a texture\n" + " #ifdef TANGRAM_POINT_TEXTURE\n" + " color *= texture2D(u_texture, v_texcoord);\n" + "\n" + " // Manually un-multiply alpha, for cases where texture has pre-multiplied alpha\n" + " #ifdef TANGRAM_UNMULTIPLY_ALPHA\n" + " color.rgb /= max(color.a, 0.001);\n" + " #endif\n" + " // Draw a point\n" + " #else\n" + " // Fade alpha near circle edge\n" + " vec2 uv = v_texcoord * 2. - 1.;\n" + " float point_dist = length(uv);\n" + " color.a = clamp(color.a - (smoothstep(0., TANGRAM_FADE_RANGE, (point_dist - TANGRAM_FADE_START)) / TANGRAM_FADE_RANGE), 0., color.a);\n" + " #endif\n" + "\n" + " // If blending is off, use alpha discard as a lower-quality substitute\n" + " #if !defined(TANGRAM_BLEND_OVERLAY) && !defined(TANGRAM_BLEND_INLAY)\n" + " if (color.a < TANGRAM_ALPHA_DISCARD) {\n" + " discard;\n" + " }\n" + " #endif\n" + "\n" + " #pragma tangram: color\n" + "\n" + " // Fade out when tile is zooming out, e.g. acting as proxy tiles\n" + " // NB: this is mostly done to compensate for text label collision happening at the label\'s 1x zoom. As labels\n" + " // in proxy tiles are scaled down, they begin to overlap, and the fade is a simple way to ease the transition.\n" + " #ifdef TANGRAM_FADE_ON_ZOOM_OUT\n" + " color.a *= clamp(1. - TANGRAM_FADE_ON_ZOOM_OUT_RATE * (u_tile_origin.z - u_map_position.z), 0., 1.);\n" + " #endif\n" + "\n" + " #pragma tangram: filter\n" + "\n" + " gl_FragColor = color;\n" + "}\n" + ""; - -shaderSources['styles/points/points_vertex'] = "uniform vec2 u_resolution;\n" + "uniform float u_time;\n" + "uniform vec3 u_map_position;\n" + "uniform vec4 u_tile_origin;\n" + "uniform float u_tile_proxy_depth;\n" + "uniform float u_meters_per_pixel;\n" + "uniform float u_device_pixel_ratio;\n" + "\n" + "uniform mat4 u_model;\n" + "uniform mat4 u_modelView;\n" + "uniform mat3 u_normalMatrix;\n" + "uniform mat3 u_inverseNormalMatrix;\n" + "\n" + "attribute vec4 a_position;\n" + "attribute vec4 a_shape;\n" + "attribute vec4 a_color;\n" + "attribute vec2 a_texcoord;\n" + "attribute vec2 a_offset;\n" + "\n" + "#define TANGRAM_NORMAL vec3(0., 0., 1.)\n" + "\n" + "varying vec4 v_color;\n" + "varying vec2 v_texcoord;\n" + "varying vec4 v_world_position;\n" + "\n" + "#pragma tangram: camera\n" + "#pragma tangram: material\n" + "#pragma tangram: lighting\n" + "#pragma tangram: raster\n" + "#pragma tangram: global\n" + "\n" + "vec2 rotate2D(vec2 _st, float _angle) {\n" + " return mat2(cos(_angle),-sin(_angle),\n" + " sin(_angle),cos(_angle)) * _st;\n" + "}\n" + "\n" + "void main() {\n" + " // Initialize globals\n" + " #pragma tangram: setup\n" + "\n" + " v_color = a_color;\n" + " v_texcoord = a_texcoord;\n" + "\n" + " // Position\n" + " vec4 position = u_modelView * vec4(SHORT(a_position.xyz), 1.);\n" + "\n" + " // Apply positioning and scaling in screen space\n" + " float zscale = fract(u_map_position.z) * (SCALE_8(a_shape.w) - 1.) + 1.;\n" + " // float zscale = log(fract(u_map_position.z) + 1.) / log(2.) * (a_shape.w - 1.) + 1.;\n" + " vec2 shape = SCALE_8(a_shape.xy) * zscale; //\n" + " vec2 offset = vec2(a_offset.x, -a_offset.y); // flip y to make it point down\n" + " float theta = radians(a_shape.z * 360.);\n" + "\n" + " shape = rotate2D(shape, theta); // apply rotation to vertex\n" + " shape += rotate2D(SHORT(offset), theta); // apply offset on rotated axis (e.g. so line labels follow text axis)\n" + "\n" + " // World coordinates for 3d procedural textures\n" + " v_world_position = u_model * position;\n" + " v_world_position.xy += shape * u_meters_per_pixel;\n" + " v_world_position = wrapWorldPosition(v_world_position);\n" + "\n" + " // Modify position before camera projection\n" + " #pragma tangram: position\n" + "\n" + " cameraProjection(position);\n" + "\n" + " #ifdef TANGRAM_LAYER_ORDER\n" + " // +1 is to keep all layers including proxies > 0\n" + " applyLayerOrder(SHORT(a_position.w) + u_tile_proxy_depth + 1., position);\n" + " #endif\n" + "\n" + " // Apply pixel offset in screen-space\n" + " // Multiply by 2 is because screen is 2 units wide Normalized Device Coords (and u_resolution device pixels wide)\n" + " // Device pixel ratio adjustment is because shape is in logical pixels\n" + " position.xy += shape * position.w * 2. * u_device_pixel_ratio / u_resolution;\n" + "\n" + " gl_Position = position;\n" + "}\n" + ""; - -shaderSources['styles/polygons/polygons_fragment'] = "uniform vec2 u_resolution;\n" + "uniform float u_time;\n" + "uniform vec3 u_map_position;\n" + "uniform vec4 u_tile_origin;\n" + "uniform float u_meters_per_pixel;\n" + "uniform float u_device_pixel_ratio;\n" + "\n" + "uniform mat3 u_normalMatrix;\n" + "uniform mat3 u_inverseNormalMatrix;\n" + "\n" + "varying vec4 v_position;\n" + "varying vec3 v_normal;\n" + "varying vec4 v_color;\n" + "varying vec4 v_world_position;\n" + "\n" + "#define TANGRAM_NORMAL v_normal\n" + "\n" + "#ifdef TANGRAM_TEXTURE_COORDS\n" + " varying vec2 v_texcoord;\n" + "#endif\n" + "\n" + "#ifdef TANGRAM_MODEL_POSITION_BASE_ZOOM_VARYING\n" + " varying vec4 v_modelpos_base_zoom;\n" + "#endif\n" + "\n" + "#if defined(TANGRAM_LIGHTING_VERTEX)\n" + " varying vec4 v_lighting;\n" + "#endif\n" + "\n" + "#pragma tangram: camera\n" + "#pragma tangram: material\n" + "#pragma tangram: lighting\n" + "#pragma tangram: raster\n" + "#pragma tangram: global\n" + "\n" + "void main (void) {\n" + " // Initialize globals\n" + " #pragma tangram: setup\n" + "\n" + " vec4 color = v_color;\n" + " vec3 normal = TANGRAM_NORMAL;\n" + "\n" + " // Apply raster to vertex color\n" + " #ifdef TANGRAM_RASTER_TEXTURE_COLOR\n" + " color *= sampleRaster(0); // multiplied to tint texture color\n" + " #endif\n" + "\n" + " // Apply normal from raster tile\n" + " #ifdef TANGRAM_RASTER_TEXTURE_NORMAL\n" + " normal = normalize(sampleRaster(0).rgb * 2. - 1.);\n" + " #endif\n" + "\n" + " // Normal modification applied here for fragment lighting or no lighting,\n" + " // and in vertex shader for vertex lighting\n" + " #if !defined(TANGRAM_LIGHTING_VERTEX)\n" + " #pragma tangram: normal\n" + " #endif\n" + "\n" + " // Color modification before lighting is applied\n" + " #pragma tangram: color\n" + "\n" + " #if defined(TANGRAM_LIGHTING_FRAGMENT)\n" + " // Calculate per-fragment lighting\n" + " color = calculateLighting(v_position.xyz - u_eye, normal, color);\n" + " #elif defined(TANGRAM_LIGHTING_VERTEX)\n" + " // Apply lighting intensity interpolated from vertex shader\n" + " color *= v_lighting;\n" + " #endif\n" + "\n" + " // Post-processing effects (modify color after lighting)\n" + " #pragma tangram: filter\n" + "\n" + " gl_FragColor = color;\n" + "}\n" + ""; - -shaderSources['styles/polygons/polygons_vertex'] = "uniform vec2 u_resolution;\n" + "uniform float u_time;\n" + "uniform vec3 u_map_position;\n" + "uniform vec4 u_tile_origin;\n" + "uniform float u_tile_proxy_depth;\n" + "uniform float u_meters_per_pixel;\n" + "uniform float u_device_pixel_ratio;\n" + "\n" + "uniform mat4 u_model;\n" + "uniform mat4 u_modelView;\n" + "uniform mat3 u_normalMatrix;\n" + "uniform mat3 u_inverseNormalMatrix;\n" + "\n" + "attribute vec4 a_position;\n" + "attribute vec4 a_color;\n" + "\n" + "// Optional normal attribute, otherwise default to up\n" + "#ifdef TANGRAM_NORMAL_ATTRIBUTE\n" + " attribute vec3 a_normal;\n" + " #define TANGRAM_NORMAL a_normal\n" + "#else\n" + " #define TANGRAM_NORMAL vec3(0., 0., 1.)\n" + "#endif\n" + "\n" + "// Optional dynamic line extrusion\n" + "#ifdef TANGRAM_EXTRUDE_LINES\n" + " // xy: extrusion direction in xy plane\n" + " // z: half-width of line (amount to extrude)\n" + " // w: scaling factor for interpolating width between zooms\n" + " attribute vec4 a_extrude;\n" + "#endif\n" + "\n" + "varying vec4 v_position;\n" + "varying vec3 v_normal;\n" + "varying vec4 v_color;\n" + "varying vec4 v_world_position;\n" + "\n" + "// Optional texture UVs\n" + "#ifdef TANGRAM_TEXTURE_COORDS\n" + " attribute vec2 a_texcoord;\n" + " varying vec2 v_texcoord;\n" + "#endif\n" + "\n" + "// Optional model position varying for tile coordinate zoom\n" + "#ifdef TANGRAM_MODEL_POSITION_BASE_ZOOM_VARYING\n" + " varying vec4 v_modelpos_base_zoom;\n" + "#endif\n" + "\n" + "#if defined(TANGRAM_LIGHTING_VERTEX)\n" + " varying vec4 v_lighting;\n" + "#endif\n" + "\n" + "#pragma tangram: camera\n" + "#pragma tangram: material\n" + "#pragma tangram: lighting\n" + "#pragma tangram: raster\n" + "#pragma tangram: global\n" + "\n" + "void main() {\n" + " // Initialize globals\n" + " #pragma tangram: setup\n" + "\n" + " // Texture UVs\n" + " #ifdef TANGRAM_TEXTURE_COORDS\n" + " v_texcoord = a_texcoord;\n" + " #ifdef TANGRAM_EXTRUDE_LINES\n" + " v_texcoord.y *= TANGRAM_V_SCALE_ADJUST;\n" + " #endif\n" + " #endif\n" + "\n" + " // Pass model position to fragment shader\n" + " #ifdef TANGRAM_MODEL_POSITION_BASE_ZOOM_VARYING\n" + " v_modelpos_base_zoom = modelPositionBaseZoom();\n" + " #endif\n" + "\n" + " // Position\n" + " vec4 position = vec4(SHORT(a_position.xyz), 1.);\n" + "\n" + " #ifdef TANGRAM_EXTRUDE_LINES\n" + " vec2 extrude = SCALE_8(a_extrude.xy);\n" + " float width = SHORT(a_extrude.z);\n" + " float dwdz = SHORT(a_extrude.w);\n" + " float dz = clamp(u_map_position.z - u_tile_origin.z, 0., 1.);\n" + "\n" + " // Interpolate between zoom levels\n" + " width += dwdz * dz;\n" + "\n" + " // Scale pixel dimensions to be consistent in screen space\n" + " width *= exp2(-dz);\n" + "\n" + " // Modify line width before extrusion\n" + " #pragma tangram: width\n" + "\n" + " position.xy += extrude * width;\n" + " #endif\n" + "\n" + " // World coordinates for 3d procedural textures\n" + " v_world_position = wrapWorldPosition(u_model * position);\n" + "\n" + " // Adjust for tile and view position\n" + " position = u_modelView * position;\n" + "\n" + " // Modify position before camera projection\n" + " #pragma tangram: position\n" + "\n" + " // Setup varyings\n" + " v_position = position;\n" + " v_normal = normalize(u_normalMatrix * TANGRAM_NORMAL);\n" + " v_color = a_color;\n" + "\n" + " #if defined(TANGRAM_LIGHTING_VERTEX)\n" + " // Vertex lighting\n" + " vec3 normal = v_normal;\n" + "\n" + " // Modify normal before lighting\n" + " #pragma tangram: normal\n" + "\n" + " // Pass lighting intensity to fragment shader\n" + " v_lighting = calculateLighting(position.xyz - u_eye, normal, vec4(1.));\n" + " #endif\n" + "\n" + " // Camera\n" + " cameraProjection(position);\n" + "\n" + " // +1 is to keep all layers including proxies > 0\n" + " applyLayerOrder(SHORT(a_position.w) + u_tile_proxy_depth + 1., position);\n" + "\n" + " gl_Position = position;\n" + "}\n" + ""; - -exports["default"] = shaderSources; -module.exports = exports["default"]; - -},{}],209:[function(_dereq_,module,exports){ +},{"../utils/log":252,"./extensions":205,"./glsl":206,"./texture":209,"babel-runtime/core-js/get-iterator":2,"babel-runtime/core-js/object/assign":6,"babel-runtime/helpers/class-call-check":18,"babel-runtime/helpers/create-class":19,"babel-runtime/helpers/interop-require-default":23,"babel-runtime/helpers/to-consumable-array":25,"gl-shader-errors":156,"strip-comments":190}],209:[function(_dereq_,module,exports){ // Texture management 'use strict'; @@ -16113,6 +16424,10 @@ Object.defineProperty(exports, '__esModule', { value: true }); +var _utilsLog = _dereq_('../utils/log'); + +var _utilsLog2 = _interopRequireDefault(_utilsLog); + var _utilsUtils = _dereq_('../utils/utils'); var _utilsUtils2 = _interopRequireDefault(_utilsUtils); @@ -16125,10 +16440,6 @@ var _utilsWorker_broker = _dereq_('../utils/worker_broker'); var _utilsWorker_broker2 = _interopRequireDefault(_utilsWorker_broker); -var _loglevel = _dereq_('loglevel'); - -var _loglevel2 = _interopRequireDefault(_loglevel); - // GL texture wrapper object for keeping track of a global set of textures, keyed by a unique user-defined name var Texture = (function () { @@ -16173,7 +16484,7 @@ var Texture = (function () { Texture.texture_configs[this.name] = _Object$assign({ name: name }, options); this.load(options); - _loglevel2['default'].trace('creating Texture ' + this.name); + (0, _utilsLog2['default'])('trace', 'creating Texture ' + this.name); } // Static/class methods and state @@ -16184,7 +16495,7 @@ var Texture = (function () { key: 'destroy', value: function destroy() { if (this.retain_count > 0) { - _loglevel2['default'].error('Texture \'' + this.name + '\': destroying texture with retain count of \'' + this.retain_count + '\''); + (0, _utilsLog2['default'])('error', 'Texture \'' + this.name + '\': destroying texture with retain count of \'' + this.retain_count + '\''); return; } @@ -16197,7 +16508,7 @@ var Texture = (function () { this.data = null; delete Texture.textures[this.name]; this.valid = false; - _loglevel2['default'].trace('destroying Texture ' + this.name); + (0, _utilsLog2['default'])('trace', 'destroying Texture ' + this.name); } }, { key: 'retain', @@ -16208,7 +16519,7 @@ var Texture = (function () { key: 'release', value: function release() { if (this.retain_count <= 0) { - _loglevel2['default'].error('Texture \'' + this.name + '\': releasing texture with retain count of \'' + this.retain_count + '\''); + (0, _utilsLog2['default'])('error', 'Texture \'' + this.name + '\': releasing texture with retain count of \'' + this.retain_count + '\''); } this.retain_count--; @@ -16218,19 +16529,22 @@ var Texture = (function () { } }, { key: 'bind', - value: function bind(unit) { + value: function bind() { + var unit = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + if (!this.valid) { return; } - if (typeof unit === 'number') { - if (Texture.activeUnit !== unit) { - this.gl.activeTexture(this.gl.TEXTURE0 + unit); - Texture.activeUnit = unit; - } + + if (Texture.activeUnit !== unit) { + this.gl.activeTexture(this.gl.TEXTURE0 + unit); + Texture.activeUnit = unit; + Texture.boundTexture = null; // texture must be re-bound when unit changes } - if (Texture.activeTexture !== this.texture) { + + if (Texture.boundTexture !== this.texture) { this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture); - Texture.activeTexture = this.texture; + Texture.boundTexture = this.texture; } } }, { @@ -16287,7 +16601,7 @@ var Texture = (function () { _this2.setElement(image, options); } catch (e) { _this2.loaded = false; - _loglevel2['default'].warn('Texture \'' + _this2.name + '\': failed to load url: \'' + _this2.source + '\'', e, options); + (0, _utilsLog2['default'])('warn', 'Texture \'' + _this2.name + '\': failed to load url: \'' + _this2.source + '\'', e, options); Texture.trigger('warning', { message: 'Failed to load texture from ' + _this2.source, error: e, texture: options }); } @@ -16297,11 +16611,17 @@ var Texture = (function () { image.onerror = function (e) { // Warn and resolve on error _this2.loaded = false; - _loglevel2['default'].warn('Texture \'' + _this2.name + '\': failed to load url: \'' + _this2.source + '\'', e, options); + (0, _utilsLog2['default'])('warn', 'Texture \'' + _this2.name + '\': failed to load url: \'' + _this2.source + '\'', e, options); Texture.trigger('warning', { message: 'Failed to load texture from ' + _this2.source, error: e, texture: options }); resolve(_this2); }; - image.crossOrigin = 'anonymous'; + + // Safari has a bug loading data-URL images with CORS enabled, so it must be disabled in that case + // https://bugs.webkit.org/show_bug.cgi?id=123978 + if (!(_utilsUtils2['default'].isSafari() && _this2.source.slice(0, 5) === 'data:')) { + image.crossOrigin = 'anonymous'; + } + image.src = _this2.source; }); return this.loading; @@ -16319,6 +16639,11 @@ var Texture = (function () { this.source = data; this.source_type = 'data'; + // Convert regular array to typed array + if (Array.isArray(this.source)) { + this.source = new Uint8Array(this.source); + } + this.update(options); this.setFiltering(options); @@ -16348,7 +16673,7 @@ var Texture = (function () { this.loaded = false; var msg = 'the \'element\' parameter (`element: ' + JSON.stringify(el) + '`) must be a CSS '; msg += 'selector string, or a , or